model.php 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513
  1. <?php
  2. /**
  3. * The model file of gitlab 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 Chenqi <chenqi@cnezsoft.com>
  8. * @package product
  9. * @version $Id: $
  10. * @link https://www.zentao.net
  11. */
  12. class gitlabModel extends model
  13. {
  14. const HOOK_PUSH_EVENT = 'Push Hook';
  15. /* Gitlab access level. */
  16. public $noAccess = 0;
  17. public $developerAccess = 30;
  18. public $maintainerAccess = 40;
  19. protected $projects = array();
  20. /**
  21. * 获取gitlab根据id。
  22. * Get a gitlab by id.
  23. *
  24. * @param int $id
  25. * @access public
  26. * @return object|false
  27. */
  28. public function getByID($id)
  29. {
  30. return $this->loadModel('pipeline')->getByID($id);
  31. }
  32. /**
  33. * 获取gitlab列表。
  34. * Get gitlab list.
  35. *
  36. * @param string $orderBy
  37. * @param object $pager
  38. * @access public
  39. * @return array
  40. */
  41. public function getList($orderBy = 'id_desc', $pager = null)
  42. {
  43. $gitlabList = $this->loadModel('pipeline')->getList('gitlab', $orderBy, $pager);
  44. return $gitlabList;
  45. }
  46. /**
  47. * 获取gitlab id name 键值对。
  48. * Get gitlab pairs.
  49. *
  50. * @access public
  51. * @return array
  52. */
  53. public function getPairs()
  54. {
  55. return $this->loadModel('pipeline')->getPairs('gitlab');
  56. }
  57. /**
  58. * 获取gitlab api 基础url 根据gitlab id。
  59. * Get gitlab api base url by gitlab id.
  60. *
  61. * @param int $gitlabID
  62. * @param bool $sudo
  63. * @access public
  64. * @return string
  65. */
  66. public function getApiRoot($gitlabID, $sudo = true)
  67. {
  68. $gitlab = $this->getByID($gitlabID);
  69. if(!$gitlab || $gitlab->type != 'gitlab') return '';
  70. $sudoParam = '';
  71. if($sudo == true && !$this->app->user->admin)
  72. {
  73. $openID = $this->loadModel('pipeline')->getOpenIdByAccount($gitlabID, 'gitlab', $this->app->user->account);
  74. if($openID) $sudoParam = "&sudo={$openID}";
  75. }
  76. return rtrim($gitlab->url, '/') . '/api/v4%s' . "?private_token={$gitlab->token}" . $sudoParam;
  77. }
  78. /**
  79. * 获取gitlab的 项目id和名称 键值对。
  80. * Get project pairs of one gitlab.
  81. *
  82. * @param int $gitlabID
  83. * @access public
  84. * @return array
  85. */
  86. public function getProjectPairs($gitlabID)
  87. {
  88. $projects = $this->apiGetProjects($gitlabID);
  89. $projectPairs = array();
  90. foreach($projects as $project) $projectPairs[$project->id] = $project->name_with_namespace;
  91. return $projectPairs;
  92. }
  93. /**
  94. * 获取匹配的gitlab用户列表。
  95. * Get matched gitlab users.
  96. *
  97. * @param int $gitlabID
  98. * @param array $gitlabUsers
  99. * @param array $zentaoUsers
  100. * @access public
  101. * @return array
  102. */
  103. public function getMatchedUsers($gitlabID, $gitlabUsers, $zentaoUsers)
  104. {
  105. $matches = new stdclass;
  106. foreach($gitlabUsers as $gitlabUser)
  107. {
  108. foreach($zentaoUsers as $zentaoUser)
  109. {
  110. if($gitlabUser->email == $zentaoUser->email) $matches->emails[$gitlabUser->email][] = $zentaoUser->account;
  111. if($gitlabUser->account == $zentaoUser->account) $matches->accounts[$gitlabUser->account][] = $zentaoUser->account;
  112. if($gitlabUser->realname == $zentaoUser->realname) $matches->names[$gitlabUser->realname][] = $zentaoUser->account;
  113. }
  114. }
  115. $bindedUsers = $this->loadModel('pipeline')->getUserBindedPairs($gitlabID, 'gitlab', 'openID,account');
  116. $matchedUsers = array();
  117. foreach($gitlabUsers as $gitlabUser)
  118. {
  119. if(isset($bindedUsers[$gitlabUser->id]))
  120. {
  121. $gitlabUser->zentaoAccount = $bindedUsers[$gitlabUser->id];
  122. $matchedUsers[$gitlabUser->id] = $gitlabUser;
  123. continue;
  124. }
  125. $matchedZentaoUsers = array();
  126. if(isset($matches->emails[$gitlabUser->email])) $matchedZentaoUsers = array_merge($matchedZentaoUsers, $matches->emails[$gitlabUser->email]);
  127. if(isset($matches->names[$gitlabUser->realname])) $matchedZentaoUsers = array_merge($matchedZentaoUsers, $matches->names[$gitlabUser->realname]);
  128. if(isset($matches->accounts[$gitlabUser->account])) $matchedZentaoUsers = array_merge($matchedZentaoUsers, $matches->accounts[$gitlabUser->account]);
  129. $matchedZentaoUsers = array_unique($matchedZentaoUsers);
  130. if(count($matchedZentaoUsers) == 1)
  131. {
  132. $gitlabUser->zentaoAccount = current($matchedZentaoUsers);
  133. $matchedUsers[$gitlabUser->id] = $gitlabUser;
  134. }
  135. }
  136. return $matchedUsers;
  137. }
  138. /**
  139. * 根据关联信息获取gitlab id和gitlab项目id。
  140. * Get gitlabID and projectID.
  141. *
  142. * @param string $objectType
  143. * @param int $objectID
  144. * @access public
  145. * @return object|false
  146. */
  147. public function getRelationByObject($objectType, $objectID)
  148. {
  149. return $this->dao->select('*, extra as gitlabID, BVersion as projectID, BID as issueID')->from(TABLE_RELATION)
  150. ->where('relation')->eq('gitlab')
  151. ->andWhere('Atype')->eq($objectType)
  152. ->andWhere('AID')->eq($objectID)
  153. ->fetch();
  154. }
  155. /**
  156. * 获取问题id列表根据关联信息。
  157. * Get issue id list group by object.
  158. *
  159. * @param string $objectType
  160. * @param array $objects
  161. * @access public
  162. * @return array
  163. */
  164. public function getIssueListByObjects($objectType, $objects)
  165. {
  166. return $this->dao->select('*, extra as gitlabID, BVersion as projectID, BID as issueID')->from(TABLE_RELATION)
  167. ->where('relation')->eq('gitlab')
  168. ->andWhere('Atype')->eq($objectType)
  169. ->andWhere('AID')->in($objects)
  170. ->fetchAll('AID');
  171. }
  172. /**
  173. * 获取gitlab项目名称根据项目id。
  174. * Get gitlab project name of one gitlab project.
  175. *
  176. * @param int $gitlabID
  177. * @param int $projectID
  178. * @access public
  179. * @return string|false
  180. */
  181. public function getProjectName($gitlabID, $projectID)
  182. {
  183. $project = $this->apiGetSingleProject($gitlabID, $projectID);
  184. if(is_object($project) and isset($project->name)) return $project->name;
  185. return false;
  186. }
  187. /**
  188. * 获取分支和标签列表。
  189. * Get reference option menus.
  190. *
  191. * @param int $gitlabID
  192. * @param int $projectID
  193. * @access public
  194. * @return array
  195. */
  196. public function getReferenceOptions($gitlabID, $projectID)
  197. {
  198. $refList = array();
  199. $branches = $this->apiGetBranches($gitlabID, $projectID);
  200. if(is_array($branches))
  201. {
  202. foreach($branches as $branch) $refList[$branch->name] = "Branch::" . $branch->name;
  203. }
  204. $tags = $this->apiGetTags($gitlabID, $projectID);
  205. if(is_array($tags))
  206. {
  207. foreach($tags as $tag) $refList[$tag->name] = "Tag::" . $tag->name;
  208. }
  209. return $refList;
  210. }
  211. /**
  212. * 获取分支名称列表。
  213. * Get branches.
  214. *
  215. * @param int $gitlabID
  216. * @param int $projectID
  217. * @access public
  218. * @return array
  219. */
  220. public function getBranches($gitlabID, $projectID)
  221. {
  222. $rawBranches = $this->apiGetBranches($gitlabID, $projectID);
  223. $branches = array();
  224. foreach($rawBranches as $branch)
  225. {
  226. $branches[] = $branch->name;
  227. }
  228. return $branches;
  229. }
  230. /**
  231. * 获取gitlab 提交列表。
  232. * Get Gitlab commits.
  233. *
  234. * @param object $repo
  235. * @param string $entry
  236. * @param object $pager
  237. * @param string $begin
  238. * @param string $end
  239. * @param object $query
  240. * @access public
  241. * @return array
  242. */
  243. public function getCommits($repo, $entry, $pager = null, $begin = '', $end = '', $query = null)
  244. {
  245. $scm = $this->app->loadClass('scm');
  246. $scm->setEngine($repo);
  247. $fromRevision = $toRevision = $committer = '';
  248. if($query)
  249. {
  250. $fromRevision = zget($query, 'commit', '');
  251. $toRevision = $fromRevision;
  252. $committer = zget($query, 'committer', '');
  253. if(!empty($query->begin)) $begin = $query->begin;
  254. if(!empty($query->end)) $end = $query->end;
  255. }
  256. $comments = $scm->engine->getCommitsByPath($entry, $fromRevision, $toRevision, isset($pager->recPerPage) ? $pager->recPerPage : 10, isset($pager->pageID) ? $pager->pageID : 1, $begin, $end, $committer);
  257. if(!is_array($comments)) return array();
  258. if(isset($pager->recTotal)) $pager->recTotal = count($comments) < $pager->recPerPage ? $pager->recPerPage * $pager->pageID : $pager->recPerPage * ($pager->pageID + 1);
  259. $commitIds = array();
  260. foreach($comments as $comment)
  261. {
  262. $commitDate = isset($comment->author->when) ? $comment->author->when : $comment->committed_date;
  263. if(!isset($comment->id)) $comment->id = $comment->sha;
  264. $comment->revision = $comment->id;
  265. $comment->originalComment = $comment->title;
  266. $comment->committed_date = $commitDate;
  267. $comment->comment = $this->loadModel('repo')->replaceCommentLink($comment->title);
  268. $comment->committer = isset($comment->author->identity->name) ? $comment->author->identity->name : $comment->committer_name;
  269. $comment->time = date("Y-m-d H:i:s", strtotime($commitDate));
  270. $commitIds[] = $comment->id;
  271. }
  272. $commitCounts = $this->dao->select('revision,commit')->from(TABLE_REPOHISTORY)->where('revision')->in($commitIds)->fetchPairs();
  273. foreach($comments as $comment) $comment->commit = !empty($commitCounts[$comment->id]) ? $commitCounts[$comment->id] : '';
  274. return $comments;
  275. }
  276. /**
  277. * 设置项目信息。
  278. * Set project data.
  279. *
  280. * @param int $gitlabID
  281. * @param int $projectID
  282. * @param object $project
  283. * @access public
  284. * @return void
  285. */
  286. public function setProject($gitlabID, $projectID, $project)
  287. {
  288. $this->projects[$gitlabID][$projectID] = $project;
  289. }
  290. /**
  291. * 发送一个get api请求。
  292. * Send an api get request.
  293. *
  294. * @param int|string $host gitlab server ID | gitlab host url.
  295. * @param string $api
  296. * @access public
  297. * @return object|array|null
  298. */
  299. public function apiGet($host, $api)
  300. {
  301. if(is_numeric($host)) $host = $this->getApiRoot($host);
  302. if(strpos($host, 'http://') !== 0 and strpos($host, 'https://') !== 0) return null;
  303. $url = sprintf($host, $api);
  304. return json_decode(commonModel::http($url));
  305. }
  306. /**
  307. * 发送一个post api请求。
  308. * Send an api post request.
  309. *
  310. * @param int|string $host gitlab server ID | gitlab host url.
  311. * @param string $api
  312. * @param array|object $data
  313. * @param array $options
  314. * @access public
  315. * @return object|array|null
  316. */
  317. public function apiPost($host, $api, $data = array(), $options = array())
  318. {
  319. if(is_numeric($host)) $host = $this->getApiRoot($host);
  320. if(strpos($host, 'http://') !== 0 and strpos($host, 'https://') !== 0) return false;
  321. $url = sprintf($host, $api);
  322. return json_decode(commonModel::http($url, $data, $options));
  323. }
  324. /**
  325. * 获取代表列表通过api。
  326. * Get a list of to-do items by API.
  327. *
  328. * @link https://docs.gitlab.com/ee/api/todos.html
  329. * @param int $gitlabID
  330. * @param int $projectID
  331. * @param int $sudo
  332. * @access public
  333. * @return object|array|null|string
  334. */
  335. public function apiGetTodoList($gitlabID, $projectID, $sudo)
  336. {
  337. $gitlab = $this->loadModel('gitlab')->getByID($gitlabID);
  338. if(!$gitlab) return '';
  339. $url = rtrim($gitlab->url, '/') . "/api/v4/todos?project_id=$projectID&type=MergeRequest&state=pending&private_token={$gitlab->token}&sudo={$sudo}";
  340. return json_decode(commonModel::http($url));
  341. }
  342. /**
  343. * 获取最新用户。
  344. * Get current user.
  345. *
  346. * @param string $host
  347. * @param string $token
  348. * @access public
  349. * @return object|array|null|false
  350. */
  351. public function apiGetCurrentUser($host, $token)
  352. {
  353. $host = rtrim($host, '/') . "/api/v4%s?private_token=$token";
  354. return $this->apiGet($host, '/user');
  355. }
  356. /**
  357. * 获取gitlab用户列表。
  358. * Get gitlab user list.
  359. *
  360. * @param int $gitlabID
  361. * @param bool $onlyLinked
  362. * @param string $orderBy
  363. * @access public
  364. * @return array
  365. */
  366. public function apiGetUsers($gitlabID, $onlyLinked = false, $orderBy = 'id_desc')
  367. {
  368. /* GitLab API '/users' can only return 20 users per page in default, so we use a loop to fetch all users. */
  369. $page = 1;
  370. $perPage = 100;
  371. $response = array();
  372. $apiRoot = $this->getApiRoot($gitlabID, strtolower($this->app->rawMethod) != 'binduser');
  373. /* Get order data. */
  374. $orders = explode('_', $orderBy);
  375. $sort = array_pop($orders);
  376. $order = join('_', $orders);
  377. while(true)
  378. {
  379. /* Also use `per_page=20` to fetch users in API. Fetch active users only. */
  380. $url = sprintf($apiRoot, "/users") . "&order_by={$order}&sort={$sort}&page={$page}&per_page={$perPage}&active=true";
  381. $httpData = commonModel::http($url, null, array(), array(), 'data', 'GET', 30, true, false);
  382. if(empty($httpData['body'])) break;
  383. $result = json_decode($httpData['body']);
  384. if(!empty($result) && is_array($result))
  385. {
  386. $response = array_merge($response, $result);
  387. $page += 1;
  388. $resultPage = isset($httpData['header']['X-Page']) ? $httpData['header']['X-Page'] : $httpData['header']['x-page'];
  389. $resultTotalPage = isset($httpData['header']['X-Total-Pages']) ? $httpData['header']['X-Total-Pages'] : $httpData['header']['x-total-pages'];
  390. if($resultPage == $resultTotalPage) break;
  391. }
  392. else
  393. {
  394. break;
  395. }
  396. }
  397. if(!$response) return array();
  398. /* Get linked users. */
  399. $linkedUsers = array();
  400. if($onlyLinked) $linkedUsers = $this->loadModel('pipeline')->getUserBindedPairs($gitlabID, 'gitlab', 'openID,account');
  401. $users = array();
  402. foreach($response as $gitlabUser)
  403. {
  404. if($onlyLinked and !isset($linkedUsers[$gitlabUser->id])) continue;
  405. $user = new stdclass;
  406. $user->id = $gitlabUser->id;
  407. $user->realname = $gitlabUser->name;
  408. $user->account = $gitlabUser->username;
  409. $user->email = zget($gitlabUser, 'email', '');
  410. $user->avatar = $gitlabUser->avatar_url;
  411. $user->createdAt = zget($gitlabUser, 'created_at', '');
  412. $user->lastActivityOn = zget($gitlabUser, 'last_activity_on', '');
  413. $users[] = $user;
  414. }
  415. return $users;
  416. }
  417. /**
  418. * 获取gitlab群组成员列表。
  419. * Get group members of one gitlab.
  420. *
  421. * @param int $gitlabID
  422. * @param int $groupID
  423. * @param int $userID
  424. * @access public
  425. * @return object
  426. */
  427. public function apiGetGroupMembers($gitlabID, $groupID, $userID = 0)
  428. {
  429. $apiRoot = $this->getApiRoot($gitlabID);
  430. $url = sprintf($apiRoot, "/groups/$groupID/members/all");
  431. if($userID) $url .= "&user_ids=$userID";
  432. $allResults = array();
  433. for($page = 1; true; $page++)
  434. {
  435. $results = json_decode(commonModel::http($url . "&&page={$page}&per_page=100"));
  436. if(!is_array($results)) break;
  437. if(!empty($results)) $allResults = array_merge($allResults, $results);
  438. if(count($results) < 100) break;
  439. }
  440. return $allResults;
  441. }
  442. /**
  443. * API获取项目的合并请求列表。
  444. * Get Merge Requests by API.
  445. *
  446. * @param int $gitlabID
  447. * @param int $projectID
  448. * @return array
  449. */
  450. public function apiGetMergeRequests($gitlabID, $projectID)
  451. {
  452. $apiRoot = $this->getApiRoot((int)$gitlabID);
  453. $url = sprintf($apiRoot, "/projects/$projectID/merge_requests");
  454. $MRs = array();
  455. for($page = 1; true; $page++)
  456. {
  457. $onePageMRs = json_decode(commonModel::http($url . "&&page={$page}&per_page=100"));
  458. if(!is_array($onePageMRs)) break;
  459. if(!empty($onePageMRs)) $MRs = array_merge($MRs, $onePageMRs);
  460. if(count($onePageMRs) < 100) break;
  461. }
  462. return $MRs;
  463. }
  464. /**
  465. * 获取gitlab命名空间列表。
  466. * Get namespaces of one gitlab.
  467. *
  468. * @param int $gitlabID
  469. * @access public
  470. * @return object
  471. */
  472. public function apiGetNamespaces($gitlabID)
  473. {
  474. $apiRoot = $this->getApiRoot($gitlabID);
  475. $url = sprintf($apiRoot, "/namespaces");
  476. $allResults = array();
  477. for($page = 1; true; $page++)
  478. {
  479. $results = json_decode(commonModel::http($url . "&&page={$page}&per_page=100"));
  480. if(!is_array($results)) break;
  481. if(!empty($results)) $allResults = array_merge($allResults, $results);
  482. if(count($results) < 100) break;
  483. }
  484. return $allResults;
  485. }
  486. /**
  487. * 获取gitlab的群组列表。
  488. * Get groups of one gitlab.
  489. *
  490. * @param int $gitlabID
  491. * @param string $orderBy
  492. * @param string $minRole
  493. * @param string $keyword
  494. * @access public
  495. * @return array
  496. */
  497. public function apiGetGroups($gitlabID, $orderBy = 'id_desc', $minRole = '', $keyword = '')
  498. {
  499. $apiRoot = $this->getApiRoot($gitlabID, $minRole == 'owner' ? true : false);
  500. $url = sprintf($apiRoot, "/groups");
  501. if($minRole == 'owner')
  502. {
  503. $url .= '&owned=true';
  504. }
  505. elseif(!empty($minRole) and isset($this->config->gitlab->accessLevel[$minRole]))
  506. {
  507. $url .= '&min_access_level=' . $this->config->gitlab->accessLevel[$minRole];
  508. }
  509. if($keyword) $url .= '&search=' . urlencode($keyword);
  510. $order = 'id';
  511. $sort = 'desc';
  512. if(strpos($orderBy, '_') !== false) list($order, $sort) = explode('_', $orderBy);
  513. $allResults = array();
  514. for($page = 1; true; $page++)
  515. {
  516. $pageUrl = $url . "&statistics=true&order_by={$order}&sort={$sort}&page={$page}&per_page=100&all_available=true";
  517. $results = json_decode(commonModel::http($pageUrl));
  518. if(!is_array($results)) break;
  519. if(!empty($results)) $allResults = array_merge($allResults, $results);
  520. if(count($results) < 100) break;
  521. }
  522. return $allResults;
  523. }
  524. /**
  525. * 通过api创建gitlab群组。
  526. * Create a gitlab group by api.
  527. *
  528. * @param int $gitlabID
  529. * @param object $group
  530. * @access public
  531. * @return object|array|null|false
  532. */
  533. public function apiCreateGroup($gitlabID, $group)
  534. {
  535. if(empty($group->name) or empty($group->path)) return false;
  536. $apiRoot = $this->getApiRoot($gitlabID);
  537. $url = sprintf($apiRoot, "/groups");
  538. return json_decode(commonModel::http($url, $group));
  539. }
  540. /**
  541. * 获取gitlab项目列表根据分页。
  542. * Get projects of one gitlab.
  543. *
  544. * @param int $gitlabID
  545. * @param string $keyword
  546. * @param string $orderBy
  547. * @param object $pager
  548. * @access public
  549. * @return array
  550. */
  551. public function apiGetProjectsPager($gitlabID, $keyword = '', $orderBy = 'id_desc', $pager = null)
  552. {
  553. $apiRoot = $this->getApiRoot($gitlabID);
  554. if(!$apiRoot) return array('pager' => null, 'projects' => array());
  555. $url = sprintf($apiRoot, "/projects");
  556. /* Parse order string. */
  557. $order = explode('_', $orderBy);
  558. $keyword = urlencode($keyword);
  559. $result = commonModel::http($url . "&per_page={$pager->recPerPage}&order_by={$order[0]}&sort={$order[1]}&page={$pager->pageID}&search={$keyword}&search_namespaces=true", null, array(), array(), 'data', 'GET', 30, true, false);
  560. if(empty($result)) return array('pager' => null, 'projects' => array());
  561. $header = $result['header'];
  562. $recTotal = isset($header['X-Total']) ? $header['X-Total']: zget($header, 'x-total', 0);
  563. $recPerPage = isset($header['X-Per-Page']) ? $header['X-Per-Page'] : zget($header, 'x-per-page', 0);
  564. $this->app->loadClass('pager', true);
  565. $pager = pager::init($recTotal, $recPerPage, $pager->pageID);
  566. if(empty($recTotal)) return array('pager' => $pager, 'projects' => array());
  567. return array('pager' => $pager, 'projects' => json_decode($result['body']));
  568. }
  569. /**
  570. * 获取gitlab的项目列表。
  571. * Get projects of one gitlab.
  572. *
  573. * @param int $gitlabID
  574. * @param string $simple
  575. * @param int $minID
  576. * @param int $maxID
  577. * @param bool $sudo
  578. * @access public
  579. * @return array
  580. */
  581. public function apiGetProjects($gitlabID, $simple = 'true', $minID = 0, $maxID = 0, $sudo = true)
  582. {
  583. $apiRoot = $this->getApiRoot($gitlabID, $sudo);
  584. if(!$apiRoot) return array();
  585. $url = sprintf($apiRoot, "/projects");
  586. if($minID > 0) $url .= '&id_after=' . (intval($minID) - 1);
  587. if($maxID > 0) $url .= '&id_before=' . (intval($maxID) + 1);
  588. $allResults = array();
  589. for($page = 1; true; $page++)
  590. {
  591. $results = json_decode(commonModel::http($url . "&simple={$simple}&page={$page}&per_page=100"));
  592. if(!is_array($results)) break;
  593. if(!empty($results)) $allResults = array_merge($allResults, $results);
  594. if(count($results) < 100) break;
  595. }
  596. return $allResults;
  597. }
  598. /**
  599. * 通过api创建gitlab项目。
  600. * Create a gitlab project by api.
  601. *
  602. * @param int $gitlabID
  603. * @param object $project
  604. * @access public
  605. * @return object|array|null|false
  606. */
  607. public function apiCreateProject($gitlabID, $project)
  608. {
  609. if(empty($project->name) || empty($project->path)) return false;
  610. $apiRoot = $this->getApiRoot($gitlabID);
  611. $url = sprintf($apiRoot, "/projects");
  612. return json_decode(commonModel::http($url, $project));
  613. }
  614. /**
  615. * 通过api创建项目成员。
  616. * Add a gitlab project member by api.
  617. *
  618. * @param int $gitlabID
  619. * @param int $projectID
  620. * @param object $member
  621. * @access public
  622. * @return object|array|null|false
  623. */
  624. public function apiCreateProjectMember($gitlabID, $projectID, $member)
  625. {
  626. if(empty($member->user_id) or empty($member->access_level)) return false;
  627. $apiRoot = $this->getApiRoot($gitlabID);
  628. $url = sprintf($apiRoot, "/projects/{$projectID}/members");
  629. return json_decode(commonModel::http($url, $member));
  630. }
  631. /**
  632. * 通过api更新一个项目成员。
  633. * Update a gitlab project member by api.
  634. *
  635. * @param int $gitlabID
  636. * @param int $projectID
  637. * @param object $member
  638. * @access public
  639. * @return object|array|null|false
  640. */
  641. public function apiUpdateProjectMember($gitlabID, $projectID, $member)
  642. {
  643. if(empty($member->user_id) or empty($member->access_level)) return false;
  644. $apiRoot = $this->getApiRoot($gitlabID);
  645. $url = sprintf($apiRoot, "/projects/{$projectID}/members/{$member->user_id}");
  646. return json_decode(commonModel::http($url, $member, array(CURLOPT_CUSTOMREQUEST => 'PUT')));
  647. }
  648. /**
  649. * 通过api删除一个项目成员
  650. * Delete a gitlab project member by api.
  651. *
  652. * @param int $gitlabID
  653. * @param int $projectID
  654. * @param int $memberID
  655. * @access public
  656. * @return object|array|null
  657. */
  658. public function apiDeleteProjectMember($gitlabID, $projectID, $memberID)
  659. {
  660. $apiRoot = $this->getApiRoot($gitlabID);
  661. $url = sprintf($apiRoot, "/projects/{$projectID}/members/{$memberID}");
  662. return json_decode(commonModel::http($url, array(), array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  663. }
  664. /**
  665. * 通过api创建一个群组成员。
  666. * Add a gitlab group member by api.
  667. *
  668. * @param int $gitlabID
  669. * @param int $groupID
  670. * @param object $member
  671. * @access public
  672. * @return object|array|null|false
  673. */
  674. public function apiCreateGroupMember($gitlabID, $groupID, $member)
  675. {
  676. if(empty($member->user_id) or empty($member->access_level)) return false;
  677. $apiRoot = $this->getApiRoot($gitlabID);
  678. $url = sprintf($apiRoot, "/groups/{$groupID}/members");
  679. return json_decode(commonModel::http($url, $member));
  680. }
  681. /**
  682. * 通过api更新一个gitlab群组成员。
  683. * Update a gitlab group member by api.
  684. *
  685. * @param int $gitlabID
  686. * @param int $groupID
  687. * @param object $member
  688. * @access public
  689. * @return object|array|null|false
  690. */
  691. public function apiUpdateGroupMember($gitlabID, $groupID, $member)
  692. {
  693. if(empty($member->user_id) or empty($member->access_level)) return false;
  694. $apiRoot = $this->getApiRoot($gitlabID);
  695. $url = sprintf($apiRoot, "/groups/{$groupID}/members/{$member->user_id}");
  696. return json_decode(commonModel::http($url, $member, array(CURLOPT_CUSTOMREQUEST => 'PUT')));
  697. }
  698. /**
  699. * 通过api删除一个gitlab群组成员。
  700. * Delete a gitlab group member by api.
  701. *
  702. * @param int $gitlabID
  703. * @param int $groupID
  704. * @param int $memberID
  705. * @access public
  706. * @return object|array|null
  707. */
  708. public function apiDeleteGroupMember($gitlabID, $groupID, $memberID)
  709. {
  710. $apiRoot = $this->getApiRoot($gitlabID);
  711. $url = sprintf($apiRoot, "/groups/{$groupID}/members/{$memberID}");
  712. return json_decode(commonModel::http($url, array(), array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  713. }
  714. /**
  715. * 通过api创建一个gitlab用户.
  716. * Create a gitlab user by api.
  717. *
  718. * @param int $gitlabID
  719. * @param object $user
  720. * @access public
  721. * @return object|array|null|false
  722. */
  723. public function apiCreateUser($gitlabID, $user)
  724. {
  725. if(empty($user->name) or empty($user->username) or empty($user->email) or empty($user->password)) return false;
  726. $apiRoot = $this->getApiRoot($gitlabID);
  727. $url = sprintf($apiRoot, "/users");
  728. return json_decode(commonModel::http($url, $user, array(CURLOPT_CUSTOMREQUEST => 'POST')));
  729. }
  730. /**
  731. * 通过api更新一个gitlab用户。
  732. * Update a gitlab user by api.
  733. *
  734. * @param int $gitlabID
  735. * @param object $user
  736. * @access public
  737. * @return object|array|null|false
  738. */
  739. public function apiUpdateUser($gitlabID, $user)
  740. {
  741. if(empty($user->id)) return false;
  742. $apiRoot = $this->getApiRoot($gitlabID);
  743. $url = sprintf($apiRoot, "/users/{$user->id}");
  744. return json_decode(commonModel::http($url, $user, array(CURLOPT_CUSTOMREQUEST => 'PUT')));
  745. }
  746. /**
  747. * 通过api更新一个gitlab群组。
  748. * Update a gitlab group by api.
  749. *
  750. * @param int $gitlabID
  751. * @param object $group
  752. * @access public
  753. * @return object|array|null|false
  754. */
  755. public function apiUpdateGroup($gitlabID, $group)
  756. {
  757. if(empty($group->id)) return false;
  758. $apiRoot = $this->getApiRoot($gitlabID);
  759. $url = sprintf($apiRoot, "/groups/{$group->id}");
  760. return json_decode(commonModel::http($url, $group, array(CURLOPT_CUSTOMREQUEST => 'PUT')));
  761. }
  762. /**
  763. * 通过api删除一个gitlab群组。
  764. * Delete a gitlab group by api.
  765. *
  766. * @param int $gitlabID
  767. * @param int $groupID
  768. * @access public
  769. * @return object|array|null|false
  770. */
  771. public function apiDeleteGroup($gitlabID, $groupID)
  772. {
  773. if(empty($groupID)) return false;
  774. $apiRoot = $this->getApiRoot($gitlabID);
  775. $url = sprintf($apiRoot, "/groups/{$groupID}");
  776. return json_decode(commonModel::http($url, array(), array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  777. }
  778. /**
  779. * 通过api更新一个gitlab项目。
  780. * Update a gitlab project by api.
  781. *
  782. * @param int $gitlabID
  783. * @param object $project
  784. * @access public
  785. * @return object|array|null|false
  786. */
  787. public function apiUpdateProject($gitlabID, $project)
  788. {
  789. if(empty($project->id)) return false;
  790. $apiRoot = $this->getApiRoot($gitlabID);
  791. $url = sprintf($apiRoot, "/projects/{$project->id}");
  792. return json_decode(commonModel::http($url, $project, array(CURLOPT_CUSTOMREQUEST => 'PUT')));
  793. }
  794. /**
  795. * 通过api删除一个gitlab项目。
  796. * Delete a gitlab project by api.
  797. *
  798. * @param int $gitlabID
  799. * @param int $projectID
  800. * @access public
  801. * @return object|array|null|false
  802. */
  803. public function apiDeleteProject($gitlabID, $projectID)
  804. {
  805. if(empty($projectID)) return false;
  806. $apiRoot = $this->getApiRoot($gitlabID);
  807. $url = sprintf($apiRoot, "/projects/{$projectID}");
  808. return json_decode(commonModel::http($url, array(), array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  809. }
  810. /**
  811. * 通过api删除一个gitlab用户。
  812. * Delete a gitlab user by api.
  813. *
  814. * @param int $gitlabID
  815. * @param int $userID
  816. * @access public
  817. * @return object|array|null|false
  818. */
  819. public function apiDeleteUser($gitlabID, $userID)
  820. {
  821. if(empty($userID)) return false;
  822. $apiRoot = $this->getApiRoot($gitlabID);
  823. $url = sprintf($apiRoot, "/users/{$userID}");
  824. return json_decode(commonModel::http($url, array(), array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  825. }
  826. /**
  827. * 通过api创建一个gitlab用户。
  828. * Create a gitlab user by api.
  829. *
  830. * @param int $gitlabID
  831. * @param int $projectID
  832. * @param object $branch
  833. * @access public
  834. * @return object|array|null|false
  835. */
  836. public function apiCreateBranch($gitlabID, $projectID, $branch)
  837. {
  838. if(empty($branch->branch) or empty($branch->ref)) return false;
  839. $apiRoot = $this->getApiRoot($gitlabID);
  840. $url = sprintf($apiRoot, "/projects/{$projectID}/repository/branches");
  841. return json_decode(commonModel::http($url, $branch, array(), array(), 'json'));
  842. }
  843. /**
  844. * 通过API创建一个标签。
  845. * Creates a new tag in the GitLab repository using the GitLab API.
  846. * @link https://docs.gitlab.com/ee/api/tags.html#create-a-new-tag
  847. *
  848. * @param int $gitlabID The ID of the GitLab instance.
  849. * @param int $projectID The ID of the project in GitLab.
  850. * @param object $tag An object containing the tag details, including the tag name and reference.
  851. * @return object|array|null|false The response from the GitLab API, or false if the tag name or reference is empty.
  852. */
  853. public function apiCreateTag($gitlabID, $projectID, $tag)
  854. {
  855. if(empty($tag->tag_name) or empty($tag->ref)) return false;
  856. $apiRoot = $this->getApiRoot($gitlabID);
  857. $url = sprintf($apiRoot, "/projects/{$projectID}/repository/tags");
  858. return json_decode(commonModel::http($url, $tag, array(), array(), 'json'));
  859. }
  860. /**
  861. * 通过api获取一个项目信息。
  862. * Get single project by API.
  863. *
  864. * @param int $gitlabID
  865. * @param int $projectID
  866. * @param bool $useUser
  867. * @access public
  868. * @return object|array|null
  869. */
  870. public function apiGetSingleProject($gitlabID, $projectID, $useUser = true)
  871. {
  872. if(isset($this->projects[$gitlabID][$projectID])) return $this->projects[$gitlabID][$projectID];
  873. $url = sprintf($this->getApiRoot($gitlabID, $useUser), "/projects/$projectID");
  874. $this->projects[$gitlabID][$projectID] = json_decode(commonModel::http($url));
  875. return $this->projects[$gitlabID][$projectID];
  876. }
  877. /**
  878. * 通过api获取一个用户。
  879. * Get single user by API.
  880. *
  881. * @param int $gitlabID
  882. * @param int $userID
  883. * @access public
  884. * @return object|array|null
  885. */
  886. public function apiGetSingleUser($gitlabID, $userID)
  887. {
  888. $url = sprintf($this->getApiRoot($gitlabID, false), "/users/$userID");
  889. return json_decode(commonModel::http($url));
  890. }
  891. /**
  892. * 通过api获取一个gitlab群组。
  893. * Get single group by API.
  894. *
  895. * @param int $gitlabID
  896. * @param int $groupID
  897. * @access public
  898. * @return object|array|null
  899. */
  900. public function apiGetSingleGroup($gitlabID, $groupID)
  901. {
  902. $url = sprintf($this->getApiRoot($gitlabID), "/groups/$groupID");
  903. return json_decode(commonModel::http($url));
  904. }
  905. /**
  906. * 获取gitlab项目最新成员。
  907. * Get project all members(users and users in groups).
  908. *
  909. * @param int $gitlabID
  910. * @param int $projectID
  911. * @param int $userID
  912. * @access public
  913. * @return object|array|null
  914. */
  915. public function apiGetProjectMembers($gitlabID, $projectID, $userID = 0)
  916. {
  917. $path = "/projects/{$projectID}/members/all" . ($userID ? "/{$userID}" : '');
  918. $url = sprintf($this->getApiRoot($gitlabID), $path);
  919. return json_decode(commonModel::http($url));
  920. }
  921. /**
  922. * 通过api获取项目一个分支。
  923. * Get single branch by API.
  924. *
  925. * @param int $gitlabID
  926. * @param int $projectID
  927. * @param string $branch
  928. * @access public
  929. * @return object|array|null
  930. */
  931. public function apiGetSingleBranch($gitlabID, $projectID, $branch)
  932. {
  933. $url = sprintf($this->getApiRoot($gitlabID), "/projects/$projectID/repository/branches/$branch");
  934. return json_decode(commonModel::http($url));
  935. }
  936. /**
  937. * 通过api获取项目 hooks。
  938. * Get hooks.
  939. *
  940. * @param int $gitlabID
  941. * @param int $projectID
  942. * @access public
  943. * @link https://docs.gitlab.com/ee/api/projects.html#list-project-hooks
  944. * @return object|array|null
  945. * @param int $hookID
  946. */
  947. public function apiGetHooks($gitlabID, $projectID, $hookID = 0)
  948. {
  949. $apiRoot = $this->getApiRoot($gitlabID, false);
  950. $apiPath = "/projects/{$projectID}/hooks" . ($hookID ? "/{$hookID}" : '');
  951. $url = sprintf($apiRoot, $apiPath);
  952. return json_decode(commonModel::http($url));
  953. }
  954. /**
  955. * 通过api创建hook。
  956. * Create hook by api.
  957. *
  958. * @param int $gitlabID
  959. * @param int $projectID
  960. * @param object $hook
  961. * @access public
  962. * @link https://docs.gitlab.com/ee/api/projects.html#add-project-hook
  963. * @return object|array|null|false
  964. */
  965. public function apiCreateHook($gitlabID, $projectID, $hook)
  966. {
  967. if(!isset($hook->url)) return false;
  968. $newHook = new stdclass;
  969. $newHook->enable_ssl_verification = "false"; /* Disable ssl verification for every hook. */
  970. foreach($hook as $index => $item) $newHook->$index= $item;
  971. $apiRoot = $this->getApiRoot($gitlabID, false);
  972. $url = sprintf($apiRoot, "/projects/{$projectID}/hooks");
  973. return json_decode(commonModel::http($url, $newHook, array(), array(), 'json'));
  974. }
  975. /**
  976. * 通过api删除hook。
  977. * Delete hook by api.
  978. *
  979. * @param int $gitlabID
  980. * @param int $projectID
  981. * @param int $hookID
  982. * @access public
  983. * @link https://docs.gitlab.com/ee/api/projects.html#delete-project-hook
  984. * @return object|array|null
  985. */
  986. public function apiDeleteHook($gitlabID, $projectID, $hookID)
  987. {
  988. $apiRoot = $this->getApiRoot($gitlabID, false);
  989. $url = sprintf($apiRoot, "/projects/{$projectID}/hooks/{$hookID}");
  990. return json_decode(commonModel::http($url, array(), array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  991. }
  992. /**
  993. * 添加一个推送和合并请求事件的webhook到gitlab项目。
  994. * Add webhook with push and merge request events to GitLab project.
  995. *
  996. * @param object $repo
  997. * @param string $token
  998. * @access public
  999. * @return bool|array
  1000. */
  1001. public function addPushWebhook($repo, $token = '')
  1002. {
  1003. $systemURL = dirname(common::getSysURL() . $_SERVER['REQUEST_URI']);
  1004. $hook = new stdClass;
  1005. $hook->url = $systemURL . '/api.php/v1/gitlab/webhook?repoID='. $repo->id;
  1006. $hook->push_events = true;
  1007. $hook->merge_requests_events = true;
  1008. if($token) $hook->token = $token;
  1009. /* Return an empty array if where is one existing webhook. */
  1010. if($this->isWebhookExists($repo, $hook->url)) return true;
  1011. $result = $this->apiCreateHook((int)$repo->serviceHost, (int)$repo->serviceProject, $hook);
  1012. if(!empty($result->id)) return true;
  1013. if(!empty($result->message)) return array('result' => 'fail', 'message' => $this->lang->gitlab->failCreateWebhook);
  1014. return false;
  1015. }
  1016. /**
  1017. * 检查webhook是否存在。
  1018. * Check if Webhook exists.
  1019. *
  1020. * @param object $repo
  1021. * @param string $url
  1022. * @return bool
  1023. */
  1024. public function isWebhookExists($repo, $url = '')
  1025. {
  1026. $hookList = $this->apiGetHooks((int)$repo->serviceHost, (int)$repo->serviceProject);
  1027. foreach($hookList as $hook)
  1028. {
  1029. if(empty($hook->url)) continue;
  1030. if($hook->url == $url) return true;
  1031. }
  1032. return false;
  1033. }
  1034. /**
  1035. * 通过api更新hook。
  1036. * Update hook by api.
  1037. *
  1038. * @param int $gitlabID
  1039. * @param int $projectID
  1040. * @param int $hookID
  1041. * @param object $hook
  1042. * @access public
  1043. * @link https://docs.gitlab.com/ee/api/projects.html#edit-project-hook
  1044. * @return string|false
  1045. */
  1046. public function apiUpdateHook($gitlabID, $projectID, $hookID, $hook)
  1047. {
  1048. $apiRoot = $this->getApiRoot($gitlabID, false);
  1049. if(!isset($hook->url)) return false;
  1050. $newHook = new stdclass;
  1051. $newHook->enable_ssl_verification = "false"; /* Disable ssl verification for every hook. */
  1052. foreach($hook as $index => $item) $newHook->$index= $item;
  1053. $url = sprintf($apiRoot, "/projects/{$projectID}/hooks/{$hookID}");
  1054. return commonModel::http($url, $newHook, array(CURLOPT_CUSTOMREQUEST => 'PUT'));
  1055. }
  1056. /**
  1057. * 创建gitlab项目的项目标签。
  1058. * Create Label for gitlab project.
  1059. *
  1060. * @param int $gitlabID
  1061. * @param int $projectID
  1062. * @param object $label
  1063. * @access public
  1064. * @return object|array|null|false
  1065. */
  1066. public function apiCreateLabel($gitlabID, $projectID, $label)
  1067. {
  1068. if(empty($label->name) or empty($label->color)) return false;
  1069. $apiRoot = $this->getApiRoot($gitlabID);
  1070. $url = sprintf($apiRoot, "/projects/{$projectID}/labels/");
  1071. return json_decode(commonModel::http($url, $label));
  1072. }
  1073. /**
  1074. * 获取项目的项目标签。
  1075. * Get labels of project by api.
  1076. *
  1077. * @param int $gitlabID
  1078. * @param int $projectID
  1079. * @access public
  1080. * @return object|array|null
  1081. */
  1082. public function apiGetLabels($gitlabID, $projectID)
  1083. {
  1084. $apiRoot = $this->getApiRoot($gitlabID);
  1085. $url = sprintf($apiRoot, "/projects/{$projectID}/labels/");
  1086. $response = commonModel::http($url);
  1087. return json_decode($response);
  1088. }
  1089. /**
  1090. * 通过api删除一个项目标签。
  1091. * Delete a Label with labelName by api.
  1092. *
  1093. * @param int $gitlabID
  1094. * @param int $projectID
  1095. * @param string $labelName
  1096. * @access public
  1097. * @return object|array|null|false
  1098. */
  1099. public function apiDeleteLabel($gitlabID, $projectID, $labelName)
  1100. {
  1101. $labels = $this->apiGetLabels($gitlabID, $projectID);
  1102. if(!$labels) return false;
  1103. foreach($labels as $label)
  1104. {
  1105. if(isset($label->name) && $label->name == $labelName) $labelID = $label->id;
  1106. }
  1107. if(empty($labelID)) return false;
  1108. $apiRoot = $this->getApiRoot($gitlabID);
  1109. $url = sprintf($apiRoot, "/projects/{$projectID}/labels/{$labelID}");
  1110. return json_decode(commonModel::http($url, null, array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  1111. }
  1112. /**
  1113. * 通过api获取一个issue。
  1114. * Get single issue by api.
  1115. *
  1116. * @param int $gitlabID
  1117. * @param int $projectID
  1118. * @param int $issueID
  1119. * @access public
  1120. * @return object|array|null
  1121. */
  1122. public function apiGetSingleIssue($gitlabID, $projectID, $issueID)
  1123. {
  1124. $url = sprintf($this->getApiRoot($gitlabID), "/projects/$projectID/issues/{$issueID}");
  1125. return json_decode(commonModel::http($url));
  1126. }
  1127. /**
  1128. * 通过api获取issue列表。
  1129. * Get gitlab issues by api.
  1130. *
  1131. * @param int $gitlabID
  1132. * @param int $projectID
  1133. * @param string $options
  1134. * @access public
  1135. * @return object|array|null
  1136. */
  1137. public function apiGetIssues($gitlabID, $projectID, $options = '')
  1138. {
  1139. if($options)
  1140. {
  1141. $url = sprintf($this->getApiRoot($gitlabID), "/projects/{$projectID}/issues") . '&per_page=20' . $options;
  1142. }
  1143. else
  1144. {
  1145. $url = sprintf($this->getApiRoot($gitlabID), "/projects/{$projectID}/issues") . '&per_page=20';
  1146. }
  1147. return json_decode(commonModel::http($url));
  1148. }
  1149. /**
  1150. * 通过api删除一个issue。
  1151. * Delete an issue by api.
  1152. *
  1153. * @param int $gitlabID
  1154. * @param int $projectID
  1155. * @param int $issueID
  1156. * @access public
  1157. * @return object|array|null
  1158. */
  1159. public function apiDeleteIssue($gitlabID, $projectID, $issueID)
  1160. {
  1161. $apiRoot = $this->getApiRoot($gitlabID);
  1162. $url = sprintf($apiRoot, "/projects/{$projectID}/issues/{$issueID}");
  1163. return json_decode(commonModel::http($url, null, array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  1164. }
  1165. /**
  1166. * 通过api创建一个流水线。
  1167. * Create a new pipeline by api.
  1168. *
  1169. * @param int $gitlabID
  1170. * @param int $projectID
  1171. * @param object $params
  1172. * @access public
  1173. * @return object
  1174. * @docment https://docs.gitlab.com/ee/api/pipelines.html#create-a-new-pipeline
  1175. */
  1176. public function apiCreatePipeline($gitlabID, $projectID, $params)
  1177. {
  1178. if(!is_string($params)) $params = json_encode($params);
  1179. $url = sprintf($this->getApiRoot($gitlabID), "/projects/{$projectID}/pipeline");
  1180. return json_decode(commonModel::http($url, $params, array(), array("Content-Type: application/json")));
  1181. }
  1182. /**
  1183. * 通过api获取一个流水线。
  1184. * Get single pipeline by api.
  1185. *
  1186. * @param int $gitlabID
  1187. * @param int $projectID
  1188. * @param int $pipelineID
  1189. * @access public
  1190. * @return object|array|null
  1191. * @docment https://docs.gitlab.com/ee/api/pipelines.html#get-a-single-pipeline
  1192. */
  1193. public function apiGetSinglePipeline($gitlabID, $projectID, $pipelineID)
  1194. {
  1195. $url = sprintf($this->getApiRoot($gitlabID), "/projects/{$projectID}/pipelines/{$pipelineID}");
  1196. return json_decode(commonModel::http($url));
  1197. }
  1198. /**
  1199. * 通过api获取流水线jobs。
  1200. * List pipeline jobs by api.
  1201. *
  1202. * @param int $gitlabID
  1203. * @param int $projectID
  1204. * @param int $pipelineID
  1205. * @access public
  1206. * @return object|array|null
  1207. * @docment https://docs.gitlab.com/ee/api/jobs.html#list-pipeline-jobs
  1208. */
  1209. public function apiGetJobs($gitlabID, $projectID, $pipelineID)
  1210. {
  1211. $url = sprintf($this->getApiRoot($gitlabID), "/projects/{$projectID}/pipelines/{$pipelineID}/jobs");
  1212. return json_decode(commonModel::http($url));
  1213. }
  1214. /**
  1215. * 通过api获取一个job。
  1216. * Get a single job by api.
  1217. *
  1218. * @param int $gitlabID
  1219. * @param int $projectID
  1220. * @param int $jobID
  1221. * @return object|array|null
  1222. * @docment https://docs.gitlab.com/ee/api/jobs.html#get-a-single-job
  1223. */
  1224. public function apiGetSingleJob($gitlabID, $projectID, $jobID)
  1225. {
  1226. $url = sprintf($this->getApiRoot($gitlabID), "/projects/{$projectID}/jobs/{$jobID}");
  1227. return json_decode(commonModel::http($url));
  1228. }
  1229. /**
  1230. * 通过api获取日志。
  1231. * Get a log file by api.
  1232. *
  1233. * @param int $gitlabID
  1234. * @param int $projectID
  1235. * @param int $jobID
  1236. * @return string
  1237. * @docment https://docs.gitlab.com/ee/api/jobs.html#get-a-log-file
  1238. */
  1239. public function apiGetJobLog($gitlabID, $projectID, $jobID)
  1240. {
  1241. $url = sprintf($this->getApiRoot($gitlabID), "/projects/{$projectID}/jobs/{$jobID}/trace");
  1242. return commonModel::http($url);
  1243. }
  1244. /**
  1245. * 通过api获取代码库分支列表。
  1246. * Get project repository branches by api.
  1247. *
  1248. * @param int $gitlabID
  1249. * @param int $projectID
  1250. * @access public
  1251. * @return array
  1252. */
  1253. public function apiGetBranches($gitlabID, $projectID)
  1254. {
  1255. $url = sprintf($this->getApiRoot($gitlabID), "/projects/{$projectID}/repository/branches");
  1256. $allResults = array();
  1257. for($page = 1; true; $page++)
  1258. {
  1259. $results = json_decode(commonModel::http($url . "&&page={$page}&per_page=100"));
  1260. if(!is_array($results)) break;
  1261. if(!empty($results)) $allResults = array_merge($allResults, $results);
  1262. if(count($results) < 100) break;
  1263. }
  1264. return $allResults;
  1265. }
  1266. /**
  1267. * 通过api获取代码库标签列表。
  1268. * Get project repository tags by api.
  1269. *
  1270. * @param int $gitlabID
  1271. * @param int $projectID
  1272. * @param string $orderBy
  1273. * @param string $keyword
  1274. * @param object $pager
  1275. * @access public
  1276. * @return object|array|null
  1277. */
  1278. public function apiGetTags($gitlabID, $projectID, $orderBy = '', $keyword = '', $pager = null)
  1279. {
  1280. $apiRoot = $this->getApiRoot($gitlabID);
  1281. /* Parse order string. */
  1282. if($orderBy)
  1283. {
  1284. list($order, $sort) = explode('_', $orderBy);
  1285. $apiRoot .= "&order_by={$order}&sort={$sort}";
  1286. }
  1287. if($keyword) $apiRoot .= "&search={$keyword}";
  1288. if(!$pager)
  1289. {
  1290. $allResults = array();
  1291. $url = sprintf($apiRoot, "/projects/{$projectID}/repository/tags");
  1292. for($page = 1; true; $page++)
  1293. {
  1294. $results = json_decode(commonModel::http($url . "&&page={$page}&per_page=100"));
  1295. if(!is_array($results)) break;
  1296. if(!empty($results)) $allResults = array_merge($allResults, $results);
  1297. if(count($results) < 100) break;
  1298. }
  1299. return $allResults;
  1300. }
  1301. else
  1302. {
  1303. $apiRoot .= "&per_page={$pager->recPerPage}&page={$pager->pageID}";
  1304. $url = sprintf($apiRoot, "/projects/{$projectID}/repository/tags");
  1305. $result = commonModel::http($url, null, array(), array(), 'data', 'GET', 30, true, false);
  1306. $header = $result['header'];
  1307. $pager->setRecTotal(isset($header['X-Total']) ? $header['X-Total'] : $header['x-total']);
  1308. $pager->setPageTotal();
  1309. if($pager->pageID > $pager->pageTotal) $pager->setPageID($pager->pageTotal);
  1310. return json_decode($result['body']);
  1311. }
  1312. }
  1313. /**
  1314. * 通过api删除一个标签。
  1315. * Delete a gitlab tag by api.
  1316. *
  1317. * @param int $gitlabID
  1318. * @param int $projectID
  1319. * @param string $tagName
  1320. * @access public
  1321. * @return object|array|null|false
  1322. */
  1323. public function apiDeleteTag($gitlabID, $projectID, $tagName = '')
  1324. {
  1325. if(!(int)$gitlabID or !(int)$projectID or empty($tagName)) return false;
  1326. $apiRoot = $this->getApiRoot($gitlabID);
  1327. $tagName = urlencode($tagName);
  1328. $url = sprintf($apiRoot, "/projects/{$projectID}/repository/tags/{$tagName}");
  1329. return json_decode(commonModel::http($url, array(), array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  1330. }
  1331. /**
  1332. * 获取一个项目的标签策略。
  1333. * Get protect tags of one project.
  1334. *
  1335. * @param int $gitlabID
  1336. * @param int $projectID
  1337. * @access public
  1338. * @return array
  1339. */
  1340. public function apiGetTagPrivs($gitlabID, $projectID)
  1341. {
  1342. $apiRoot = $this->getApiRoot($gitlabID);
  1343. $url = sprintf($apiRoot, "/projects/{$projectID}/protected_tags");
  1344. $allResults = array();
  1345. for($page = 1; true; $page++)
  1346. {
  1347. $results = json_decode(commonModel::http($url . "&&page={$page}&per_page=100"));
  1348. if(!is_array($results)) break;
  1349. if(!empty($results)) $allResults = array_merge($allResults, $results);
  1350. if(count($results) < 100) break;
  1351. }
  1352. $tags = array();
  1353. foreach($allResults as $tag) $tags[$tag->name] = $tag;
  1354. return $tags;
  1355. }
  1356. /**
  1357. * 通过api删除一个gitlab项目tag。
  1358. * Delete a gitlab protect tag by api.
  1359. *
  1360. * @param int $gitlabID
  1361. * @param int $projectID
  1362. * @param string $tag
  1363. * @access public
  1364. * @return object|array|null|false
  1365. */
  1366. public function apiDeleteTagPriv($gitlabID, $projectID, $tag)
  1367. {
  1368. if(empty($gitlabID)) return false;
  1369. $apiRoot = $this->getApiRoot($gitlabID);
  1370. $tag = urlencode($tag);
  1371. $url = sprintf($apiRoot, "/projects/{$projectID}/protected_tags/{$tag}");
  1372. return json_decode(commonModel::http($url, array(), array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  1373. }
  1374. /**
  1375. * 通过HTTP_X_GITLAB_TOKEN检查webhook token。
  1376. * Check webhook token by HTTP_X_GITLAB_TOKEN.
  1377. *
  1378. * @access public
  1379. * @return void
  1380. */
  1381. public function webhookCheckToken()
  1382. {
  1383. $gitlab = $this->getByID($this->get->gitlab);
  1384. if($gitlab->private != $_SERVER["HTTP_X_GITLAB_TOKEN"]) echo 'Token error.';
  1385. }
  1386. /**
  1387. * 通过webhook同步issue。
  1388. * Webhook sync issue.
  1389. *
  1390. * @param object $issue
  1391. * @access public
  1392. * @return void
  1393. */
  1394. public function webhookSyncIssue($issue)
  1395. {
  1396. $tableName = zget($this->config->gitlab->objectTables, $issue->objectType, '');
  1397. if(!$tableName || empty($issue->objectID) || empty((array)$issue->object)) return false;
  1398. $this->dao->update($tableName)->data($issue->object)->where('id')->eq($issue->objectID)->exec();
  1399. return !dao::isError();
  1400. }
  1401. /**
  1402. * 通过issue webhook指派禅道任务、需求、bug。
  1403. * Process webhook issue assign option.
  1404. *
  1405. * @param object $issue
  1406. * @access public
  1407. * @return bool
  1408. */
  1409. public function webhookAssignIssue($issue)
  1410. {
  1411. $tableName = zget($this->config->gitlab->objectTables, $issue->objectType, '');
  1412. if(!$tableName) return false;
  1413. $data = $issue->object;
  1414. $data->assignedDate = zget($data, 'lastEditedDate', helper::now());
  1415. $data->assignedTo = zget($data, 'assignedTo', '');
  1416. $this->dao->update($tableName)->data($data)->where('id')->eq($issue->objectID)->exec();
  1417. if(dao::isError()) return false;
  1418. $oldObject = $this->dao->findById($issue->objectID)->from($tableName)->fetch();
  1419. if(!$oldObject) return false;
  1420. $changes = common::createChanges($oldObject, $data);
  1421. $actionID = $this->loadModel('action')->create($issue->objectType, $issue->objectID, 'Assigned', "Assigned by webhook by gitlab issue : {$issue->issue->url}", $data->assignedTo);
  1422. $this->action->logHistory($actionID, $changes);
  1423. return true;
  1424. }
  1425. /**
  1426. * 通过issue webhook关闭禅道任务、需求、bug。
  1427. * Process issue close option.
  1428. *
  1429. * @param object $issue
  1430. * @access public
  1431. * @return bool
  1432. */
  1433. public function webhookCloseIssue($issue)
  1434. {
  1435. $tableName = zget($this->config->gitlab->objectTables, $issue->objectType, '');
  1436. if(!$tableName) return false;
  1437. $data = $issue->object;
  1438. $data->assignedTo = 'closed';
  1439. $data->status = 'closed';
  1440. $data->closedBy = zget($data, 'lastEditedBy', '');
  1441. $data->closedDate = zget($data, 'lastEditedDate', helper::now());
  1442. $this->dao->update($tableName)->data($data)->where('id')->eq($issue->objectID)->exec();
  1443. if(dao::isError()) return false;
  1444. $oldObject = $this->dao->findById($issue->objectID)->from($tableName)->fetch();
  1445. if(!$oldObject) return false;
  1446. $changes = common::createChanges($oldObject, $data);
  1447. $actionID = $this->loadModel('action')->create($issue->objectType, $issue->objectID, 'Closed', "Closed by gitlab issue: {$issue->issue->url}.");
  1448. $this->action->logHistory($actionID, $changes);
  1449. return true;
  1450. }
  1451. /**
  1452. * 创建一个gitlab项目标签。
  1453. * Create zentao object label for gitlab project.
  1454. *
  1455. * @param int $gitlabID
  1456. * @param int $projectID
  1457. * @param string $objectType
  1458. * @param string $objectID
  1459. * @access public
  1460. * @return object|array|null|false
  1461. */
  1462. public function createZentaoObjectLabel($gitlabID, $projectID, $objectType, $objectID)
  1463. {
  1464. $label = new stdclass;
  1465. $label->name = sprintf($this->config->gitlab->zentaoObjectLabel->name, $objectType, $objectID);
  1466. $label->color = $this->config->gitlab->zentaoObjectLabel->color->$objectType;
  1467. $label->description = common::getSysURL() . helper::createLink($objectType, 'view', "id={$objectID}");
  1468. return $this->apiCreateLabel($gitlabID, $projectID, $label);
  1469. }
  1470. /**
  1471. * 从禅道和gtilab上删除一个issue。
  1472. * Delete an issue from zentao and gitlab.
  1473. *
  1474. * @param string $objectType
  1475. * @param int $objectID
  1476. * @param int $issueID
  1477. * @access public
  1478. * @return void
  1479. */
  1480. public function deleteIssue($objectType, $objectID, $issueID)
  1481. {
  1482. $relation = $this->getRelationByObject($objectType, $objectID);
  1483. if(!empty($relation)) $this->dao->delete()->from(TABLE_RELATION)->where('id')->eq($relation->id)->exec();
  1484. $this->apiDeleteIssue((int)$relation->gitlabID, (int)$relation->projectID, $issueID);
  1485. }
  1486. /**
  1487. * 保存同步的issut到关联表。
  1488. * Save synced issue to relation table.
  1489. *
  1490. * @param string $objectType
  1491. * @param object $object
  1492. * @param int $gitlabID
  1493. * @param object $issue
  1494. * @access public
  1495. * @return bool
  1496. */
  1497. public function saveIssueRelation($objectType, $object, $gitlabID, $issue)
  1498. {
  1499. if(empty($issue->iid) or empty($issue->project_id)) return false;
  1500. $relation = new stdclass;
  1501. $relation->product = zget($object, 'product', 0);
  1502. $relation->execution = zget($object, 'execution', 0);
  1503. $relation->AType = $objectType;
  1504. $relation->AID = $object->id;
  1505. $relation->AVersion = '';
  1506. $relation->relation = 'gitlab';
  1507. $relation->BType = 'issue';
  1508. $relation->BID = $issue->iid;
  1509. $relation->BVersion = $issue->project_id;
  1510. $relation->extra = $gitlabID;
  1511. $this->dao->replace(TABLE_RELATION)->data($relation)->exec();
  1512. return true;
  1513. }
  1514. /**
  1515. * 保存导入issue。
  1516. * Save imported issue.
  1517. *
  1518. * @param int $gitlabID
  1519. * @param int $projectID
  1520. * @param string $objectType
  1521. * @param int $objectID
  1522. * @param object $issue
  1523. * @access public
  1524. * @return void
  1525. * @param object $object
  1526. */
  1527. public function saveImportedIssue($gitlabID, $projectID, $objectType, $objectID, $issue, $object)
  1528. {
  1529. $label = $this->createZentaoObjectLabel($gitlabID, $projectID, $objectType, (string)$objectID);
  1530. $data = new stdclass;
  1531. if(isset($label->name)) $data->labels = $label->name;
  1532. if(isset($label->message) && $label->message == 'Label already exists') $data->labels = sprintf($this->config->gitlab->zentaoObjectLabel->name, $objectType, $objectID);
  1533. $apiRoot = $this->getApiRoot($gitlabID);
  1534. $url = sprintf($apiRoot, "/projects/{$projectID}/issues/{$issue->iid}");
  1535. commonModel::http($url, $data, array(CURLOPT_CUSTOMREQUEST => 'PUT'));
  1536. $this->saveIssueRelation($objectType, $object, $gitlabID, $issue);
  1537. }
  1538. /**
  1539. * 创建一个gitlab项目。
  1540. * Create gitlab project.
  1541. *
  1542. * @param int $gitlabID
  1543. * @param object $project
  1544. * @access public
  1545. * @return bool
  1546. */
  1547. public function createProject($gitlabID, $project)
  1548. {
  1549. if(empty($project->name)) dao::$errors['name'][] = $this->lang->gitlab->project->emptyNameError;
  1550. if(empty($project->path)) dao::$errors['path'][] = $this->lang->gitlab->project->emptyPathError;
  1551. if(dao::isError()) return false;
  1552. $response = $this->apiCreateProject($gitlabID, $project);
  1553. if(!empty($response->id))
  1554. {
  1555. $this->loadModel('action')->create('gitlabproject', $response->id, 'created', '', $response->name);
  1556. return true;
  1557. }
  1558. return $this->apiErrorHandling($response);
  1559. }
  1560. /**
  1561. * 编辑一个gitlab项目。
  1562. * Edit gitlab project.
  1563. *
  1564. * @param int $gitlabID
  1565. * @access public
  1566. * @return bool
  1567. * @param object $project
  1568. */
  1569. public function editProject($gitlabID, $project)
  1570. {
  1571. if(empty($project->name)) dao::$errors['name'][] = $this->lang->gitlab->project->emptyNameError;
  1572. if(dao::isError()) return false;
  1573. $response = $this->apiUpdateProject($gitlabID, $project);
  1574. if(!empty($response->id))
  1575. {
  1576. $this->loadModel('action')->create('gitlabproject', $project->id, 'edited', '', $project->name);
  1577. return true;
  1578. }
  1579. return $this->apiErrorHandling($response);
  1580. }
  1581. /**
  1582. * 创建一个gitlab用户。
  1583. * Create a gitlab user.
  1584. *
  1585. * @param int $gitlabID
  1586. * @param object $gitlabUser
  1587. * @access public
  1588. * @return bool
  1589. */
  1590. public function createUser($gitlabID, $gitlabUser)
  1591. {
  1592. if(empty($gitlabUser->account)) dao::$errors['account'][] = $this->lang->gitlab->user->bind . $this->lang->gitlab->user->emptyError;
  1593. if(empty($gitlabUser->name)) dao::$errors['name'][] = $this->lang->gitlab->user->name . $this->lang->gitlab->user->emptyError;
  1594. if(empty($gitlabUser->username)) dao::$errors['username'][] = $this->lang->gitlab->user->username . $this->lang->gitlab->user->emptyError;
  1595. if(empty($gitlabUser->email)) dao::$errors['email'][] = $this->lang->gitlab->user->email . $this->lang->gitlab->user->emptyError;
  1596. if(empty($gitlabUser->password)) dao::$errors['password'][] = $this->lang->gitlab->user->password . $this->lang->gitlab->user->emptyError;
  1597. if(dao::isError()) return false;
  1598. if($gitlabUser->password != $gitlabUser->password_repeat)
  1599. {
  1600. dao::$errors['password_repeat'][] = $this->lang->gitlab->user->passwordError;
  1601. return false;
  1602. }
  1603. /* Check whether the user has been bind. */
  1604. if($gitlabUser->account)
  1605. {
  1606. $zentaoBindUser = $this->dao->select('account')->from(TABLE_OAUTH)->where('providerType')->eq('gitlab')->andWhere('providerID')->eq($gitlabID)->andWhere('account')->eq($gitlabUser->account)->fetch();
  1607. if($zentaoBindUser)
  1608. {
  1609. dao::$errors['account'][] = $this->lang->gitlab->user->bindError;
  1610. return false;
  1611. }
  1612. }
  1613. $response = $this->apiCreateUser($gitlabID, $gitlabUser);
  1614. if(!empty($response->id))
  1615. {
  1616. $this->loadModel('action')->create('gitlabuser', $response->id, 'created', '', $response->name);
  1617. /* Bind user. */
  1618. if($gitlabUser->account)
  1619. {
  1620. $gitlabUserBind = new stdclass;
  1621. $gitlabUserBind->providerID = $gitlabID;
  1622. $gitlabUserBind->providerType = 'gitlab';
  1623. $gitlabUserBind->account = $gitlabUser->account;
  1624. $gitlabUserBind->openID = $response->id;
  1625. $this->dao->insert(TABLE_OAUTH)->data($gitlabUserBind)->exec();
  1626. }
  1627. return true;
  1628. }
  1629. return $this->apiErrorHandling($response);
  1630. }
  1631. /**
  1632. * 编辑一个gitlab用户。
  1633. * Edit a gitlab user.
  1634. *
  1635. * @param int $gitlabID
  1636. * @access public
  1637. * @return bool
  1638. * @param object $gitlabUser
  1639. */
  1640. public function editUser($gitlabID, $gitlabUser)
  1641. {
  1642. if(empty($gitlabUser->account)) dao::$errors['account'][] = $this->lang->gitlab->user->bind . $this->lang->gitlab->user->emptyError;
  1643. if(empty($gitlabUser->name)) dao::$errors['name'][] = $this->lang->gitlab->user->name . $this->lang->gitlab->user->emptyError;
  1644. if(empty($gitlabUser->email)) dao::$errors['email'][] = $this->lang->gitlab->user->email . $this->lang->gitlab->user->emptyError;
  1645. if(dao::isError()) return false;
  1646. if(!empty($gitlabUser->password) and $gitlabUser->password != $gitlabUser->password_repeat)
  1647. {
  1648. dao::$errors['password_repeat'][] = $this->lang->gitlab->user->passwordError;
  1649. return false;
  1650. }
  1651. /* Check whether the user has been bind. */
  1652. if($gitlabUser->account)
  1653. {
  1654. $zentaoBindUser = $this->dao->select('account,openID')->from(TABLE_OAUTH)->where('providerType')->eq('gitlab')->andWhere('providerID')->eq($gitlabID)->andWhere('account')->eq($gitlabUser->account)->fetch();
  1655. $changeBind = (!$zentaoBindUser or $zentaoBindUser->openID != $gitlabUser->id) ? true : false;
  1656. if($zentaoBindUser && $changeBind)
  1657. {
  1658. dao::$errors['account'][] = $this->lang->gitlab->user->bindError;
  1659. return false;
  1660. }
  1661. }
  1662. $response = $this->apiUpdateUser($gitlabID, $gitlabUser);
  1663. if(!empty($response->id))
  1664. {
  1665. $this->loadModel('action')->create('gitlabuser', $response->id, 'edited', '', $response->name);
  1666. /* Delete old bind. */
  1667. $this->dao->delete()->from(TABLE_OAUTH)->where('providerType')->eq('gitlab')->andWhere('providerID')->eq($gitlabID)->andWhere('openID')->eq($response->id)->andWhere('account')->ne($gitlabUser->account)->exec();
  1668. /* Bind user. */
  1669. if($gitlabUser->account && $changeBind)
  1670. {
  1671. $gitlabUserBind = new stdclass;
  1672. $gitlabUserBind->providerID = $gitlabID;
  1673. $gitlabUserBind->providerType = 'gitlab';
  1674. $gitlabUserBind->account = $gitlabUser->account;
  1675. $gitlabUserBind->openID = $response->id;
  1676. $this->dao->replace(TABLE_OAUTH)->data($gitlabUserBind)->exec();
  1677. }
  1678. return true;
  1679. }
  1680. return $this->apiErrorHandling($response);
  1681. }
  1682. /**
  1683. * 创建一个gitlab群组。
  1684. * Create a gitlab group.
  1685. *
  1686. * @param int $gitlabID
  1687. * @param object $group
  1688. * @access public
  1689. * @return bool
  1690. */
  1691. public function createGroup($gitlabID, $group)
  1692. {
  1693. if(empty($group->name)) dao::$errors['name'][] = $this->lang->gitlab->group->name . $this->lang->gitlab->group->emptyError;
  1694. if(empty($group->path)) dao::$errors['path'][] = $this->lang->gitlab->group->path . $this->lang->gitlab->group->emptyError;
  1695. if(dao::isError()) return false;
  1696. $response = $this->apiCreateGroup($gitlabID, $group);
  1697. if(!empty($response->id))
  1698. {
  1699. $this->loadModel('action')->create('gitlabgroup', $response->id, 'created', '', $response->name);
  1700. return true;
  1701. }
  1702. return $this->apiErrorHandling($response);
  1703. }
  1704. /**
  1705. * 编辑一个gitlab群组。
  1706. * Edit a gitlab group.
  1707. *
  1708. * @param int $gitlabID
  1709. * @param object $group
  1710. * @access public
  1711. * @return bool
  1712. */
  1713. public function editGroup($gitlabID, $group)
  1714. {
  1715. if(empty($group->name)) dao::$errors['name'][] = $this->lang->gitlab->group->name . $this->lang->gitlab->group->emptyError;
  1716. if(dao::isError()) return false;
  1717. $response = $this->apiUpdateGroup($gitlabID, $group);
  1718. if(!empty($response->id))
  1719. {
  1720. $this->loadModel('action')->create('gitlabgroup', $response->id, 'edited', '', $response->name);
  1721. return true;
  1722. }
  1723. return $this->apiErrorHandling($response);
  1724. }
  1725. /**
  1726. * 创建一个项目分支。
  1727. * Create a gitlab branch.
  1728. *
  1729. * @param int $gitlabID
  1730. * @param int $projectID
  1731. * @param object $branch
  1732. * @access public
  1733. * @return bool
  1734. */
  1735. public function createBranch($gitlabID, $projectID, $branch)
  1736. {
  1737. if(empty($branch->branch)) dao::$errors['branch'][] = $this->lang->gitlab->branch->name . $this->lang->gitlab->emptyError;
  1738. if(empty($branch->ref)) dao::$errors['ref'][] = $this->lang->gitlab->branch->from . $this->lang->gitlab->emptyError;
  1739. if(dao::isError()) return false;
  1740. $response = $this->apiCreateBranch($gitlabID, $projectID, $branch);
  1741. if(!empty($response->name))
  1742. {
  1743. $this->loadModel('action')->create('gitlabbranch', 0, 'created', '', $response->name);
  1744. return true;
  1745. }
  1746. if(!is_object($response)) return false;
  1747. return $this->apiErrorHandling($response);
  1748. }
  1749. /**
  1750. * 错误处理。
  1751. * Api error handling.
  1752. *
  1753. * @param object $response
  1754. * @access public
  1755. * @return bool
  1756. */
  1757. public function apiErrorHandling($response)
  1758. {
  1759. if(!empty($response->error))
  1760. {
  1761. dao::$errors[] = $response->error;
  1762. return false;
  1763. }
  1764. if(!empty($response->message))
  1765. {
  1766. if(is_string($response->message))
  1767. {
  1768. $errorKey = array_search($response->message, $this->lang->gitlab->apiError);
  1769. dao::$errors[] = $errorKey === false ? $response->message : zget($this->lang->gitlab->errorLang, $errorKey);
  1770. }
  1771. else
  1772. {
  1773. foreach($response->message as $field => $fieldErrors)
  1774. {
  1775. if(empty($fieldErrors)) continue;
  1776. if(is_string($fieldErrors))
  1777. {
  1778. $errorKey = array_search($fieldErrors, $this->lang->gitlab->apiError);
  1779. if($fieldErrors) dao::$errors[$field][] = $errorKey === false ? $fieldErrors : zget($this->lang->gitlab->errorLang, $errorKey);
  1780. }
  1781. else
  1782. {
  1783. foreach($fieldErrors as $error)
  1784. {
  1785. $errorKey = array_search($error, $this->lang->gitlab->apiError);
  1786. if($error) dao::$errors[$field][] = $errorKey === false ? $error : zget($this->lang->gitlab->errorLang, $errorKey);
  1787. }
  1788. }
  1789. }
  1790. }
  1791. }
  1792. if(!$response) dao::$errors[] = false;
  1793. return false;
  1794. }
  1795. /**
  1796. * 获取项目保护分支。
  1797. * Get protect branches of one project.
  1798. *
  1799. * @param int $gitlabID
  1800. * @param int $projectID
  1801. * @param string $keyword
  1802. * @param string $orderBy
  1803. * @access public
  1804. * @return array|object|null
  1805. */
  1806. public function apiGetBranchPrivs($gitlabID, $projectID, $keyword = '', $orderBy = 'id_desc')
  1807. {
  1808. $keyword = urlencode($keyword);
  1809. $url = sprintf($this->getApiRoot($gitlabID), "/projects/$projectID/protected_branches");
  1810. $branches = json_decode(commonModel::http($url));
  1811. if(!is_array($branches)) return $branches;
  1812. /* Parse order string. */
  1813. $order = explode('_', $orderBy);
  1814. $newBranches = array();
  1815. foreach($branches as $branch)
  1816. {
  1817. if(empty($keyword) || stristr($branch->name, $keyword)) $newBranches[$branch->{$order[0]}] = $branch;
  1818. }
  1819. if($order[1] == 'asc') ksort($newBranches);
  1820. if($order[1] == 'desc') krsort($newBranches);
  1821. return $newBranches;
  1822. }
  1823. /**
  1824. * 管理分支策略。
  1825. * Manage branch privs.
  1826. *
  1827. * @param int $gitlabID
  1828. * @param int $projectID
  1829. * @param array $protected
  1830. * @access public
  1831. * @return array
  1832. */
  1833. public function manageBranchPrivs($gitlabID, $projectID, $protected = array())
  1834. {
  1835. $data = fixer::input('post')->get();
  1836. $branches = $data->name;
  1837. $pushLevels = $data->pushAccess;
  1838. $mergeLevels = $data->mergeAccess;
  1839. $failure = array();
  1840. /* Remove privs. */
  1841. foreach($protected as $name => $branch)
  1842. {
  1843. if(!in_array($name, $branches))
  1844. {
  1845. $result = $this->apiDeleteBranchPriv($gitlabID, $projectID, $name);
  1846. if($result and substr($result->message, 0, 2) != '20') $failure[] = $name;
  1847. }
  1848. }
  1849. $priv = new stdClass();
  1850. foreach($branches as $key => $name)
  1851. {
  1852. /* Process exists data. */
  1853. if(isset($protected[$name]))
  1854. {
  1855. if($protected[$name]->pushAccess == $pushLevels[$key] and $protected[$name]->mergeAccess == $mergeLevels[$key]) continue;
  1856. $result = $this->apiDeleteBranchPriv($gitlabID, $projectID, $name);
  1857. if(isset($result->message) and substr($result->message, 0, 2) != '20') $failure[] = $name;
  1858. }
  1859. $priv->name = $name;
  1860. $priv->push_access_level = $pushLevels[$key];
  1861. $priv->merge_access_level = $mergeLevels[$key];
  1862. $response = $this->apiCreateBranchPriv($gitlabID, $projectID, $priv);
  1863. if(isset($response->message) and substr($response->message, 0, 2) != '20') $failure[] = $name;
  1864. }
  1865. return array_unique($failure);
  1866. }
  1867. /**
  1868. * 通过api创建一个分支策略。
  1869. * Create a gitlab protect branch by api.
  1870. *
  1871. * @param int $gitlabID
  1872. * @param int $projectID
  1873. * @param object $priv
  1874. * @access public
  1875. * @return object|array|null|false
  1876. */
  1877. public function apiCreateBranchPriv($gitlabID, $projectID, $priv)
  1878. {
  1879. if(empty($gitlabID)) return false;
  1880. if(empty($projectID)) return false;
  1881. if(empty($priv->name)) return false;
  1882. $priv->name = html_entity_decode($priv->name, ENT_QUOTES);
  1883. $url = sprintf($this->getApiRoot($gitlabID), "/projects/" . $projectID . '/protected_branches');
  1884. return json_decode(commonModel::http($url, $priv));
  1885. }
  1886. /**
  1887. * 通过api删除一个保护分支。
  1888. * Delete a gitlab protect branch by api.
  1889. *
  1890. * @param int $gitlabID
  1891. * @param int $projectID
  1892. * @param string $branch
  1893. * @access public
  1894. * @return object|array|null|false
  1895. */
  1896. public function apiDeleteBranchPriv($gitlabID, $projectID, $branch)
  1897. {
  1898. if(empty($gitlabID)) return false;
  1899. $branch = urlencode($branch);
  1900. $apiRoot = $this->getApiRoot($gitlabID);
  1901. $url = sprintf($apiRoot, "/projects/{$projectID}/protected_branches/{$branch}");
  1902. return json_decode(commonModel::http($url, array(), array(CURLOPT_CUSTOMREQUEST => 'DELETE')));
  1903. }
  1904. /**
  1905. * 管理标签策略。
  1906. * Manage tag privs.
  1907. *
  1908. * @param int $gitlabID
  1909. * @param int $projectID
  1910. * @param array $protected
  1911. * @access public
  1912. * @return array
  1913. */
  1914. public function manageTagPrivs($gitlabID, $projectID, $protected = array())
  1915. {
  1916. $data = fixer::input('post')->get();
  1917. $tags = $data->name;
  1918. $createLevels = $data->createAccess;
  1919. $failure = array();
  1920. /* Remove privs. */
  1921. foreach($protected as $name => $tag)
  1922. {
  1923. if(!in_array($name, $tags))
  1924. {
  1925. $result = $this->apiDeleteTagPriv($gitlabID, $projectID, $name);
  1926. if($result and substr($result->message, 0, 2) != '20') $failure[] = $name;
  1927. }
  1928. }
  1929. $priv = new stdClass();
  1930. foreach($tags as $key => $name)
  1931. {
  1932. /* Process exists data. */
  1933. if(isset($protected[$name]))
  1934. {
  1935. if($protected[$name]->createAccess == $createLevels[$key]) continue;
  1936. $result = $this->apiDeleteTagPriv($gitlabID, $projectID, $name);
  1937. if(isset($result->message) and substr($result->message, 0, 2) != '20') $failure[] = $name;
  1938. }
  1939. $priv->name = $name;
  1940. $priv->create_access_level = $createLevels[$key];
  1941. $response = $this->apiCreateTagPriv($gitlabID, $projectID, $priv);
  1942. if(isset($response->message))
  1943. {
  1944. if(is_array($response->message) or (is_string($response->message) and substr($response->message, 0, 2) != '20')) $failure[] = $name;
  1945. }
  1946. }
  1947. return array_unique($failure);
  1948. }
  1949. /**
  1950. * 通过api创建一个保护分支。
  1951. * Create a gitlab protect tag by api.
  1952. *
  1953. * @param int $gitlabID
  1954. * @param int $projectID
  1955. * @param object $priv
  1956. * @access public
  1957. * @return object|array|null|false
  1958. */
  1959. public function apiCreateTagPriv($gitlabID, $projectID, $priv)
  1960. {
  1961. if(empty($gitlabID) or empty($projectID)) return false;
  1962. if(empty($priv->name)) return false;
  1963. $url = sprintf($this->getApiRoot($gitlabID), "/projects/" . $projectID . '/protected_tags');
  1964. return json_decode(commonModel::http($url, $priv));
  1965. }
  1966. /**
  1967. * 检查权限等级。
  1968. * Check access level.
  1969. *
  1970. * @param array $accessLevels
  1971. * @access public
  1972. * @return int
  1973. */
  1974. public function checkAccessLevel($accessLevels)
  1975. {
  1976. if(is_array($accessLevels))
  1977. {
  1978. $levels = array();
  1979. foreach($accessLevels as $level)
  1980. {
  1981. if(is_array($level)) $level = (object)$level;
  1982. $levels[] = isset($level->access_level) ? (int)$level->access_level : $this->maintainerAccess;
  1983. }
  1984. if(in_array($this->noAccess, $levels)) return $this->noAccess;
  1985. if(in_array($this->developerAccess, $levels)) return $this->developerAccess;
  1986. }
  1987. return $this->maintainerAccess;
  1988. }
  1989. /**
  1990. * Get single branch by API.
  1991. *
  1992. * @param int $gitlabID
  1993. * @param int $projectID
  1994. * @param string $tag
  1995. * @access public
  1996. * @return object|array|null|false
  1997. */
  1998. public function apiGetSingleTag($gitlabID, $projectID, $tag)
  1999. {
  2000. if(empty($gitlabID)) return false;
  2001. $url = sprintf($this->getApiRoot($gitlabID), "/projects/$projectID/repository/tags/$tag");
  2002. return json_decode(commonModel::http($url));
  2003. }
  2004. /**
  2005. * 创建一个gitlab标签。
  2006. * Create gitlab tag.
  2007. *
  2008. * @param int $gitlabID
  2009. * @param int $projectID
  2010. * @param object $tag
  2011. * @access public
  2012. * @return bool
  2013. */
  2014. public function createTag($gitlabID, $projectID, $tag)
  2015. {
  2016. if(empty($gitlabID)) return false;
  2017. if(empty($tag->tag_name)) dao::$errors['tag_name'][] = $this->lang->gitlab->tag->emptyNameError;
  2018. if(empty($tag->ref)) dao::$errors['ref'][] = $this->lang->gitlab->tag->emptyRefError;
  2019. if(dao::isError()) return false;
  2020. $singleBranch = $this->apiGetSingleTag($gitlabID, $projectID, $tag->tag_name);
  2021. if(!empty($singleBranch->name)) dao::$errors['tag_name'][] = $this->lang->gitlab->tag->issetNameError;
  2022. if(dao::isError()) return false;
  2023. $url = sprintf($this->getApiRoot($gitlabID), "/projects/" . $projectID . '/repository/tags');
  2024. $response = json_decode(commonModel::http($url, $tag));
  2025. if(!empty($response->name))
  2026. {
  2027. $this->loadModel('action')->create('gitlabtag', 0, 'created', '', $response->name);
  2028. return true;
  2029. }
  2030. return $this->apiErrorHandling($response);
  2031. }
  2032. /**
  2033. * 检查用户权限。
  2034. * Check user access.
  2035. *
  2036. * @param int $gitlabID
  2037. * @param int $projectID
  2038. * @param object $project
  2039. * @param array $groupIDList
  2040. * @param string $maxRole
  2041. * @access public
  2042. * @return bool
  2043. */
  2044. public function checkUserAccess($gitlabID, $projectID = 0, $project = null, $groupIDList = array(), $maxRole = 'maintainer')
  2045. {
  2046. if($this->app->user->admin) return true;
  2047. if($project == null) $project = $this->apiGetSingleProject($gitlabID, $projectID);
  2048. if(!isset($project->id)) return false;
  2049. $accessLevel = $this->config->gitlab->accessLevel[$maxRole];
  2050. if(isset($project->permissions->project_access->access_level) and $project->permissions->project_access->access_level >= $accessLevel) return true;
  2051. if(isset($project->permissions->group_access->access_level) and $project->permissions->group_access->access_level >= $accessLevel) return true;
  2052. if(!empty($project->shared_with_groups))
  2053. {
  2054. if(empty($groupIDList))
  2055. {
  2056. $groups = $this->apiGetGroups($gitlabID, 'name_asc', $maxRole);
  2057. foreach($groups as $group) $groupIDList[] = $group->id;
  2058. }
  2059. foreach($project->shared_with_groups as $group)
  2060. {
  2061. if($group->group_access_level < $accessLevel) continue;
  2062. if(in_array($group->group_id, $groupIDList)) return true;
  2063. }
  2064. }
  2065. return false;
  2066. }
  2067. /**
  2068. * 获取gitlab版本。
  2069. * Get gitlab version.
  2070. *
  2071. * @param string $host
  2072. * @param string $token
  2073. * @access public
  2074. * @return object|array|null
  2075. */
  2076. public function getVersion($host, $token)
  2077. {
  2078. $host = rtrim($host, '/') . "/api/v4%s?private_token=$token";
  2079. return $this->apiGet($host, '/version');
  2080. }
  2081. /**
  2082. * 检查token。
  2083. * Check token access.
  2084. *
  2085. * @param string $url
  2086. * @param string $token
  2087. * @access public
  2088. * @return object|array|null|false
  2089. */
  2090. public function checkTokenAccess($url = '', $token = '')
  2091. {
  2092. $apiRoot = rtrim($url, '/') . '/api/v4%s' . "?private_token={$token}";
  2093. $url = sprintf($apiRoot, "/users") . "&per_page=5&active=true";
  2094. $response = commonModel::http($url);
  2095. $users = json_decode($response);
  2096. if(empty($users)) return false;
  2097. if(isset($users->message) or isset($users->error)) return null;
  2098. $apiRoot .= '&sudo=' . $users[0]->id;
  2099. return $this->apiGet($apiRoot, '/user');
  2100. }
  2101. /**
  2102. * 通过api获取流水线。
  2103. * Get pipeline with api.
  2104. *
  2105. * @param int $gitlabID
  2106. * @param int $projectID
  2107. * @param string $branch
  2108. * @access public
  2109. * @return object|array|null
  2110. */
  2111. public function apiGetPipeline($gitlabID, $projectID, $branch)
  2112. {
  2113. $apiRoot = $this->getApiRoot($gitlabID);
  2114. $url = sprintf($apiRoot, "/projects/$projectID/pipelines") . "&ref=$branch";
  2115. return json_decode(commonModel::http($url));
  2116. }
  2117. /**
  2118. * 更新版本库的代码地址。
  2119. * Update repo code path.
  2120. *
  2121. * @param int $gitlabID
  2122. * @param int $projectID
  2123. * @param int $repoID
  2124. * @access public
  2125. * @return string
  2126. */
  2127. public function updateCodePath($gitlabID, $projectID, $repoID)
  2128. {
  2129. $project = $this->apiGetSingleProject($gitlabID, $projectID);
  2130. if(is_object($project) and !empty($project->web_url))
  2131. {
  2132. $this->dao->update(TABLE_REPO)->set('path')->eq($project->web_url)->where('id')->eq($repoID)->exec();
  2133. return $project->web_url;
  2134. }
  2135. return '';
  2136. }
  2137. /**
  2138. * 判断按钮是否可点击。
  2139. * Adjust the action clickable.
  2140. *
  2141. * @param object $object
  2142. * @param string $action
  2143. * @access public
  2144. * @return bool
  2145. */
  2146. public function isClickable($object, $action)
  2147. {
  2148. if(!commonModel::hasPriv('space', 'browse')) return false;
  2149. if($action == 'browseBranch') return $object->isDeveloper;
  2150. if($action == 'browseTag') return $object->isDeveloper;
  2151. if($action == 'manageProjectMembers') return $object->hasRepo;
  2152. if($action == 'createWebhook') return $object->hasRepo;
  2153. if($action == 'manageBranchPriv') return $object->defaultBranch;
  2154. if($action == 'manageTagPriv') return $object->defaultBranch;
  2155. if($action == 'editProject') return $object->defaultBranch;
  2156. if($action == 'deleteProject') return $object->defaultBranch;
  2157. if($action == 'editGroup') return $object->isAdmin;
  2158. if($action == 'deleteGroup') return $object->isAdmin;
  2159. if($action == 'editUser') return $object->isAdmin;
  2160. if($action == 'deleteUser') return $object->isAdmin;
  2161. if($action == 'deleteTag') return !$object->protected;
  2162. return true;
  2163. }
  2164. /**
  2165. * 判断按钮是否显示在列表页。
  2166. * Judge an action is displayed in browse page.
  2167. *
  2168. * @param string $action
  2169. * @access public
  2170. * @return bool
  2171. */
  2172. public static function isDisplay($action)
  2173. {
  2174. $action = strtolower($action);
  2175. if(!common::hasPriv('space', 'browse')) return false;
  2176. if(!in_array($action, array('browseproject', 'browsegroup', 'browseuser', 'browsebranch', 'browsetag')))
  2177. {
  2178. if(!common::hasPriv('instance', 'manage', new stdclass())) return false;
  2179. }
  2180. return true;
  2181. }
  2182. /**
  2183. * 通过graphql的api获取数据。
  2184. * Get data by api graphql.
  2185. *
  2186. * @param object $repo
  2187. * @param string $query
  2188. * @access public
  2189. * @return object|array|null
  2190. */
  2191. public function apiGetByGraphql($repo, $query)
  2192. {
  2193. static $gitlab;
  2194. if(empty($gitlab)) $gitlab = $this->getByID((int)$repo->serviceHost);
  2195. if(!$gitlab) return array();
  2196. /* Compatible with HTTP and HTTPS domain. */
  2197. if(strpos($repo->codePath, '/api/v4/projects')) $repo->codePath = $this->updateCodePath((int)$repo->serviceHost, (int)$repo->serviceProject, $repo->id);
  2198. $repo->client = str_replace('https://', 'http://', $repo->client);
  2199. $repo->codePath = str_replace('https://', 'http://', $repo->codePath);
  2200. $fullPath = trim(str_replace($repo->client, '', $repo->codePath), '/');
  2201. if(strpos($fullPath, 'http://') === 0)
  2202. {
  2203. $project = $this->apiGetSingleProject((int)$repo->serviceHost, (int)$repo->serviceProject);
  2204. if(isset($project->path_with_namespace)) $fullPath = $project->path_with_namespace;
  2205. if(isset($repo->apiPath) && substr($repo->apiPath, 0, 5) == 'https') $repo->client = str_replace('http://', 'https://', $repo->client);
  2206. $this->dao->update(TABLE_REPO)->set('path')->eq("{$repo->client}/{$fullPath}")->where('id')->eq($repo->id)->exec();
  2207. }
  2208. $url = rtrim($gitlab->url, '/') . "/api/graphql?private_token={$gitlab->token}";
  2209. return json_decode(commonModel::http($url, array('query' => sprintf($query, $fullPath)), array(CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1)));
  2210. }
  2211. /**
  2212. * 获取文件最后一次提交信息。
  2213. * Get file last commit info.
  2214. *
  2215. * @param object $repo
  2216. * @param string $path
  2217. * @param string $branch
  2218. * @access public
  2219. * @return object|array|null
  2220. */
  2221. public function getFileLastCommit($repo, $path, $branch = 'HEAD')
  2222. {
  2223. $path = str_replace(array('\\', '"', '%'), array('\\\\', '\"', '%%'), $path);
  2224. $query = 'query {project(fullPath: "%s") {repository {tree(path: "' . trim($path, '/') . '", ref: "' . $branch . '") {lastCommit {sha message author {name username} authorName authoredDate}}}}}';
  2225. $response = $this->apiGetByGraphql($repo, $query);
  2226. if(!isset($response->data->project->repository->tree->lastCommit)) return null;
  2227. return $response->data->project->repository->tree->lastCommit;
  2228. }
  2229. }