model.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  1. <?php
  2. /**
  3. * The model file of mr module of ZenTaoPMS.
  4. *
  5. * @copyright Copyright 2009-2023 禅道软件(青岛)有限公司(ZenTao Software (Qingdao) Co., Ltd. www.cnezsoft.com)
  6. * @license ZPL(http://zpl.pub/page/zplv12.html) or AGPL(https://www.gnu.org/licenses/agpl-3.0.en.html)
  7. * @author dingguodong <dingguodong@easycorp.ltd>
  8. * @package mr
  9. * @link https://www.zentao.net
  10. * @property gitlabModel $gitlab
  11. */
  12. class mrModel extends model
  13. {
  14. public $moduleName = 'mr';
  15. public function __construct($appName = '')
  16. {
  17. parent::__construct($appName);
  18. if($this->app->rawModule == 'pullreq') $this->moduleName = 'pullreq';
  19. }
  20. /**
  21. * 获取合并请求列表.
  22. * Get MR list of gitlab project.
  23. *
  24. * @param string $mode
  25. * @param string $param
  26. * @param string $orderBy
  27. * @param array $filterProjects
  28. * @param int $repoID
  29. * @param int $objectID
  30. * @param object $pager
  31. * @access public
  32. * @return array
  33. */
  34. public function getList($mode = 'all', $param = 'all', $orderBy = 'id_desc', $filterProjects = array(), $repoID = 0, $objectID = 0, $pager = null)
  35. {
  36. $filterProjectSql = '';
  37. if(!$this->app->user->admin && !empty($filterProjects))
  38. {
  39. foreach($filterProjects as $hostID => $projectID)
  40. {
  41. $filterProjectSql .= "(hostID = {$hostID} AND sourceProject = '{$projectID}') OR ";
  42. }
  43. if($filterProjectSql) $filterProjectSql = '(' . substr($filterProjectSql, 0, -3) . ')'; // Remove last or.
  44. }
  45. if($this->app->tab == 'project')
  46. {
  47. $executionIdList = $this->loadModel('execution')->fetchExecutionList($objectID, 'all');
  48. if(!empty($executionIdList)) $objectID = array_merge(array_keys($executionIdList), array($objectID));
  49. }
  50. return $this->dao->select('*')->from(TABLE_MR)
  51. ->where('deleted')->eq('0')
  52. ->beginIF($mode == 'status' && $param != 'all')->andWhere('status')->eq($param)->fi()
  53. ->beginIF($mode == 'assignee' && $param != 'all')->andWhere('assignee')->eq($param)->fi()
  54. ->beginIF($mode == 'creator' && $param != 'all')->andWhere('createdBy')->eq($param)->fi()
  55. ->beginIF($filterProjectSql)->andWhere($filterProjectSql)->fi()
  56. ->beginIF($repoID)->andWhere('repoID')->eq($repoID)->fi()
  57. ->beginIF($this->moduleName == 'mr')->andWhere('isFlow')->eq('0')->fi()
  58. ->beginIF($this->moduleName == 'pullreq')->andWhere('isFlow')->eq('1')->fi()
  59. ->beginIF($objectID && $this->moduleName == 'mr')->andWhere('executionID')->in($objectID)->fi()
  60. ->orderBy($orderBy)
  61. ->page($pager)
  62. ->fetchAll('id');
  63. }
  64. /**
  65. * 根据代码库ID获取合并请求列表.
  66. * Get MR list by repoID.
  67. *
  68. * @access public
  69. * @return array
  70. * @param int $repoID
  71. */
  72. public function getPairs($repoID)
  73. {
  74. return $this->dao->select('id,title')
  75. ->from(TABLE_MR)
  76. ->where('deleted')->eq('0')
  77. ->andWhere('repoID')->eq($repoID)
  78. ->orderBy('id')
  79. ->fetchPairs('id', 'title');
  80. }
  81. /**
  82. * 获取Gitea服务器的项目.
  83. * Get gitea projects.
  84. *
  85. * @param int $hostID
  86. * @access public
  87. * @return array
  88. */
  89. public function getGiteaProjects($hostID = 0)
  90. {
  91. $projects = $this->loadModel('gitea')->apiGetProjects($hostID);
  92. return array($hostID => helper::arrayColumn($projects, null, 'full_name'));
  93. }
  94. /**
  95. * 获取Gogs服务器的项目.
  96. * Get gogs projects.
  97. *
  98. * @param int $hostID
  99. * @access public
  100. * @return array
  101. */
  102. public function getGogsProjects($hostID = 0)
  103. {
  104. $projects = $this->loadModel('gogs')->apiGetProjects($hostID);
  105. return array($hostID => helper::arrayColumn($projects, null, 'full_name'));
  106. }
  107. /**
  108. * 获取Gitlab服务器的项目.
  109. * Get gitlab projects.
  110. *
  111. * @param int $hostID
  112. * @param array $projectIdList
  113. * @access public
  114. * @return array
  115. */
  116. public function getGitlabProjects($hostID = 0, $projectIdList = array())
  117. {
  118. if(!$this->app->user->admin)
  119. {
  120. $gitlabUsers = $this->loadModel('pipeline')->getProviderPairsByAccount('gitlab');
  121. if(!isset($gitlabUsers[$hostID])) return array();
  122. }
  123. $minProject = $maxProject = 0;
  124. /* Mysql string to int. */
  125. $MR = $this->dao->select('min(CAST(sourceProject AS DECIMAL)) as minSource, MAX(CAST(sourceProject AS DECIMAL)) as maxSource,MIN(CAST(targetProject AS DECIMAL)) as minTarget,MAX(CAST(targetProject AS DECIMAL)) as maxTarget')->from(TABLE_MR)
  126. ->where('deleted')->eq('0')
  127. ->andWhere('hostID')->eq($hostID)
  128. ->beginIF($projectIdList)->andWhere('sourceProject', true)->in($projectIdList)
  129. ->orWhere('targetProject')->in($projectIdList)
  130. ->markRight(1)
  131. ->fi()
  132. ->fetch();
  133. if(empty($MR->minSource) && empty($MR->minTarget)) return array();
  134. $minProject = min($MR->minSource, $MR->minTarget);
  135. $maxProject = max($MR->maxSource, $MR->maxTarget);
  136. /* If not an administrator, need to obtain group member information. */
  137. $groupIDList = array(0 => 0);
  138. $this->loadModel('gitlab');
  139. if(!$this->app->user->admin)
  140. {
  141. $groups = $this->gitlab->apiGetGroups($hostID, 'name_asc', 'reporter');
  142. foreach($groups as $group) $groupIDList[] = $group->id;
  143. }
  144. $allProjectPairs = array();
  145. $allProjects = $this->gitlab->apiGetProjects($hostID, 'false', (int)$minProject, (int)$maxProject);
  146. foreach($allProjects as $project)
  147. {
  148. if($projectIdList && !in_array($project->id, $projectIdList)) continue;
  149. if(!$this->gitlab->checkUserAccess($hostID, 0, $project, $groupIDList, 'reporter')) continue;
  150. $project->isDeveloper = $this->gitlab->checkUserAccess($hostID, 0, $project, $groupIDList, 'developer');
  151. $allProjectPairs[$hostID][$project->id] = $project;
  152. }
  153. return $allProjectPairs;
  154. }
  155. /**
  156. * 创建合并请求。
  157. * Create MR function.
  158. *
  159. * @param object $MR
  160. * @access public
  161. * @return array
  162. */
  163. public function create($MR)
  164. {
  165. $result = $this->checkSameOpened($MR->hostID, $MR->sourceProject, $MR->sourceBranch, $MR->targetProject, $MR->targetBranch);
  166. if($result['result'] == 'fail') return $result;
  167. $MRID = $this->insertMr($MR);
  168. if(dao::isError()) return array('result' => 'fail', 'message' => dao::getError());
  169. $this->loadModel('action')->create($this->moduleName, $MRID, 'opened');
  170. if($MR->needCI && $MR->jobID) $this->execJob($MRID, (int)$MR->jobID);
  171. $rawMR = $this->apiCreateMR($MR->hostID, $MR);
  172. /**
  173. * Another open merge request already exists for this source branch.
  174. * The type of variable `$rawMR->message` is array.
  175. */
  176. if(isset($rawMR->message) and !isset($rawMR->iid))
  177. {
  178. $this->dao->delete()->from(TABLE_MR)->where('id')->eq($MRID)->exec();
  179. $errorMessage = $this->convertApiError($rawMR->message);
  180. return array('result' => 'fail', 'message' => sprintf($this->lang->mr->apiError->createMR, $errorMessage));
  181. }
  182. /* Create MR failed. */
  183. if(!isset($rawMR->iid))
  184. {
  185. $this->dao->delete()->from(TABLE_MR)->where('id')->eq($MRID)->exec();
  186. return array('result' => 'fail', 'message' => $this->lang->mr->createFailedFromAPI);
  187. }
  188. /* Create a todo item for this MR. */
  189. if(empty($MR->jobID)) $this->apiCreateMRTodo($MR->hostID, $MR->targetProject, $rawMR->iid);
  190. $newMR = new stdclass();
  191. $newMR->mriid = $rawMR->iid;
  192. $newMR->status = $rawMR->state == 'open' ? 'opened' : $rawMR->state;
  193. $newMR->mergeStatus = $rawMR->merge_status;
  194. $this->dao->update(TABLE_MR)->data($newMR)->where('id')->eq($MRID)->autoCheck()->exec();
  195. /* Link stories,bugs and tasks. */
  196. $MR->id = $MRID;
  197. $MR->mriid = $newMR->mriid;
  198. $this->linkObjects($MR);
  199. if(dao::isError()) return array('result' => 'fail', 'message' => dao::getError());
  200. $linkParams = $this->app->tab == 'execution' || $this->app->tab == 'project' ? "repoID=0&mode=status&param=opened&objectID={$MR->executionID}" : "repoID={$MR->repoID}";
  201. return array('result' => 'success', 'message' => $this->lang->saveSuccess, 'load' => helper::createLink($this->moduleName, 'browse', $linkParams));
  202. }
  203. /**
  204. * 通过API创建合并请求。
  205. * Create MR function by api.
  206. *
  207. * @access public
  208. * @return bool|int
  209. */
  210. public function apiCreate()
  211. {
  212. $postData = fixer::input('post')->get();
  213. $repo = $this->dao->findByID($postData->repoID)->from(TABLE_REPO)->fetch();
  214. if(empty($repo))
  215. {
  216. dao::$errors[] = 'No matched gitlab.';
  217. return false;
  218. }
  219. /* Process and insert mr data. */
  220. $MR = new stdClass();
  221. $MR->hostID = (int)$repo->serviceHost;
  222. $MR->sourceProject = $repo->serviceProject;
  223. $MR->sourceBranch = $postData->sourceBranch;
  224. $MR->targetProject = $repo->serviceProject;
  225. $MR->targetBranch = $postData->targetBranch;
  226. $MR->diffs = $postData->diffs;
  227. $MR->title = $this->lang->mr->common . ' ' . $postData->sourceBranch . $this->lang->mr->to . $postData->targetBranch ;
  228. $MR->repoID = $repo->id;
  229. $MR->jobID = $postData->jobID;
  230. $MR->status = 'opened';
  231. $MR->synced = '0';
  232. $MR->needCI = '1';
  233. $MR->hasNoConflict = $postData->mergeStatus ? '0' : '1';
  234. $MR->mergeStatus = $postData->mergeStatus ? 'can_be_merged' : 'cannot_be_merged';
  235. $MR->createdBy = $this->app->user->account;
  236. $MR->createdDate = date('Y-m-d H:i:s');
  237. if($MR->sourceProject == $MR->targetProject && $MR->sourceBranch == $MR->targetBranch)
  238. {
  239. dao::$errors[] = $this->lang->mr->errorLang[1];
  240. return false;
  241. }
  242. $result = $this->checkSameOpened($MR->hostID, (string)$MR->sourceProject, $MR->sourceBranch, (string)$MR->targetProject, $MR->targetBranch);
  243. if($result['result'] == 'fail')
  244. {
  245. dao::$errors[] = $result['message'];
  246. return false;
  247. }
  248. $MRID = $this->insertMr($MR);
  249. if(dao::isError()) return false;
  250. $this->loadModel('action')->create($this->moduleName, $MRID, 'opened');
  251. /* Exec Job */
  252. if($MR->hasNoConflict == '0' && $MR->mergeStatus == 'can_be_merged' && $MR->jobID) $this->execJob($MRID, (int)$MR->jobID);
  253. return $MRID;
  254. }
  255. /**
  256. * 更新合并请求。
  257. * Edit MR function.
  258. *
  259. * @param int $MRID
  260. * @param object $MR
  261. * @access public
  262. * @return array
  263. */
  264. public function update($MRID, $MR)
  265. {
  266. $oldMR = $this->fetchByID($MRID);
  267. $diff = array_diff_assoc((array)$oldMR, (array)$MR);
  268. if(!$oldMR) return array('result' => 'fail', 'message' => $this->lang->mr->notFound);
  269. /* The source and target branches cannot be the same. */
  270. if($oldMR->sourceBranch == $MR->targetBranch ) return array('result' => 'fail', 'message' => $this->lang->mr->errorLang[1]);
  271. $this->dao->update(TABLE_MR)->data($MR)->checkIF($MR->needCI, 'jobID', 'notempty');
  272. if(dao::isError()) return array('result' => 'fail', 'message' => dao::getError());
  273. /* Exec Job */
  274. $needExecJob = isset($diff['targetBranch']) || isset($diff['jobID']) ? true : false;
  275. if($needExecJob && isset($MR->jobID) && $MR->jobID)
  276. {
  277. $this->execJob($MRID, (int)$MR->jobID);
  278. if(dao::isError()) return array('result' => 'fail', 'message' => implode("\n", dao::getError()));
  279. }
  280. /* Known issue: `reviewer_ids` takes no effect. */
  281. $rawMR = $this->apiUpdateMR($oldMR, $MR);
  282. if(!isset($rawMR->id) and isset($rawMR->message))
  283. {
  284. $errorMessage = $this->convertApiError($rawMR->message);
  285. return array('result' => 'fail', 'message' => $errorMessage);
  286. }
  287. /* Update MR in Zentao database. */
  288. $this->dao->update(TABLE_MR)->data($MR, $this->config->mr->edit->skippedFields)
  289. ->where('id')->eq($MRID)
  290. ->batchCheck($this->config->mr->edit->requiredFields, 'notempty')
  291. ->autoCheck()
  292. ->exec();
  293. if(dao::isError()) return array('result' => 'fail', 'message' => dao::getError());
  294. $MR = $this->fetchByID($MRID);
  295. $this->linkObjects($MR);
  296. $actionID = $this->loadModel('action')->create($this->moduleName, $MRID, 'edited');
  297. $changes = common::createChanges($oldMR, $MR);
  298. if(!empty($changes))
  299. {
  300. foreach($changes as &$change) if($change['field'] == 'assignee') $change['field'] = 'reviewer';
  301. $this->action->logHistory($actionID, $changes);
  302. }
  303. $this->createMRLinkedAction($MRID, 'edit' . $this->moduleName, $MR->editedDate);
  304. if(dao::isError()) return array('result' => 'fail', 'message' => dao::getError());
  305. if($this->session->{$this->app->tab}) $MR->executionID = $this->session->{$this->app->tab};
  306. $linkParams = $this->app->tab == 'execution' || $this->app->tab == 'project' ? "repoID=0&mode=status&param=opened&objectID={$MR->executionID}" : "repoID={$MR->repoID}";
  307. return array('result' => 'success', 'message' => $needExecJob ? $this->lang->mr->triggeredCI : $this->lang->saveSuccess, 'load' => helper::createLink($this->moduleName, 'browse', $linkParams));
  308. }
  309. /**
  310. * 更新合并请求关联信息。
  311. * Update MR linked info.
  312. *
  313. * @param int $MRID
  314. * @param string $action createmr|editmr|removemr
  315. * @param string $actionDate
  316. * @access public
  317. * @return bool
  318. */
  319. public function createMRLinkedAction($MRID, $action, $actionDate = '')
  320. {
  321. if(empty($actionDate)) $actionDate = helper::now();
  322. $MRAction = $actionDate . '::' . $this->app->user->account . '::' . helper::createLink($this->moduleName, 'view', "mr={$MRID}");
  323. $this->loadModel('action');
  324. foreach(array('story', 'task', 'bug') as $objectType)
  325. {
  326. $linkedObjects = $this->mrTao->getLinkedObjectPairs($MRID, $objectType);
  327. foreach($linkedObjects as $objectID) $this->action->create($objectType, $objectID, $action, '', $MRAction);
  328. }
  329. return !dao::isError();
  330. }
  331. /**
  332. * 通过API同步合并请求。
  333. * Sync MR from GitLab API to Zentao database.
  334. *
  335. * @param object $MR
  336. * @access public
  337. * @return object|false
  338. */
  339. public function apiSyncMR($MR)
  340. {
  341. $rawMR = $this->apiGetSingleMR($MR->repoID, $MR->mriid);
  342. /* Sync MR in ZenTao database whatever status of MR in GitLab. */
  343. if(isset($rawMR->iid))
  344. {
  345. $newMR = new stdclass();
  346. $gitUsers = $this->loadModel('pipeline')->getUserBindedPairs($MR->hostID, $rawMR->gitService, 'openID,account');
  347. foreach($this->config->mr->maps->sync as $syncField => $config)
  348. {
  349. $value = '';
  350. list($field, $optionType, $options) = explode('|', $config);
  351. if($optionType == 'field') $value = $rawMR->$field;
  352. if($optionType == 'userPairs')
  353. {
  354. $gitUserID = '';
  355. if(isset($rawMR->$field))
  356. {
  357. $values = $rawMR->$field;
  358. if(isset($values[0])) $gitUserID = $values[0]->$options;
  359. }
  360. $value = zget($gitUsers, $gitUserID, '');
  361. }
  362. if($value) $newMR->$syncField = $value;
  363. }
  364. /* For compatibility with PHP 5.4 . */
  365. $condition = (array)$newMR;
  366. if(empty($condition)) return false;
  367. /* Update compile status of current MR object */
  368. if(isset($MR->needCI) && $MR->needCI == '1')
  369. {
  370. $compile = $this->loadModel('compile')->getByID($MR->id);
  371. $newMR->compileStatus = $compile ? $compile->status : 'failed';
  372. }
  373. /* Update MR in Zentao database. */
  374. $newMR->editedBy = $this->app->user->account;
  375. $newMR->editedDate = helper::now();
  376. $this->dao->update(TABLE_MR)->data($newMR)
  377. ->where('id')->eq($MR->id)
  378. ->exec();
  379. }
  380. return $this->fetchByID($MR->id);
  381. }
  382. /**
  383. * 通过API批量同步合并请求。
  384. * Batch Sync GitLab MR Database.
  385. *
  386. * @param array $MRList
  387. * @access public
  388. * @return array
  389. */
  390. public function batchSyncMR($MRList)
  391. {
  392. if(empty($MRList)) return array();
  393. foreach($MRList as $key => $MR)
  394. {
  395. if($MR->status != 'opened') continue;
  396. $MRList[$key] = $this->apiSyncMR($MR);
  397. }
  398. return $MRList;
  399. }
  400. /**
  401. * 创建远程合并请求。
  402. * Create MR by API.
  403. *
  404. * @param int $hostID
  405. * @param object $MR
  406. * @access public
  407. * @return object|null
  408. */
  409. public function apiCreateMR($hostID, $MR)
  410. {
  411. $repo = $this->loadModel('repo')->getByID($MR->repoID);
  412. if(!$repo) return null;
  413. $openID = $this->loadModel('pipeline')->getOpenIdByAccount($hostID, strtolower($repo->SCM), $this->app->user->account);
  414. $assignee = '';
  415. if($MR->assignee) $assignee = $this->pipeline->getOpenIdByAccount($hostID, strtolower($repo->SCM), $MR->assignee);
  416. $scm = $this->app->loadClass('scm');
  417. $scm->setEngine($repo);
  418. $result = $scm->createMR($MR, $openID, $assignee);
  419. if(!empty($result->message)) $result->message = $this->convertApiError($result->message);
  420. return $result;
  421. }
  422. /**
  423. * 通过API查看是否有相同的合并请求。
  424. * Get same opened mr by api.
  425. *
  426. * @param int $hostID
  427. * @param string $sourceProject
  428. * @param string $sourceBranch
  429. * @param string $targetProject
  430. * @param string $targetBranch
  431. * @access public
  432. * @return object|null
  433. */
  434. public function apiGetSameOpened($hostID, $sourceProject, $sourceBranch, $targetProject, $targetBranch)
  435. {
  436. if(empty($hostID) || empty($sourceProject) || empty($sourceBranch) || empty($targetProject) || empty($targetBranch)) return null;
  437. $url = sprintf($this->loadModel('gitlab')->getApiRoot((int)$hostID), "/projects/{$sourceProject}/merge_requests") . "&state=opened&source_branch={$sourceBranch}&target_branch={$targetBranch}";
  438. $response = json_decode(commonModel::http($url));
  439. if($response)
  440. {
  441. foreach($response as $MR)
  442. {
  443. if(empty($MR->source_project_id) || empty($MR->target_project_id)) return null;
  444. if($MR->source_project_id == $sourceProject && $MR->target_project_id == $targetProject) return $MR;
  445. }
  446. }
  447. return null;
  448. }
  449. /**
  450. * 通过API获取单个合并请求。
  451. * Get single MR by API.
  452. *
  453. * @param int $repoID
  454. * @param int $MRID
  455. * @access public
  456. * @return object|null
  457. */
  458. public function apiGetSingleMR($repoID, $MRID)
  459. {
  460. $repo = $this->loadModel('repo')->getByID($repoID);
  461. if(!$repo) return null;
  462. $scm = $this->app->loadClass('scm');
  463. $scm->setEngine($repo);
  464. $MR = $scm->getSingleMR($MRID);
  465. if($MR)
  466. {
  467. if(!isset($MR->flow)) $MR->flow = 0;
  468. $MR->gitService = strtolower($repo->SCM);
  469. if($MR->state == 'open') $MR->state = 'opened';
  470. }
  471. return $MR;
  472. }
  473. /**
  474. * 通过API获取合并请求的提交信息。
  475. * Get MR commits by API.
  476. *
  477. * @param int $hostID
  478. * @param string $projectID targetProject
  479. * @param int $MRID
  480. * @access public
  481. * @return array|null
  482. */
  483. public function apiGetMRCommits($hostID, $projectID, $MRID)
  484. {
  485. $host = $this->loadModel('pipeline')->getByID($hostID);
  486. $apiRoot = $this->loadModel($host->type)->getApiRoot($hostID);
  487. if($host->type == 'gitlab')
  488. {
  489. $url = sprintf($apiRoot, "/projects/$projectID/merge_requests/$MRID/commits");
  490. }
  491. else
  492. {
  493. $url = sprintf($apiRoot, "/repos/$projectID/pulls/$MRID/commits");
  494. }
  495. return (array)json_decode(commonModel::http($url, null, array(), is_object($apiRoot) ? $apiRoot->header : array()));
  496. }
  497. /**
  498. * 通过API更新合并请求。
  499. * Update MR by API.
  500. *
  501. * @param object $oldMR
  502. * @param object $MR
  503. * @access public
  504. * @return object|null
  505. */
  506. public function apiUpdateMR($oldMR, $MR)
  507. {
  508. $host = $this->loadModel('pipeline')->getByID($oldMR->hostID);
  509. if(!$host) return null;
  510. if(!empty($MR->assignee)) $assignee = $this->pipeline->getOpenIdByAccount($host->id, $host->type, $MR->assignee);
  511. $apiRoot = $this->loadModel($host->type)->getApiRoot($host->id);
  512. $MRObject = new stdclass();
  513. $MRObject->title = $MR->title;
  514. if($host->type == 'gitlab')
  515. {
  516. if(isset($MR->targetBranch)) $MRObject->target_branch = zget($MR, 'targetBranch', $oldMR->targetBranch);
  517. if(isset($MR->description)) $MRObject->description = $MR->description;
  518. if(isset($MR->remove_source_branch)) $MRObject->remove_source_branch = $MR->removeSourceBranch == '1' ? true : false;
  519. if(isset($MR->squash)) $MRObject->squash = $MR->squash == '1' ? 1 : 0;
  520. if(!empty($assignee)) $MRObject->assignee_ids = $assignee;
  521. $url = sprintf($apiRoot, "/projects/{$oldMR->sourceProject}/merge_requests/{$oldMR->mriid}");
  522. return json_decode(commonModel::http($url, $MRObject, array(CURLOPT_CUSTOMREQUEST => 'PUT')));
  523. }
  524. else
  525. {
  526. if(isset($MR->targetBranch)) $MRObject->base = zget($MR, 'targetBranch', $oldMR->targetBranch);
  527. if(isset($MR->description)) $MRObject->body = $MR->description;
  528. if(!empty($assignee)) $MRObject->assignee = $assignee;
  529. $url = sprintf($apiRoot, "/repos/{$oldMR->sourceProject}/pulls/{$oldMR->mriid}");
  530. $mergeResult = json_decode(commonModel::http($url, $MRObject, array(), array(), 'json', 'PATCH'));
  531. if(isset($mergeResult->number)) $mergeResult->iid = $host->type == 'gitea' ? $mergeResult->number : $mergeResult->id;
  532. if(isset($mergeResult->mergeable))
  533. {
  534. if($mergeResult->mergeable) $mergeResult->merge_status = 'can_be_merged';
  535. if(!$mergeResult->mergeable) $mergeResult->merge_status = 'cannot_be_merged';
  536. }
  537. if(isset($mergeResult->state) && $mergeResult->state == 'open') $mergeResult->state = 'opened';
  538. if(isset($mergeResult->merged) && $mergeResult->merged) $mergeResult->state = 'merged';
  539. return $mergeResult;
  540. }
  541. }
  542. /**
  543. * 通过API删除合并请求。
  544. * Delete MR by API.
  545. *
  546. * @param int $hostID
  547. * @param string $projectID
  548. * @param int $MRID
  549. * @access public
  550. * @return object|null
  551. */
  552. public function apiDeleteMR($hostID, $projectID, $MRID)
  553. {
  554. $host = $this->loadModel('pipeline')->getByID($hostID);
  555. if(!$host) return null;
  556. if($host->type == 'gitlab')
  557. {
  558. $url = sprintf($this->loadModel('gitlab')->getApiRoot($hostID), "/projects/$projectID/merge_requests/$MRID");
  559. return json_decode(commonModel::http($url, null, array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  560. }
  561. $repoID = $this->dao->select('repoID')->from(TABLE_MR)
  562. ->where('hostID')->eq($hostID)
  563. ->andWhere('sourceProject')->eq($projectID)
  564. ->andWhere('mriid')->eq($MRID)
  565. ->andWhere('deleted')->eq('0')
  566. ->fetch('repoID');
  567. $rowMR = $this->apiGetSingleMR((int)$repoID, $MRID);
  568. if($rowMR && $rowMR->state == 'opened')
  569. {
  570. $apiRoot = $this->loadModel($host->type)->getApiRoot($hostID);
  571. $header = is_string($apiRoot) ? array() : $apiRoot->header;
  572. if(is_object($apiRoot)) $apiRoot = $apiRoot->url;
  573. $api = "/repos/$projectID/pulls/$MRID";
  574. return json_decode(commonModel::http(sprintf($apiRoot, $api), array('state' => 'closed'), array(), $header, 'json', 'PATCH'));
  575. }
  576. return null;
  577. }
  578. /**
  579. * 通过API关闭合并请求。
  580. * Close MR by API.
  581. *
  582. * @param int $hostID
  583. * @param string $projectID
  584. * @param int $MRID
  585. * @access public
  586. * @return object|null
  587. */
  588. public function apiCloseMR($hostID, $projectID, $MRID)
  589. {
  590. $host = $this->loadModel('pipeline')->getByID($hostID);
  591. if(!$host) return null;
  592. if($host->type == 'gitlab')
  593. {
  594. $url = sprintf($this->loadModel('gitlab')->getApiRoot($hostID), "/projects/$projectID/merge_requests/$MRID") . '&state_event=close';
  595. return json_decode(commonModel::http($url, null, array(CURLOPT_CUSTOMREQUEST => 'PUT')));
  596. }
  597. else
  598. {
  599. return $this->apiDeleteMR($hostID, $projectID, $MRID);
  600. }
  601. }
  602. /**
  603. * 通过API重新打开合并请求。
  604. * Reopen MR by API.
  605. *
  606. * @param int $hostID
  607. * @param string $projectID
  608. * @param int $MRID
  609. * @access public
  610. * @return object|null
  611. */
  612. public function apiReopenMR($hostID, $projectID, $MRID)
  613. {
  614. $host = $this->loadModel('pipeline')->getByID($hostID);
  615. if(!$host) return null;
  616. $apiRoot = $this->loadModel($host->type)->getApiRoot($hostID);
  617. if($host->type == 'gitlab')
  618. {
  619. $url = sprintf($apiRoot, "/projects/$projectID/merge_requests/$MRID") . '&state_event=reopen';
  620. return json_decode(commonModel::http($url, null, array(CURLOPT_CUSTOMREQUEST => 'PUT')));
  621. }
  622. else
  623. {
  624. $url = sprintf($apiRoot, "/repos/$projectID/pulls/$MRID");
  625. return json_decode(commonModel::http($url, array('state' => 'open'), array(), array(), 'json', 'PATCH'));
  626. }
  627. }
  628. /**
  629. * 通过API接受合并请求。
  630. * Accept MR by API.
  631. *
  632. * @param object $MR
  633. * @access public
  634. * @return object|null
  635. */
  636. public function apiAcceptMR($MR)
  637. {
  638. $host = $this->loadModel('pipeline')->getByID($MR->hostID);
  639. if(!$host) return null;
  640. $apiRoot = $this->loadModel($host->type)->getApiRoot($MR->hostID);
  641. if($host->type == 'gitlab')
  642. {
  643. $approveUrl = sprintf($apiRoot, "/projects/$MR->targetProject/merge_requests/$MR->mriid/approved");
  644. commonModel::http($approveUrl, null, array(CURLOPT_CUSTOMREQUEST => 'POST'));
  645. $url = sprintf($apiRoot, "/projects/$MR->targetProject/merge_requests/$MR->mriid/merge");
  646. return json_decode(commonModel::http($url, null, array(CURLOPT_CUSTOMREQUEST => 'PUT')));
  647. }
  648. else
  649. {
  650. $url = sprintf($apiRoot, "/repos/$MR->targetProject/pulls/$MR->mriid/merge");
  651. $data = array('Do' => $MR->squash == '1' ? 'squash' : 'merge');
  652. if($MR->removeSourceBranch == '1') $data['delete_branch_after_merge'] = true;
  653. }
  654. $rowMR = json_decode(commonModel::http($url, $data, array(), array(), 'json', 'POST'));
  655. if(!isset($rowMR->massage))
  656. {
  657. $rowMR = $this->apiGetSingleMR($MR->repoID, $MR->mriid);
  658. if($MR->removeSourceBranch == '1' && $host->type == 'gogs') $this->loadModel($host->type)->apiDeleteBranch($MR->hostID, $MR->sourceProject, $MR->sourceBranch);
  659. }
  660. return $rowMR;
  661. }
  662. /**
  663. * 获取合并请求的对比信息。
  664. * Get MR diff versions by API.
  665. *
  666. * @param object $MR
  667. * @access public
  668. * @return array
  669. */
  670. public function getDiffs($MR)
  671. {
  672. if(!isset($MR->repoID)) return array();
  673. $repo = $this->loadModel('repo')->getByID($MR->repoID);
  674. if(!$repo) return array();
  675. $host = $this->loadModel('pipeline')->getByID($MR->hostID);
  676. $scm = $this->app->loadClass('scm');
  677. $scm->setEngine($repo);
  678. $lines = array();
  679. if($host->type == 'gitlab')
  680. {
  681. $diffVersions = array();
  682. if($MR->synced) $diffVersions = $this->apiGetDiffVersions($MR->hostID, $MR->targetProject, $MR->mriid);
  683. foreach($diffVersions as $diffVersion)
  684. {
  685. $singleDiff = $this->apiGetSingleDiffVersion($MR->hostID, $MR->targetProject, $MR->mriid, $diffVersion->id);
  686. if($singleDiff->state == 'empty') continue;
  687. $diffs = $singleDiff->diffs;
  688. foreach($diffs as $diff)
  689. {
  690. $lines[] = sprintf("diff --git a/%s b/%s", $diff->old_path, $diff->new_path);
  691. $lines[] = sprintf("index %s ... %s %s ", $singleDiff->head_commit_sha, $singleDiff->base_commit_sha, $diff->b_mode);
  692. $lines[] = sprintf("--a/%s", $diff->old_path);
  693. $lines[] = sprintf("--b/%s", $diff->new_path);
  694. $diffLines = explode("\n", $diff->diff);
  695. foreach($diffLines as $diffLine) $lines[] = $diffLine;
  696. }
  697. }
  698. }
  699. else
  700. {
  701. $lines = $this->apiGetDiffs($MR->hostID, $MR->targetProject, $MR->mriid);
  702. }
  703. if(empty($MR->synced)) $lines = preg_replace('/^\s*$\n?\r?/m', '', $MR->diffs);
  704. if(is_string($lines)) $lines = explode("\n", $lines);
  705. return $scm->engine->parseDiff($lines);
  706. }
  707. /**
  708. * 通过API创建合并请求待办。
  709. * Create a todo item for merge request.
  710. *
  711. * @param int $hostID
  712. * @param string $projectID
  713. * @param int $MRID
  714. * @access public
  715. * @return object|null
  716. */
  717. public function apiCreateMRTodo($hostID, $projectID, $MRID)
  718. {
  719. $url = sprintf($this->loadModel('gitlab')->getApiRoot($hostID), "/projects/$projectID/merge_requests/$MRID/todo");
  720. return json_decode(commonModel::http($url, null, array(CURLOPT_CUSTOMREQUEST => 'POST')));
  721. }
  722. /**
  723. * 通过API获取合并请求的对比版本信息。
  724. * Get diff versions of MR from GitLab API.
  725. *
  726. * @param int $hostID
  727. * @param string $projectID
  728. * @param int $MRID
  729. * @access public
  730. * @return array|null
  731. */
  732. public function apiGetDiffVersions($hostID, $projectID, $MRID)
  733. {
  734. $url = sprintf($this->loadModel('gitlab')->getApiRoot($hostID), "/projects/$projectID/merge_requests/$MRID/versions");
  735. return json_decode(commonModel::http($url));
  736. }
  737. /**
  738. * 通过API获取合并请求的单个对比版本信息。
  739. * Get a single diff version of MR from GitLab API.
  740. *
  741. * @param int $hostID
  742. * @param string $projectID
  743. * @param int $MRID
  744. * @param int $versionID
  745. * @access public
  746. * @return object|null
  747. */
  748. public function apiGetSingleDiffVersion($hostID, $projectID, $MRID, $versionID)
  749. {
  750. $url = sprintf($this->loadModel('gitlab')->getApiRoot($hostID), "/projects/$projectID/merge_requests/$MRID/versions/$versionID");
  751. return json_decode(commonModel::http($url));
  752. }
  753. /**
  754. * 通过Gitea API获取合并请求的对比信息。
  755. * Get diff of MR from Gitea API.
  756. *
  757. * @param int $hostID
  758. * @param string $projectID
  759. * @param int $MRID
  760. * @access public
  761. * @return string
  762. */
  763. public function apiGetDiffs($hostID, $projectID, $MRID)
  764. {
  765. $host = $this->loadModel('pipeline')->getByID($hostID);
  766. if(!$host || $host->type == 'gitlab') return '';
  767. $url = sprintf($this->loadModel($host->type)->getApiRoot($hostID), "/repos/$projectID/pulls/$MRID.diff");
  768. return commonModel::http($url);
  769. }
  770. /**
  771. * 审核合并请求。
  772. * Reject or Approve this MR.
  773. *
  774. * @param object $MR
  775. * @param string $action approve|reject
  776. * @param string $comment
  777. * @return array
  778. */
  779. public function approve($MR, $action = 'approve', $comment = '')
  780. {
  781. if(isset($MR->status) && $MR->status == 'opened')
  782. {
  783. $oldMR = clone $MR;
  784. $rawApprovalStatus = zget($MR, 'approvalStatus', '');
  785. if($action == 'reject' && $rawApprovalStatus != 'rejected') $MR->approvalStatus = 'rejected';
  786. if($action == 'approve' && $rawApprovalStatus != 'approved') $MR->approvalStatus = 'approved';
  787. if(isset($MR->approvalStatus) && $rawApprovalStatus != $MR->approvalStatus)
  788. {
  789. $changes = common::createChanges($oldMR, $MR);
  790. unset($MR->editedDate);
  791. $MR->approver = $this->app->user->account;
  792. $this->dao->update(TABLE_MR)->data($MR)
  793. ->where('id')->eq($MR->id)
  794. ->exec();
  795. if(dao::isError()) return array('result' => 'fail', 'message' => dao::getError());
  796. /* Save approval history into db. */
  797. $approval = new stdClass;
  798. $approval->date = helper::now();
  799. $approval->mrID = $MR->id;
  800. $approval->account = $MR->approver;
  801. $approval->action = $action;
  802. $approval->comment = $comment;
  803. $this->dao->insert(TABLE_MRAPPROVAL)->data($approval, $this->config->mrapproval->create->skippedFields)
  804. ->batchCheck($this->config->mrapproval->create->requiredFields, 'notempty')
  805. ->autoCheck()
  806. ->exec();
  807. if(dao::isError()) return array('result' => 'fail', 'message' => dao::getError());
  808. $actionID = $this->loadModel('action')->create($this->moduleName, $MR->id, $action);
  809. $this->action->logHistory($actionID, $changes);
  810. return array('result' => 'success', 'message' => $this->lang->saveSuccess, 'closeModal' => true, 'load' => true);
  811. }
  812. }
  813. return array('result' => 'fail', 'message' => $this->lang->mr->repeatedOperation, 'load' => helper::createLink($this->moduleName, 'view', "mr={$MR->id}"));
  814. }
  815. /**
  816. * 关闭合并请求。
  817. * Close this MR.
  818. *
  819. * @param object $MR
  820. * @access public
  821. * @return array
  822. */
  823. public function close($MR)
  824. {
  825. if($MR->status == 'closed') return array('result' => 'fail', 'message' => $this->lang->mr->repeatedOperation);
  826. $actionID = $this->loadModel('action')->create($this->moduleName, $MR->id, 'closed');
  827. $rawMR = $this->apiCloseMR($MR->hostID, $MR->targetProject, $MR->mriid);
  828. $changes = common::createChanges($MR, $rawMR);
  829. $this->action->logHistory($actionID, $changes);
  830. if(isset($rawMR->state) && $rawMR->state == 'closed') return array('result' => 'success', 'message' => $this->lang->mr->closeSuccess, 'load' => 'reload');
  831. return array('result' => 'fail', 'message' => $this->lang->fail);
  832. }
  833. /**
  834. * 重新打开合并请求。
  835. * Reopen this MR.
  836. *
  837. * @param object $MR
  838. * @access public
  839. * @return array
  840. */
  841. public function reopen($MR)
  842. {
  843. if($MR->status == 'opened') return array('result' => 'fail', 'message' => $this->lang->mr->repeatedOperation);
  844. $this->loadModel('action')->create($this->moduleName, $MR->id, 'reopen');
  845. $rawMR = $this->apiReopenMR($MR->hostID, $MR->targetProject, $MR->mriid);
  846. if(!empty($rawMR) && empty($rawMR->message)) return array('result' => 'success', 'message' => $this->lang->mr->reopenSuccess, 'load' => 'reload');
  847. return array('result' => 'fail', 'message' => $this->lang->fail);
  848. }
  849. /**
  850. * 获取合并请求关联的对象。
  851. * Get mr link list.
  852. *
  853. * @param int $MRID
  854. * @param string $type story|task|bug
  855. * @param string $orderBy
  856. * @param object $pager
  857. * @access public
  858. * @return array
  859. */
  860. public function getLinkList($MRID, $type, $orderBy = 'id_desc', $pager = null)
  861. {
  862. if(!isset($this->config->objectTables[$type])) return array();
  863. $orderBy = str_replace('name_', 'title_', $orderBy);
  864. if($type == 'task') $orderBy = str_replace('title_', 'name_', $orderBy);
  865. return $this->dao->select('t1.*')->from($this->config->objectTables[$type])->alias('t1')
  866. ->leftJoin(TABLE_RELATION)->alias('t2')->on('t1.id=t2.BID')
  867. ->where('t2.relation')->eq('interrated')
  868. ->andWhere('t2.AType')->eq($this->moduleName)
  869. ->andWhere('t2.AID')->eq($MRID)
  870. ->andWhere('t2.BType')->eq($type)
  871. ->andWhere('t1.deleted')->eq(0)
  872. ->orderBy($orderBy)
  873. ->page($pager)
  874. ->fetchAll('id');
  875. }
  876. /**
  877. * 根据对象信息获取合并请求列表。
  878. * Get linked MR pairs.
  879. *
  880. * @param int $objectID
  881. * @param string $objectType
  882. * @param string $module mr|pullreq
  883. * @access public
  884. * @return array
  885. */
  886. public function getLinkedMRPairs($objectID, $objectType = 'story', $module = '')
  887. {
  888. if(!$module) $module = $this->moduleName;
  889. return $this->dao->select("t2.id,t2.title,t2.status")->from(TABLE_RELATION)->alias('t1')
  890. ->leftJoin(TABLE_MR)->alias('t2')->on('t1.AID = t2.id')
  891. ->where('t1.AType')->eq($module)
  892. ->andWhere('t1.BType')->eq($objectType)
  893. ->andWhere('t1.BID')->eq($objectID)
  894. ->andWhere('t2.id')->ne(0)
  895. ->fetchAll('id');
  896. }
  897. /**
  898. * 合并请求关联对象。
  899. * Create an mr link.
  900. *
  901. * @param int $MRID
  902. * @param string $type story|task|bug
  903. * @param array $objects
  904. * @access public
  905. * @return bool
  906. */
  907. public function link($MRID, $type, $objects)
  908. {
  909. if(!isset($this->config->objectTables[$type])) return false;
  910. $MR = $this->fetchByID($MRID);
  911. if(!$MR) return false;
  912. /* Set link action text. */
  913. $user = $this->loadModel('user')->getRealNameAndEmails($MR->createdBy);
  914. $comment = $MR->createdDate . '::' . zget($user, 'realname', $this->app->user->realname) . '::' . helper::createLink($this->moduleName, 'view', "mr={$MR->id}");
  915. $this->loadModel('action');
  916. foreach($objects as $objectID)
  917. {
  918. $relation = new stdclass();
  919. $relation->product = 0;
  920. $relation->AType = $this->moduleName;
  921. $relation->AID = $MRID;
  922. $relation->relation = 'interrated';
  923. $relation->BType = $type;
  924. $relation->BID = $objectID;
  925. $this->dao->replace(TABLE_RELATION)->data($relation)->exec();
  926. $this->action->create($type, (int)$objectID, 'create' . $this->moduleName, '', $comment);
  927. }
  928. return !dao::isError();
  929. }
  930. /**
  931. * 保存合并请求关联的对象。
  932. * Save linked objects.
  933. *
  934. * @param object $MR
  935. * @access public
  936. * @return bool
  937. */
  938. public function linkObjects($MR)
  939. {
  940. /* Get commits by MR. */
  941. $commits = $this->apiGetMRCommits($MR->hostID, (string)$MR->targetProject, $MR->mriid);
  942. if(empty($commits)) return true;
  943. /* Init objects. */
  944. $objectList = array('story' => array(), 'bug' => array(), 'task' => array());
  945. $this->loadModel('repo');
  946. foreach($commits as $commit)
  947. {
  948. if(empty($commit->message)) $commit->message = zget($commit, 'title', '');
  949. $objects = $this->repo->parseComment($commit->message);
  950. $objectList['story'] = array_merge($objectList['story'], $objects['stories']);
  951. $objectList['bug'] = array_merge($objectList['bug'], $objects['bugs']);
  952. $objectList['task'] = array_merge($objectList['task'], $objects['tasks']);
  953. }
  954. $users = $this->loadModel('user')->getPairs('noletter');
  955. $MRCreateAction = $MR->createdDate . '::' . zget($users, $MR->createdBy) . '::' . $MR->id;
  956. $product = $this->getMRProduct($MR);
  957. $this->loadModel('action');
  958. foreach($objectList as $type => $objectIDs)
  959. {
  960. $relation = new stdclass();
  961. $relation->product = $product ? $product->id : 0;
  962. $relation->AType = $this->moduleName;
  963. $relation->AID = $MR->id;
  964. $relation->relation = 'interrated';
  965. $relation->BType = $type;
  966. foreach($objectIDs as $objectID)
  967. {
  968. $relation->BID = $objectID;
  969. $this->dao->replace(TABLE_RELATION)->data($relation)->exec();
  970. $this->action->create($type, (int)$objectID, 'create' . $this->moduleName, '', $MRCreateAction);
  971. }
  972. }
  973. return !dao::isError();
  974. }
  975. /**
  976. * 解除合并请求关联的对象。
  977. * Unlink an mr link.
  978. *
  979. * @param int $MRID
  980. * @param string $type
  981. * @param int $objectID
  982. * @access public
  983. * @return bool
  984. */
  985. public function unlink($MRID, $type, $objectID)
  986. {
  987. if(!isset($this->config->objectTables[$type])) return false;
  988. $this->dao->delete()->from(TABLE_RELATION)
  989. ->where('AType')->eq($this->moduleName)
  990. ->andWhere('AID')->eq($MRID)
  991. ->andWhere('relation')->eq('interrated')
  992. ->andWhere('BType')->eq($type)
  993. ->andWhere('BID')->eq($objectID)
  994. ->exec();
  995. $this->loadModel('action')->create($type, $objectID, 'deletemr', '', helper::createLink($this->moduleName, 'view', "mr={$MRID}"));
  996. return !dao::isError();
  997. }
  998. /**
  999. * 获取合并请求的产品。
  1000. * Get mr product.
  1001. *
  1002. * @param object $MR
  1003. * @access public
  1004. * @return object|false
  1005. */
  1006. public function getMRProduct($MR)
  1007. {
  1008. $productID = $this->dao->select('product')->from(TABLE_REPO)->where('id')->eq($MR->repoID)->fetch('product');
  1009. if(!$productID) return false;
  1010. return $this->loadModel('product')->getById((int)$productID);
  1011. }
  1012. /**
  1013. * 获取合并请求的收件人和抄送人。
  1014. * Get toList and ccList.
  1015. *
  1016. * @param object $MR
  1017. * @access public
  1018. * @return array
  1019. */
  1020. public function getToAndCcList($MR)
  1021. {
  1022. return array($MR->createdBy, $MR->assignee);
  1023. }
  1024. /**
  1025. * 将合并的操作记录到链接
  1026. * Log merged action to links.
  1027. *
  1028. * @param object $MR
  1029. * @access public
  1030. * @return bool
  1031. */
  1032. public function logMergedAction($MR)
  1033. {
  1034. $this->loadModel('action')->create($this->moduleName, $MR->id, 'merged' . $this->moduleName);
  1035. foreach(array('story', 'bug', 'task') as $type)
  1036. {
  1037. $objects = $this->getLinkList($MR->id, $type);
  1038. foreach($objects as $object)
  1039. {
  1040. $this->action->create($type, $object->id, 'merged' . $this->moduleName, '', helper::createLink($this->moduleName, 'view', "mr={$MR->id}"));
  1041. }
  1042. }
  1043. $this->dao->update(TABLE_MR)->data(array('status' => 'merged'))->where('id')->eq($MR->id)->exec();
  1044. return !dao::isError();
  1045. }
  1046. /**
  1047. * 检查是否有相同的未关闭合并请求。
  1048. * Check same opened mr for source branch.
  1049. *
  1050. * @param int $hostID
  1051. * @param string $sourceProject
  1052. * @param string $sourceBranch
  1053. * @param string $targetProject
  1054. * @param string $targetBranch
  1055. * @access public
  1056. * @return array
  1057. */
  1058. public function checkSameOpened($hostID, $sourceProject, $sourceBranch, $targetProject, $targetBranch)
  1059. {
  1060. if($sourceProject == $targetProject && $sourceBranch == $targetBranch) return array('result' => 'fail', 'message' => $this->lang->mr->errorLang[1]);
  1061. $dbOpenedID = $this->dao->select('id')->from(TABLE_MR)
  1062. ->where('hostID')->eq($hostID)
  1063. ->andWhere('sourceProject')->eq($sourceProject)
  1064. ->andWhere('sourceBranch')->eq($sourceBranch)
  1065. ->andWhere('targetProject')->eq($targetProject)
  1066. ->andWhere('targetBranch')->eq($targetBranch)
  1067. ->andWhere('status')->eq('opened')
  1068. ->andWhere('deleted')->eq('0')
  1069. ->fetch('id');
  1070. if(!empty($dbOpenedID)) return array('result' => 'fail', 'message' => sprintf($this->lang->mr->hasSameOpenedMR, $dbOpenedID));
  1071. $MR = $this->apiGetSameOpened($hostID, (string)$sourceProject, $sourceBranch, (string)$targetProject, $targetBranch);
  1072. if($MR) return array('result' => 'fail', 'message' => sprintf($this->lang->mr->errorLang[2], $MR->iid));
  1073. return array('result' => 'success');
  1074. }
  1075. /**
  1076. * 解析API错误信息。
  1077. * Convert API error.
  1078. *
  1079. * @param array $message
  1080. * @access public
  1081. * @return string
  1082. */
  1083. public function convertApiError($message)
  1084. {
  1085. if(is_array($message)) $message = $message[0];
  1086. if(!is_string($message)) return $message;
  1087. foreach($this->lang->mr->apiErrorMap as $key => $errorMsg)
  1088. {
  1089. if(strpos($errorMsg, '/') === 0)
  1090. {
  1091. $result = preg_match($errorMsg, $message, $matches);
  1092. if($result) $errorMessage = sprintf(zget($this->lang->mr->errorLang, $key), zget($matches, 1, $matches[0]));
  1093. }
  1094. elseif($message == $errorMsg)
  1095. {
  1096. $errorMessage = zget($this->lang->mr->errorLang, $key, $message);
  1097. }
  1098. if(isset($errorMessage)) break;
  1099. }
  1100. return isset($errorMessage) ? $errorMessage : $message;
  1101. }
  1102. /**
  1103. * 判断按钮是否可点击。
  1104. * Adjust the action clickable.
  1105. *
  1106. * @param object $MR
  1107. * @param string $action
  1108. * @access public
  1109. * @return bool
  1110. */
  1111. public static function isClickable($MR, $action)
  1112. {
  1113. if($action == 'edit' && !$MR->synced) return false;
  1114. if($action == 'edit') return $MR->canEdit != 'disabled';
  1115. if($action == 'delete') return $MR->canDelete != 'disabled';
  1116. return true;
  1117. }
  1118. /**
  1119. * 根据ID删除合并请求。
  1120. * Delete MR by ID.
  1121. *
  1122. * @param int $MRID
  1123. * @access public
  1124. * @return bool
  1125. */
  1126. public function deleteByID($MRID)
  1127. {
  1128. $MR = $this->fetchByID($MRID);
  1129. if(!$MR) return false;
  1130. if($MR->synced)
  1131. {
  1132. $res = $this->apiDeleteMR($MR->hostID, $MR->targetProject, $MR->mriid);
  1133. if(isset($res->message)) dao::$errors[] = $this->convertApiError($res->message);
  1134. if(dao::isError()) return false;
  1135. }
  1136. $this->dao->delete()->from(TABLE_MR)->where('id')->eq($MRID)->exec();
  1137. $this->loadModel('action')->create($this->moduleName, $MRID, 'deleted', '', $MR->title);
  1138. $this->createMRLinkedAction($MRID, 'remove' . $this->moduleName);
  1139. return !dao::isError();
  1140. }
  1141. /**
  1142. * 执行合并请求流水线。
  1143. * Execute MR pipeline.
  1144. *
  1145. * @param int $MRID
  1146. * @param int $jobID
  1147. * @access public
  1148. * @return bool
  1149. */
  1150. public function execJob($MRID, $jobID)
  1151. {
  1152. if(empty($MRID) || empty($jobID)) return false;
  1153. $MR = $this->fetchByID($MRID);
  1154. if(!$MR) return false;
  1155. $compile = $this->loadModel('job')->exec($jobID, array('sourceBranch' => $MR->sourceBranch, 'targetBranch' => $MR->targetBranch), 'commit');
  1156. if(!$compile) return false;
  1157. $newMR = new stdclass();
  1158. $newMR->compileID = $compile->id;
  1159. $newMR->compileStatus = $compile->status;
  1160. if($newMR->compileStatus == 'failure') $newMR->status = 'closed';
  1161. if($newMR->compileStatus == 'create_fail') $newMR->status = 'closed';
  1162. $this->loadModel('repo')->saveRelation($MRID, 'mr', $compile->id, 'compile', 'mrjob');
  1163. $this->dao->update(TABLE_MR)->data($newMR)->where('id')->eq($MRID)->autoCheck()->exec();
  1164. return dao::isError();
  1165. }
  1166. /**
  1167. * 创建合并请求。
  1168. * Insert a merge request.
  1169. *
  1170. * @param object $MR
  1171. * @access public
  1172. * @return int|false
  1173. */
  1174. public function insertMr($MR)
  1175. {
  1176. $this->dao->insert(TABLE_MR)->data($MR, $this->config->mr->create->skippedFields)
  1177. ->batchCheck($this->config->mr->create->requiredFields, 'notempty')
  1178. ->checkIF(!empty($MR->needCI), 'jobID', 'notempty')
  1179. ->exec();
  1180. if(dao::isError()) return false;
  1181. return $this->dao->lastInsertID();
  1182. }
  1183. }