model.php 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015
  1. <?php
  2. /**
  3. * The model file of user 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 Chunsheng Wang <chunsheng@cnezsoft.com>
  8. * @package user
  9. * @version $Id: model.php 5005 2013-07-03 08:39:11Z chencongzhi520@gmail.com $
  10. * @link https://www.zentao.net
  11. */
  12. ?>
  13. <?php
  14. class userModel extends model
  15. {
  16. /**
  17. * 创建或编辑用户前的检查。
  18. * Check before create or edit a user.
  19. *
  20. * @param object $user
  21. * @param bool $canNoPassword
  22. * @access public
  23. * @return bool
  24. */
  25. public function checkBeforeCreateOrEdit($user, $canNoPassword = false)
  26. {
  27. if(strtolower($user->account) == 'guest') dao::$errors['account'][] = sprintf($this->lang->user->error->reserved, $user->account);
  28. $this->checkPassword($user, $canNoPassword);
  29. $this->checkVerifyPassword($user->verifyPassword);
  30. return !dao::isError();
  31. }
  32. /**
  33. * 批量创建用户前的检查。
  34. * Check before batch creating users.
  35. *
  36. * @param array $users
  37. * @param string $verifyPassword
  38. * @access public
  39. * @return bool
  40. */
  41. public function checkBeforeBatchCreate($users, $verifyPassword)
  42. {
  43. if(!$users) return true;
  44. $accounts = array_map(function($user){return $user->account;}, $users);
  45. $accounts = $this->dao->select('account')->from(TABLE_USER)->where('account')->in($accounts)->fetchPairs();
  46. foreach($users as $key => $user)
  47. {
  48. if(empty($user->account)) continue;
  49. if(strtolower($user->account) == 'guest') dao::$errors["account[{$key}]"][] = $this->lang->user->error->reserved;
  50. if(isset($accounts[$user->account])) dao::$errors["account[{$key}]"][] = sprintf($this->lang->error->unique, $this->lang->user->account, $user->account);
  51. if(!validater::checkAccount($user->account)) dao::$errors["account[{$key}]"][] = sprintf($this->lang->error->account, $this->lang->user->account);
  52. if(empty($user->realname)) dao::$errors["realname[{$key}]"][] = sprintf($this->lang->error->notempty, $this->lang->user->realname);
  53. if(empty($user->visions)) dao::$errors["visions[{$key}][]"][] = sprintf($this->lang->error->notempty, $this->lang->user->visions);
  54. if(empty($user->password)) dao::$errors["password[{$key}]"][] = sprintf($this->lang->error->notempty, $this->lang->user->password);
  55. if(!empty($user->password) && !validater::checkReg($user->password, '|(.){6,}|')) dao::$errors["password[{$key}]"][] = $this->lang->user->error->password;
  56. if(!empty($user->email) && !validater::checkEmail($user->email)) dao::$errors["email[{$key}]"][] = sprintf($this->lang->error->email, $this->lang->user->email);
  57. if(!empty($user->phone) && !validater::checkPhone($user->phone)) dao::$errors["phone[{$key}]"][] = sprintf($this->lang->error->phone, $this->lang->user->phone);
  58. if(!empty($user->mobile) && !validater::checkMobile($user->mobile)) dao::$errors["mobile[{$key}]"][] = sprintf($this->lang->error->mobile, $this->lang->user->mobile);
  59. if(empty($user->gender)) dao::$errors["gender[{$key}]"][] = sprintf($this->lang->error->notempty, $this->lang->user->gender);
  60. /* 检查密码强度是否符合安全设置。*/
  61. /* Check if the password strength meets the security settings. */
  62. if(isset($this->config->safe->mode) && $this->computePasswordStrength($user->password) < $this->config->safe->mode) dao::$errors["password[{$key}]"][] = $this->lang->user->error->weakPassword;
  63. /* 检查明文的弱密码。*/
  64. /* Check the weak password in clear text. */
  65. if(!empty($this->config->safe->changeWeak))
  66. {
  67. if(!isset($this->config->safe->weak)) $this->app->loadConfig('admin');
  68. if(strpos(",{$this->config->safe->weak},", ",{$user->password},") !== false) dao::$errors["password[{$key}]"][] = sprintf($this->lang->user->error->dangerPassword, $this->config->safe->weak);
  69. }
  70. $accounts[$user->account] = $user->account;
  71. }
  72. $this->checkVerifyPassword($verifyPassword);
  73. return !dao::isError();
  74. }
  75. /**
  76. * 批量编辑用户前的检查。
  77. * Check before batch editing users.
  78. *
  79. * @param array $users
  80. * @param string $verifyPassword
  81. * @access public
  82. * @return bool
  83. */
  84. public function checkBeforeBatchUpdate($users, $verifyPassword)
  85. {
  86. if(!$users) return true;
  87. foreach($users as $key => $user)
  88. {
  89. if(empty($user->realname)) dao::$errors["realname[{$key}]"][] = sprintf($this->lang->error->notempty, $this->lang->user->realname);
  90. if(empty($user->visions)) dao::$errors["visions[{$key}][]"][] = sprintf($this->lang->error->notempty, $this->lang->user->visions);
  91. if(!empty($user->email) && !validater::checkEmail($user->email)) dao::$errors["email[{$key}]"][] = sprintf($this->lang->error->email, $this->lang->user->email);
  92. if(!empty($user->phone) && !validater::checkPhone($user->phone)) dao::$errors["phone[{$key}]"][] = sprintf($this->lang->error->phone, $this->lang->user->phone);
  93. if(!empty($user->mobile) && !validater::checkMobile($user->mobile)) dao::$errors["mobile[{$key}]"][] = sprintf($this->lang->error->mobile, $this->lang->user->mobile);
  94. }
  95. $this->checkVerifyPassword($verifyPassword);
  96. return !dao::isError();
  97. }
  98. /**
  99. * 检查密码强度。
  100. * Check the posted password.
  101. *
  102. * @param object $user
  103. * @param bool $canNoPassword
  104. * @access public
  105. * @return bool
  106. */
  107. public function checkPassword($user, $canNoPassword = false)
  108. {
  109. if(empty($user->password1))
  110. {
  111. if(!$canNoPassword) dao::$errors['password1'][] = sprintf($this->lang->error->notempty, $this->lang->user->password);
  112. return !dao::isError();
  113. }
  114. /* 检查密码强度是否符合安全设置。*/
  115. /* Check if the password strength meets the security settings. */
  116. if(isset($this->config->safe->mode) && ($user->passwordStrength < $this->config->safe->mode))
  117. {
  118. dao::$errors['password1'][] = zget($this->lang->user->placeholder->passwordStrengthCheck, $this->config->safe->mode, $this->lang->user->weakPassword);
  119. }
  120. else if($user->passwordLength < 6)
  121. {
  122. dao::$errors['password1'][] = zget($this->lang->user->placeholder->passwordStrengthCheck, 0, $this->lang->user->weakPassword);
  123. }
  124. if($user->password1 != $user->password2) dao::$errors['password1'][] = $this->lang->error->passwordsame;
  125. if(!empty($this->config->safe->changeWeak))
  126. {
  127. if(!isset($this->config->safe->weak)) $this->app->loadConfig('admin');
  128. /* 检查明文的弱密码。*/
  129. /* Check the weak password in clear text. */
  130. if(strpos(",{$this->config->safe->weak},", ",{$user->password1},") !== false) dao::$errors['password1'] = sprintf($this->lang->user->errorWeak, $this->config->safe->weak);
  131. /* 检查加密后的弱密码。*/
  132. /* Check for encrypted weak password. */
  133. $weaks = array();
  134. foreach(explode(',', $this->config->safe->weak) as $weak) $weaks[] = md5(trim($weak));
  135. if(in_array(substr($user->password1, 0, 32), $weaks)) dao::$errors['password1'] = sprintf($this->lang->user->errorWeak, $this->config->safe->weak);
  136. }
  137. return !dao::isError();
  138. }
  139. /**
  140. * 检查当前用户密码是否正确。
  141. * Check if the current user password is correct.
  142. *
  143. * @param string $verifyPassword
  144. * @access public
  145. * @return bool
  146. */
  147. public function checkVerifyPassword($verifyPassword)
  148. {
  149. /* API has no verifyPassword. */
  150. if($this->app->apiVersion == 'v2') return true;
  151. if(empty($verifyPassword) || $verifyPassword != md5($this->app->user->password . $this->session->rand)) dao::$errors['verifyPassword'][] = $this->lang->user->error->verifyPassword;
  152. return !dao::isError();
  153. }
  154. /**
  155. * 获取用户列表。
  156. * Get user list.
  157. *
  158. * @param string $params
  159. * @param string $fields
  160. * @access public
  161. * @return array
  162. */
  163. public function getList($params = 'nodeleted', $fields = '*')
  164. {
  165. return $this->dao->select($fields)->from(TABLE_USER)
  166. ->where('1 = 1')
  167. ->beginIF(strpos($params, 'all') === false)->andWhere('type')->eq('inside')->fi()
  168. ->beginIF(strpos($params, 'nodeleted') !== false)->andWhere('deleted')->eq(0)->fi()
  169. ->orderBy('account')
  170. ->fetchAll('', false);
  171. }
  172. /**
  173. * 根据用户 id 列表获取用户。
  174. * Get user list by id list.
  175. *
  176. * @param array $idList
  177. * @access public
  178. * @return array
  179. */
  180. public function getListByIdList($idList)
  181. {
  182. if(!$idList) return array();
  183. return $this->dao->select('*')->from(TABLE_USER)
  184. ->where('deleted')->eq('0')
  185. ->andWhere('id')->in($idList)
  186. ->orderBy('id')
  187. ->fetchAll('id');
  188. }
  189. /**
  190. * 根据用户名列表获取用户信息。
  191. * Get user info by account list.
  192. *
  193. * @param array $accounts
  194. * @param string $keyField
  195. * @access public
  196. * @return array
  197. */
  198. public function getListByAccounts($accounts, $keyField = 'id')
  199. {
  200. if(empty($accounts)) return array();
  201. return $this->dao->select('id,account,realname,avatar,role')->from(TABLE_USER)
  202. ->where('account')->in($accounts)
  203. ->fetchAll($keyField);
  204. }
  205. /**
  206. * 获取用户名和真实姓名的键值对。
  207. * Get account and realname pairs.
  208. *
  209. * @param string $params noletter|noempty|nodeleted|noclosed|withguest|pofirst|devfirst|qafirst|pmfirst|realname|outside|inside|all, can be sets of theme
  210. * @param string|array $usersToAppended account1,account2
  211. * @param int $maxCount
  212. * @param string|array $accounts
  213. * @access public
  214. * @return array
  215. */
  216. public function getPairs($params = '', $usersToAppended = '', $maxCount = 0, $accounts = '')
  217. {
  218. if(commonModel::isTutorialMode()) return $this->loadModel('tutorial')->getUserPairs();
  219. /* 设置查询字段、条件字段、排序字段和索引字段。
  220. * Set query fields, condition fields, order fields and index field.
  221. *
  222. * 如果参数中有 xxfirst,使用 INSTR 函数获取角色字段在排序字符串中的位置,以确保用户在角色排序中排在前面。
  223. * If there's xxfirst in the params, use INSTR function to get the position of role fields in a order string,
  224. * thus to make sure users of this role at first.
  225. */
  226. $fields = 'id, account, realname, deleted';
  227. if(strpos($params, 'pofirst') !== false) $fields .= ", INSTR(',pd,po,', role) AS roleOrder";
  228. if(strpos($params, 'pdfirst') !== false) $fields .= ", INSTR(',po,pd,', role) AS roleOrder";
  229. if(strpos($params, 'qafirst') !== false) $fields .= ", INSTR(',qd,qa,', role) AS roleOrder";
  230. if(strpos($params, 'qdfirst') !== false) $fields .= ", INSTR(',qa,qd,', role) AS roleOrder";
  231. if(strpos($params, 'pmfirst') !== false) $fields .= ", INSTR(',td,pm,', role) AS roleOrder";
  232. if(strpos($params, 'devfirst')!== false) $fields .= ", INSTR(',td,pm,qd,qa,dev,', role) AS roleOrder";
  233. $type = (strpos($params, 'outside') !== false) ? 'outside' : 'inside';
  234. $orderBy = (strpos($params, 'first') !== false) ? 'roleOrder DESC, account' : 'account';
  235. $keyField = (strpos($params, 'useid') !== false) ? 'id' : "account";
  236. $users = $this->dao->select($fields)->from(TABLE_USER)
  237. ->where('1=1')
  238. ->beginIF(strpos($params, 'nodeleted') !== false || empty($this->config->user->showDeleted))->andWhere('deleted')->eq('0')->fi()
  239. ->beginIF(strpos($params, 'all') === false)->andWhere('type')->eq($type)->fi()
  240. ->beginIF($accounts)->andWhere('account')->in($accounts)->fi()
  241. ->beginIF($this->config->vision && $this->app->rawModule !== 'kanban')->andWhere("FIND_IN_SET('{$this->config->vision}', visions)")->fi()
  242. ->orderBy($orderBy)
  243. ->beginIF($maxCount)->limit($maxCount)->fi()
  244. ->fetchAll($keyField);
  245. $this->processMoreLink($params, $usersToAppended, $maxCount, count($users));
  246. if($usersToAppended) $users += $this->fetchExtraUsers($usersToAppended, $fields, $keyField);
  247. $users = $this->processDisplayValue($users, $params);
  248. $users = $this->setCurrentUserFirst($users);
  249. /* Append empty, closed, and guest users. */
  250. if(strpos($params, 'noclosed') === false) $users = $users + array('closed' => 'Closed');
  251. if(strpos($params, 'withguest') !== false) $users = $users + array('guest' => 'Guest');
  252. return $users;
  253. }
  254. /**
  255. * 处理获取更多用户的链接。
  256. * Process the more link.
  257. *
  258. * @param string $params
  259. * @param string|array $usersToAppended
  260. * @param int $maxCount
  261. * @param int $userCount
  262. * @access public
  263. * @return bool
  264. */
  265. public function processMoreLink($params, $usersToAppended, $maxCount, $userCount)
  266. {
  267. unset($this->config->user->moreLink);
  268. if($maxCount && $maxCount == $userCount)
  269. {
  270. if(is_array($usersToAppended)) $usersToAppended = implode(',', $usersToAppended);
  271. $moreLinkParams = "params={$params}&usersToAppended={$usersToAppended}";
  272. $moreLink = helper::createLink('user', 'ajaxGetMore');
  273. $this->config->user->moreLink = $moreLink . (strpos($moreLink, '?') === false ? '?' : '&') . "params=" . base64_encode($moreLinkParams) . '&search={search}';
  274. }
  275. return true;
  276. }
  277. /**
  278. * 根据用户名获取额外的用户。
  279. * Get extra users by account.
  280. *
  281. * @param string|array $usersToAppended
  282. * @param string $fields
  283. * @param string $keyField
  284. * @access public
  285. * @return array
  286. */
  287. public function fetchExtraUsers($usersToAppended, $fields, $keyField)
  288. {
  289. if(!$usersToAppended) return array();
  290. return $this->dao->select($fields)->from(TABLE_USER)->where('account')->in($usersToAppended)->fetchAll($keyField);
  291. }
  292. /**
  293. * 处理用户的显示名称。
  294. * Process the display value of users.
  295. *
  296. * @param array $users
  297. * @param string $params
  298. * @access public
  299. * @return array
  300. */
  301. public function processDisplayValue($users, $params)
  302. {
  303. foreach($users as $account => $user)
  304. {
  305. if(strpos($params, 'showid') !== false)
  306. {
  307. $users[$account] = $user->id;
  308. continue;
  309. }
  310. $firstLetter = ucfirst(mb_substr($user->account, 0, 1)) . ':';
  311. if(strpos($params, 'noletter') !== false || !empty($this->config->isINT)) $firstLetter = '';
  312. $users[$account] = $firstLetter . (($user->deleted && strpos($params, 'realname') === false) ? $user->account : ($user->realname ?: $user->account));
  313. }
  314. return $users;
  315. }
  316. /**
  317. * 获取用户名和头像的键值对。
  318. * Get account and avatar pairs.
  319. *
  320. * @param string $params
  321. * @access public
  322. * @return array
  323. */
  324. public function getAvatarPairs($params = 'nodeleted')
  325. {
  326. $avatarPairs = array();
  327. $userList = $this->getList($params, 'account,avatar');
  328. foreach($userList as $user) $avatarPairs[$user->account] = $user->avatar;
  329. return $avatarPairs;
  330. }
  331. /**
  332. * 获取源代码账号和真实姓名/用户名的键值对。
  333. * Get account and realname pairs.
  334. *
  335. * @param string $field
  336. * @access public
  337. * @return array
  338. */
  339. public function getCommiters($field = 'realname')
  340. {
  341. $rawCommiters = $this->dao->select('commiter, account, realname')->from(TABLE_USER)->where('commiter')->ne('')->fetchAll();
  342. if(!$rawCommiters) return array();
  343. $commiters = array();
  344. foreach($rawCommiters as $commiter)
  345. {
  346. $userCommiters = explode(',', $commiter->commiter);
  347. foreach($userCommiters as $userCommiter) $commiters[$userCommiter] = $commiter->$field ?: $commiter->account;
  348. }
  349. return $commiters;
  350. }
  351. /**
  352. * 获取用户名、真实姓名和邮箱组成的用户列表。
  353. * Get user list with account, realname and email.
  354. *
  355. * @param string|array $users
  356. * @access public
  357. * @return array
  358. */
  359. public function getRealNameAndEmails($users)
  360. {
  361. if(!$users) return array();
  362. return $this->dao->select("account, email, IF(realname = '', account, realname) AS realname")->from(TABLE_USER)->where('account')->in($users)->fetchAll('account');
  363. }
  364. /**
  365. * 获取用户名和角色名的键值对。
  366. * Get account and role pairs.
  367. *
  368. * @param string|array $users
  369. * @access public
  370. * @return array
  371. */
  372. public function getUserRoles($users)
  373. {
  374. if(!$users) return array();
  375. $users = $this->dao->select('account, role')->from(TABLE_USER)->where('account')->in($users)->fetchPairs();
  376. if(!$users) return array();
  377. foreach($users as $account => $role) $users[$account] = zget($this->lang->user->roleList, $role);
  378. return $users;
  379. }
  380. /**
  381. * 根据指定字段的值获取一个用户。
  382. * Get a user by the value of the specified field.
  383. *
  384. * @param string $userID
  385. * @param string $field id|account
  386. * @access public
  387. * @return object|bool
  388. */
  389. public function getById($userID, $field = 'account')
  390. {
  391. /* 如果 userID 参数为空并且当前用户是游客,返回当前用户,以确保仪表盘页面正常工作。*/
  392. /* If the userID param is empty and the current user is guest, return the current user to make sure the dashboard page works well. */
  393. if(empty($userID) && $this->app->user->account == 'guest') return $this->app->user;
  394. if($field == 'id') $userID = (int)$userID;
  395. if($field == 'account') $userID = trim($userID);
  396. $user = $this->dao->select('*')->from(TABLE_USER)->where("`$field`")->eq($userID)->fetch();
  397. if(!$user) return false;
  398. return $user;
  399. }
  400. /**
  401. * 根据自定义查询语句获取用户。
  402. * Get users by custom query.
  403. *
  404. * @param string $browseType inside|outside|all
  405. * @param string $query
  406. * @param object $pager
  407. * @param string $orderBy
  408. * @access public
  409. * @return array
  410. */
  411. public function getByQuery($browseType = 'inside', $query = '', $pager = null, $orderBy = 'id')
  412. {
  413. return $this->dao->select('*')->from(TABLE_USER)
  414. ->where('deleted')->eq('0')
  415. ->beginIF($query)->andWhere($query)->fi()
  416. ->beginIF($browseType == 'inside')->andWhere('type')->eq('inside')->fi()
  417. ->beginIF($browseType == 'outside')->andWhere('type')->eq('outside')->fi()
  418. ->beginIF($this->config->vision)->andWhere("FIND_IN_SET('{$this->config->vision}', visions)")->fi()
  419. ->orderBy($orderBy)
  420. ->page($pager)
  421. ->fetchAll();
  422. }
  423. /**
  424. * 添加一个用户。
  425. * Create a user.
  426. *
  427. * @param object $user
  428. * @access public
  429. * @return false|int
  430. */
  431. public function create($user)
  432. {
  433. $this->checkBeforeCreateOrEdit($user);
  434. $this->dao->begin();
  435. $requiredFields = $this->config->user->create->requiredFields;
  436. if($user->type == 'outside')
  437. {
  438. if($user->new) $user->company = $this->createCompany($user->newCompany);
  439. $requiredFields = trim(str_replace(array(',dept,', ',commiter,'), '', ',' . $requiredFields . ','), ',');
  440. }
  441. $this->dao->insert(TABLE_USER)->data($user, 'new,newCompany,password1,password2,group,verifyPassword,passwordLength,passwordStrength')
  442. ->batchCheck($requiredFields, 'notempty')
  443. ->checkIF($user->account, 'account', 'unique')
  444. ->checkIF($user->account, 'account', 'account')
  445. ->checkIF($user->email, 'email', 'email')
  446. ->autoCheck()
  447. ->exec();
  448. if(dao::isError()) return $this->rollback();
  449. $userID = $this->dao->lastInsertID();
  450. /* 创建用户组,更新用户视图并记录日志。*/
  451. /* Create user group, update user view and save log. */
  452. $groups = array_filter($user->group);
  453. if($groups) $this->createUserGroup($groups, $user->account);
  454. $this->loadModel('action')->create('user', $userID, 'Created');
  455. if(dao::isError()) return $this->rollback();
  456. $this->dao->commit();
  457. return $userID;
  458. }
  459. /**
  460. * 创建一个外部公司。
  461. * Create a outside company.
  462. *
  463. * @param string $companyName
  464. * @access public
  465. * @return int
  466. */
  467. public function createCompany($companyName)
  468. {
  469. if(empty($companyName))
  470. {
  471. dao::$errors['newCompany'][] = sprintf($this->lang->error->notempty, $this->lang->user->company);
  472. return 0;
  473. }
  474. $company = new stdClass();
  475. $company->name = $companyName;
  476. $this->dao->insert(TABLE_COMPANY)->data($company)->exec();
  477. return $this->dao->lastInsertID();
  478. }
  479. /**
  480. * 创建用户组。
  481. * Create user group.
  482. *
  483. * @param array $groups
  484. * @param string $account
  485. * @access public
  486. * @return bool
  487. */
  488. public function createUserGroup($groups, $account)
  489. {
  490. if(empty($groups) || empty($account)) return false;
  491. $userGroup = new stdclass();
  492. $userGroup->account = $account;
  493. $userGroup->project = '';
  494. foreach($groups as $group)
  495. {
  496. $userGroup->group = $group;
  497. $this->dao->replace(TABLE_USERGROUP)->data($userGroup)->exec();
  498. }
  499. return !dao::isError();
  500. }
  501. /**
  502. * 批量创建用户。
  503. * Batch create users.
  504. *
  505. * @param array $users
  506. * @param string $verifyPassword
  507. * @access public
  508. * @return bool|array
  509. */
  510. public function batchCreate($users, $verifyPassword)
  511. {
  512. if(!$users) return false;
  513. $this->checkBeforeBatchCreate($users, $verifyPassword);
  514. if(dao::isError()) return false;
  515. $this->loadModel('action');
  516. $this->dao->begin();
  517. $userIdList = array();
  518. $preCompany = 0;
  519. foreach($users as $index => $user)
  520. {
  521. if(empty($user->account)) continue;
  522. $user->password = md5($user->password);
  523. if($user->type == 'outside')
  524. {
  525. if($user->new) $user->company = $this->createCompany($user->newCompany);
  526. if($this->post->company[$index] != 'ditto') $preCompany = $user->company;
  527. if($this->post->company[$index] == 'ditto') $user->company = $preCompany;
  528. }
  529. $this->dao->insert(TABLE_USER)->data($user, 'new,newCompany,group')->autoCheck()->exec();
  530. if(dao::isError()) return $this->rollback();
  531. $userID = $this->dao->lastInsertID();
  532. /* 创建用户组,更新用户视图并记录日志。*/
  533. /* Create user group, update user view and save log. */
  534. $groups = array_filter($user->group);
  535. if($groups) $this->createUserGroup($groups, $user->account);
  536. $this->action->create('user', $userID, 'Created');
  537. if(dao::isError()) return $this->rollback();
  538. $userIdList[] = $userID;
  539. }
  540. $this->dao->commit();
  541. return $userIdList;
  542. }
  543. /**
  544. * 更新一个用户。
  545. * Update a user.
  546. *
  547. * @param object $user
  548. * @access public
  549. * @return bool
  550. */
  551. public function update($user)
  552. {
  553. $oldUser = $this->getById($user->id, 'id');
  554. $this->checkBeforeCreateOrEdit($user, true);
  555. $this->dao->begin();
  556. if(!isset($user->type)) $user->type = $oldUser->type;
  557. if($user->type == 'outside' && $user->new) $user->company = $this->createCompany($user->newCompany);
  558. /* 获取所有的联系方式字段。*/
  559. /* Get all contact fields. */
  560. $allContactFields = array_keys($this->lang->user->contactFieldList);
  561. /* 获取可用的联系方式字段,转为数组并去空、去重。*/
  562. /* Get available contact fields, convert to array and remove empty and duplicate. */
  563. $availableContactFields = array_unique(array_filter(explode(',', trim($this->config->user->contactField, ','))));
  564. /* 获取不可用的联系方式字段。*/
  565. /* Get unavailable contact fields. */
  566. $unAvailableContactFields = array_diff($allContactFields, $availableContactFields);
  567. /* 从配置文件获取必填项字段,转为数组并去空、去重。*/
  568. /* Get required fields from config file, convert to array and remove empty and duplicate. */
  569. $requiredFields = array_unique(array_filter(explode(',', trim($this->config->user->edit->requiredFields, ','))));
  570. /* 从必填项字段中去除不可用的联系方式字段。*/
  571. /* Remove unavailable contact fields from available fields. */
  572. $requiredFields = implode(',', array_diff($requiredFields, $unAvailableContactFields));
  573. $this->dao->update(TABLE_USER)->data($user, 'new,newCompany,password1,password2,group,verifyPassword,passwordLength,passwordStrength')
  574. ->batchCheck($requiredFields, 'notempty')
  575. ->checkIF($user->account, 'account', 'unique', "id != '$user->id'")
  576. ->checkIF($user->account, 'account', 'account')
  577. ->checkIF($user->email, 'email', 'email')
  578. ->checkIF($user->phone, 'phone', 'phone')
  579. ->checkIF($user->mobile, 'mobile', 'mobile')
  580. ->autoCheck()
  581. ->where('id')->eq($user->id)
  582. ->exec();
  583. if(dao::isError()) return $this->rollBack();
  584. /* 更新用户组和用户视图并记录积分和日志。*/
  585. /* Update user group and user view, and save log and score. */
  586. $this->checkAccountChange($oldUser->account, $user->account);
  587. $this->checkGroupChange($user);
  588. $this->loadModel('score')->create('user', 'editProfile');
  589. $changes = common::createChanges($oldUser, $user);
  590. if($changes)
  591. {
  592. $actionID = $this->loadModel('action')->create('user', $user->id, 'edited');
  593. $this->action->logHistory($actionID, $changes);
  594. }
  595. if(dao::isError()) return $this->rollBack();
  596. if(!empty($user->password) && $user->password != $oldUser->password) $this->userTao->deleteImUserDevice($user->id);
  597. $this->dao->commit();
  598. /* 更新当前用户的信息。*/
  599. /* Update current user's info. */
  600. if($user->account == $this->app->user->account)
  601. {
  602. if(!empty($user->password)) $this->app->user->password = $user->password;
  603. $this->app->user->realname = $user->realname;
  604. $this->app->user->role = isset($user->role) ? $user->role : $oldUser->role;
  605. }
  606. return true;
  607. }
  608. /**
  609. * 检查用户名是否发生变化。
  610. * Check if the account changed.
  611. *
  612. * @param string $oldAccount
  613. * @param string $newAccount
  614. * @access public
  615. * @return bool
  616. */
  617. public function checkAccountChange($oldAccount, $newAccount)
  618. {
  619. if($oldAccount == $newAccount) return false;
  620. /* 更新用户组和用户视图。*/
  621. /* Update the user group and user view. */
  622. $this->dao->update(TABLE_USERGROUP)->set('account')->eq($newAccount)->where('account')->eq($oldAccount)->exec();
  623. $this->dao->update(TABLE_USERVIEW)->set('account')->eq($newAccount)->where('account')->eq($oldAccount)->exec();
  624. /* 如果旧用户名是公司管理员,则更新公司管理员。*/
  625. /* If the old account is company admin, update the company admin. */
  626. if(strpos($this->app->company->admins, ',' . $oldAccount . ',') !== false)
  627. {
  628. $admins = str_replace(',' . $oldAccount . ',', ',' . $newAccount . ',', $this->app->company->admins);
  629. $this->dao->update(TABLE_COMPANY)->set('admins')->eq($admins)->where('id')->eq($this->app->company->id)->exec();
  630. if(dao::isError()) return false;
  631. $this->app->company->admins = $admins;
  632. }
  633. return !dao::isError();
  634. }
  635. /**
  636. * 检查权限组是否发生变化。
  637. * Check if the group changed.
  638. *
  639. * @param object $user
  640. * @access public
  641. * @return bool
  642. */
  643. public function checkGroupChange($user)
  644. {
  645. $oldGroups = array_keys($this->loadModel('group')->getByAccount($user->account, true));
  646. $newGroups = array_unique(array_filter($user->group));
  647. sort($oldGroups);
  648. sort($newGroups);
  649. if(implode(',', $oldGroups) == implode(',', $newGroups)) return false;
  650. /* 如果权限组发生变化,则删除原有的权限组,重新创建并更新用户视图。*/
  651. /* If the group changed, delete the old group, create new group and update user view. */
  652. $projectGroups = $this->dao->select('id')->from(TABLE_GROUP)->where('project')->ne(0)->fetchPairs();
  653. $this->dao->delete()->from(TABLE_USERGROUP)
  654. ->where('account')->eq($user->account)
  655. ->andWhere('`group`')->notin($projectGroups)
  656. ->exec();
  657. if($newGroups) $this->createUserGroup($newGroups, $user->account);
  658. return !dao::isError();
  659. }
  660. /**
  661. * 批量编辑用户。
  662. * Batch update user.
  663. *
  664. * @param array $users
  665. * @param string $verifyPassword
  666. * @access public
  667. * @return bool
  668. */
  669. public function batchUpdate($users, $verifyPassword)
  670. {
  671. if(!$users) return false;
  672. $this->checkBeforeBatchUpdate($users, $verifyPassword);
  673. if(dao::isError()) return false;
  674. $this->loadModel('action');
  675. $accounts = array_map(function($user){return $user->account;}, $users);
  676. $oldUsers = $this->dao->select('*')->from(TABLE_USER)->where('account')->in($accounts)->fetchAll('id');
  677. $this->dao->begin();
  678. foreach($users as $id => $user)
  679. {
  680. $this->dao->update(TABLE_USER)->data($user)->where('id')->eq($id)->autoCheck()->exec();
  681. if(dao::isError()) return $this->rollback();
  682. /* 更新用户组和用户视图并记录日志。*/
  683. /* Update user group and user view, and save log and score. */
  684. $oldUser = $oldUsers[$id];
  685. $changes = common::createChanges($oldUser, $user);
  686. if($changes)
  687. {
  688. $actionID = $this->action->create('user', $id, 'edited');
  689. $this->action->logHistory($actionID, $changes);
  690. }
  691. if(dao::isError()) return $this->rollback();
  692. /* 更新当前用户的信息。*/
  693. /* Update current user's info. */
  694. if($user->account == $this->app->user->account)
  695. {
  696. $this->app->user->realname = $user->realname;
  697. $this->app->user->role = $user->role;
  698. }
  699. }
  700. $this->dao->commit();
  701. return true;
  702. }
  703. /**
  704. * 更新当前用户的密码。
  705. * Update current user's password.
  706. *
  707. * @param object $user
  708. * @access public
  709. * @return bool
  710. */
  711. public function updatePassword($user)
  712. {
  713. $this->checkPassword($user);
  714. if($user->originalPassword != md5($this->app->user->password . $this->session->rand)) dao::$errors['originalPassword'][] = $this->lang->user->error->originalPassword;
  715. if(dao::isError()) return false;
  716. $this->dao->update(TABLE_USER)->set('password')->eq($user->password)->where('id')->eq($this->app->user->id)->exec();
  717. if(dao::isError()) return false;
  718. $this->userTao->deleteImUserDevice($this->app->user->id);
  719. $this->loadModel('score')->create('user', 'changePassword', $this->computePasswordStrength($user->password1));
  720. $this->app->user->password = $user->password;
  721. $this->app->user->modifyPassword = false;
  722. $this->app->user->modifyPasswordReason = '';
  723. $_SESSION['user'] = $this->app->user;
  724. return true;
  725. }
  726. /**
  727. * 重置密码。
  728. * Reset password.
  729. *
  730. * @param object $user
  731. * @access public
  732. * @return bool
  733. */
  734. public function resetPassword($user)
  735. {
  736. $oldUser = $this->getById($user->account);
  737. if(!$oldUser)
  738. {
  739. dao::$errors['account'] = $this->lang->user->error->noUser;
  740. return false;
  741. }
  742. $this->checkPassword($user);
  743. $this->dao->update(TABLE_USER)->set('password')->eq($user->password)->where('account')->eq($user->account)->exec();
  744. return !dao::isError();
  745. }
  746. /**
  747. * 验证用户并设置相关属性。
  748. * Identify user and set related properties.
  749. *
  750. * @param string $account the user account
  751. * @param string $password the user password or auth hash
  752. * @param int $passwordStrength the user password strength
  753. * @access public
  754. * @return bool|object
  755. */
  756. public function identify($account, $password, $passwordStrength = 0)
  757. {
  758. if(!$account || !$password) return false;
  759. if(!validater::checkAccount($account)) return false;
  760. $user = $this->identifyUser($account, $password);
  761. if(!$user) return false;
  762. $ip = helper::getRemoteIp();
  763. $last = helper::now();
  764. $user = $this->checkNeedModifyPassword($user, $passwordStrength);
  765. $user->last = $last;
  766. $user->admin = strpos($this->app->company->admins, ",{$user->account},") !== false;
  767. if($this->app->isServing())
  768. {
  769. $this->dao->update(TABLE_USER)->set('visits = visits + 1')->set('ip')->eq($ip)->set('last')->eq($last)->where('account')->eq($account)->exec();
  770. /* 登录后创建周期性待办。*/
  771. /* Create cycle todo after login. */
  772. $todoList = $this->dao->select('*')->from(TABLE_TODO)->where('cycle')->eq(1)->andWhere('deleted')->eq('0')->andWhere('account')->eq($user->account)->fetchAll('id');
  773. if($todoList) $this->loadModel('todo')->createByCycle($todoList);
  774. }
  775. if($user->avatar)
  776. {
  777. $avatarRoot = substr($user->avatar, 0, strpos($user->avatar, 'data/upload/'));
  778. if($this->config->webRoot != $avatarRoot) $user->avatar = substr_replace($user->avatar, $this->config->webRoot, 0, strlen($avatarRoot));
  779. }
  780. return $user;
  781. }
  782. /**
  783. * 根据用户名和密码验证用户。
  784. * Identify user by account and password.
  785. *
  786. * @param string $account the user account
  787. * @param string $password the user password or auth hash
  788. * @access public
  789. * @return bool|object
  790. */
  791. public function identifyUser($account, $password)
  792. {
  793. $user = $this->dao->select('*')->from(TABLE_USER)->where('deleted')->eq('0')->andWhere('account')->eq($account)->fetch();
  794. if(!$user) return false;
  795. $passwordLength = strlen($password);
  796. if($passwordLength == 32)
  797. {
  798. $hash = $this->session->rand ? md5($user->password . $this->session->rand) : $user->password;
  799. if($password == $hash) return $user;
  800. }
  801. if($passwordLength == 40)
  802. {
  803. $lastTimestamp = is_numeric($user->last) ? $user->last : strtotime($user->last);
  804. $hash = sha1($user->account . $user->password . $lastTimestamp);
  805. if($password == $hash) return $user;
  806. }
  807. return md5($password) == $user->password ? $user : false;
  808. }
  809. /**
  810. * 检查是否需要修改密码。
  811. * Check if need to modify password.
  812. *
  813. * @param object $user
  814. * @param int $passwordStrength
  815. * @access public
  816. * @return object
  817. */
  818. public function checkNeedModifyPassword($user, $passwordStrength)
  819. {
  820. /* 如果开启了首次登录修改密码功能,检查是否是首次登录。*/
  821. /* If the modify password on first login feature is enabled, check if it's the first login. */
  822. if(!empty($this->config->safe->modifyPasswordFirstLogin))
  823. {
  824. $user->modifyPassword = $user->visits == 0;
  825. if($user->modifyPassword)
  826. {
  827. $user->modifyPasswordReason = 'modifyPasswordFirstLogin';
  828. return $user;
  829. }
  830. }
  831. /* 如果开启了修改弱口令密码功能,检查是否是弱口令。*/
  832. /* If the modify weak password feature is enabled, check if it's a weak password. */
  833. if(!empty($this->config->safe->changeWeak))
  834. {
  835. $user->modifyPassword = $this->loadModel('admin')->checkWeak($user);
  836. if($user->modifyPassword)
  837. {
  838. $user->modifyPasswordReason = 'weak';
  839. return $user;
  840. }
  841. }
  842. /* 如果开启了密码强度检查功能,检查密码是否满足强度要求。*/
  843. /* If the password strength feature is enabled, check if the password is strong enough. */
  844. if(!empty($this->config->safe->mode) && $this->app->moduleName == 'user' && $this->app->methodName == 'login')
  845. {
  846. $user->modifyPassword = $passwordStrength < $this->config->safe->mode;
  847. if($user->modifyPassword)
  848. {
  849. $user->modifyPasswordReason = 'passwordStrengthWeak';
  850. return $user;
  851. }
  852. }
  853. return $user;
  854. }
  855. /**
  856. * 根据 PHP 的 HTTP 认证验证用户。
  857. * Identify user by PHP HTTP auth.
  858. *
  859. * @access public
  860. * @return bool
  861. */
  862. public function identifyByPhpAuth()
  863. {
  864. $account = $this->server->php_auth_user;
  865. $password = $this->server->php_auth_pw;
  866. $user = $this->identify($account, $password);
  867. if(!$user) return false;
  868. $user->rights = $this->authorize($account);
  869. $user->groups = $this->getGroups($account);
  870. $user->view = $this->grantUserView($user->account, $user->rights['acls']);
  871. $this->session->set('user', $user);
  872. $this->app->user = $this->session->user;
  873. $this->loadModel('action')->create('user', $user->id, 'login');
  874. $this->loadModel('score')->create('user', 'login');
  875. $this->loadModel('common')->loadConfigFromDB();
  876. return true;
  877. }
  878. /**
  879. * 根据 Cookie 验证用户。
  880. * Identify user by cookie.
  881. *
  882. * @access public
  883. * @return bool
  884. */
  885. public function identifyByCookie()
  886. {
  887. $account = $this->cookie->za;
  888. $authHash = $this->cookie->zp;
  889. $user = $this->identify($account, $authHash, 3); // Set passwordStrength=MAX_PASSWORD_STRENGTH, don't check modifyPassword.
  890. if(!$user) return false;
  891. $user->rights = $this->authorize($account);
  892. $user->groups = $this->getGroups($account);
  893. $user->view = $this->grantUserView($user->account, $user->rights['acls']);
  894. $this->session->set('user', $user);
  895. $this->app->user = $this->session->user;
  896. $this->loadModel('action')->create('user', $user->id, 'login');
  897. $this->loadModel('score')->create('user', 'login');
  898. $this->loadModel('common')->loadConfigFromDB();
  899. $this->keepLogin($user);
  900. return true;
  901. }
  902. /**
  903. * 获取某用户的视图访问权限。
  904. * Get user acls.
  905. *
  906. * @param string $account
  907. * @access private
  908. * @return array
  909. */
  910. private function getUserAcls($account)
  911. {
  912. if($account == 'guest')
  913. {
  914. $acls = $this->dao->select('acl')->from(TABLE_GROUP)->where('name')->eq('guest')->fetch('acl');
  915. return !empty($acls) ? json_decode($acls, true) : array();
  916. }
  917. $groups = $this->dao->select('t1.acl, t1.project')->from(TABLE_GROUP)->alias('t1')
  918. ->leftJoin(TABLE_USERGROUP)->alias('t2')->on('t1.id=t2.`group`')
  919. ->where('t2.account')->eq($account)
  920. ->andWhere('t1.vision')->eq($this->config->vision)
  921. ->andWhere('t1.role')->ne('projectAdmin')
  922. ->andWhere('t1.role')->ne('limited')
  923. ->andWhere('t1.project')->eq(0)
  924. ->fetchAll();
  925. /* Init variables. */
  926. $acls = array('programs' => array(), 'projects' => array(), 'products' => array(), 'sprints' => array(), 'views' => array(), 'actions' => array());
  927. $programAllow = $projectAllow = $productAllow = $sprintAllow = $viewAllow = $actionAllow = false;
  928. /* Authorize by group. */
  929. foreach($groups as $group)
  930. {
  931. /* 只要有一个权限分组没有配置过视图权限,就代表所有视图都没有访问限制。 */
  932. if(empty($group->acl))
  933. {
  934. $programAllow = $projectAllow = $productAllow = $sprintAllow = $viewAllow = $actionAllow = true;
  935. break;
  936. }
  937. $acl = json_decode($group->acl, true);
  938. /* 只要有一个权限分组的某个配置为空,就代表该配置没有访问限制。 */
  939. if(empty($acl['programs'])) $programAllow = true;
  940. if(empty($acl['projects'])) $projectAllow = true;
  941. if(empty($acl['products'])) $productAllow = true;
  942. if(empty($acl['sprints'])) $sprintAllow = true;
  943. if(empty($acl['views'])) $viewAllow = true;
  944. if(!isset($acl['actions'])) $actionAllow = true;
  945. /* 将所有权限分组的视图访问限制合并。 */
  946. if(!$programAllow && !empty($acl['programs'])) $acls['programs'] = array_merge($acls['programs'], $acl['programs']);
  947. if(!$projectAllow && !empty($acl['projects'])) $acls['projects'] = array_merge($acls['projects'], $acl['projects']);
  948. if(!$productAllow && !empty($acl['products'])) $acls['products'] = array_merge($acls['products'], $acl['products']);
  949. if(!$sprintAllow && !empty($acl['sprints'])) $acls['sprints'] = array_merge($acls['sprints'], $acl['sprints']);
  950. if(!$actionAllow && !empty($acl['actions'])) $acls['actions'] = array_merge($acls['actions'], $acl['actions']);
  951. if(!$viewAllow && !empty($acl['views'])) $acls['views'] = array_merge($acls['views'], $acl['views']);
  952. }
  953. /* 只要有一个权限分组的某个配置为空,就代表该配置没有访问限制。 */
  954. if($programAllow) $acls['programs'] = array();
  955. if($projectAllow) $acls['projects'] = array();
  956. if($productAllow) $acls['products'] = array();
  957. if($sprintAllow) $acls['sprints'] = array();
  958. if($viewAllow) $acls['views'] = array();
  959. if($actionAllow) $acls['actions'] = array();
  960. if($actionAllow && empty($acls['actions'])) unset($acls['actions']);
  961. return $acls;
  962. }
  963. /**
  964. * 获取某个用户的权限。
  965. * Get user's rights.
  966. *
  967. * @param string $account
  968. * @access public
  969. * @return array the user rights.
  970. */
  971. public function authorize($account)
  972. {
  973. $account = filter_var($account, FILTER_UNSAFE_RAW);
  974. if(!$account) return array();
  975. $acls = $this->getUserAcls($account);
  976. if($account == 'guest')
  977. {
  978. $stmt = $this->dao->select('module, method')->from(TABLE_GROUP)->alias('t1')->leftJoin(TABLE_GROUPPRIV)->alias('t2')->on('t1.id = t2.`group`')->where('t1.name')->eq('guest')->query();
  979. }
  980. else
  981. {
  982. $stmt = $this->dao->select('module, method')->from(TABLE_GROUP)->alias('t1')
  983. ->leftJoin(TABLE_USERGROUP)->alias('t2')->on('t1.id = t2.`group`')
  984. ->leftJoin(TABLE_GROUPPRIV)->alias('t3')->on('t2.`group` = t3.`group`')
  985. ->where('t2.account')->eq($account)
  986. ->andWhere('t1.project')->eq(0)
  987. ->andWhere('t1.vision')->eq($this->config->vision)
  988. ->query();
  989. }
  990. if(!$stmt) return array('rights' => array(), 'acls' => $acls);
  991. /* 获取用户拥有的权限列表,而首页是大家都应该有的权限。 */
  992. $rights = array('index' => array('index' => 1), 'my' => array('index' => 1));
  993. while($row = $stmt->fetch(PDO::FETCH_ASSOC))
  994. {
  995. if($row['module'] && $row['method']) $rights[strtolower($row['module'])][strtolower($row['method'])] = true;
  996. }
  997. /* Get can manage projects by user. */
  998. $canManageProjects = $canManagePrograms = $canManageProducts = $canManageExecutions = '';
  999. if(!$this->app->upgrading)
  1000. {
  1001. $canManageObjects = $this->dao->select('programs,projects,products,executions')->from(TABLE_PROJECTADMIN)->where('account')->eq($account)->fetchAll();
  1002. foreach($canManageObjects as $object)
  1003. {
  1004. if($object->projects) $canManageProjects .= $object->projects . ',';
  1005. if($object->products) $canManageProducts .= $object->products . ',';
  1006. if($object->programs) $canManagePrograms .= $object->programs . ',';
  1007. if($object->executions) $canManageExecutions .= $object->executions . ',';
  1008. }
  1009. }
  1010. return array('rights' => $rights, 'acls' => $acls, 'projects' => $canManageProjects, 'programs' => $canManagePrograms, 'products' => $canManageProducts, 'executions' => $canManageExecutions);
  1011. }
  1012. /**
  1013. * 获取用户所属权限组、权限和视图,记录日志并发放登录积分。
  1014. * Get user's groups, rights and views, save log and give login score.
  1015. *
  1016. * @param object $user
  1017. * @param bool $addAction
  1018. * @param bool $keepLogin
  1019. * @access public
  1020. * @return false|object
  1021. */
  1022. public function login($user, $addAction = true, $keepLogin = false)
  1023. {
  1024. if(empty($user->account)) return false;
  1025. if($user->fails || $user->locked) $this->cleanLocked($user->account);
  1026. /* 获取用户所属权限组、权限和视图,判断用户是否是管理员。*/
  1027. /* Get user's groups, rights and views, and judge if the user is admin. */
  1028. $user->rights = $this->authorize($user->account);
  1029. $user->groups = $this->getGroups($user->account);
  1030. $user->view = $this->grantUserView($user->account, $user->rights['acls'], $user->rights['projects']);
  1031. $user->admin = strpos($this->app->company->admins, ",{$user->account},") !== false;
  1032. $this->session->set('user', $user);
  1033. $this->app->user = $this->session->user;
  1034. /* 记录登录日志并发放积分。*/
  1035. /* Save log and give login score. */
  1036. if(isset($user->id) and $addAction) $this->loadModel('action')->create('user', $user->id, 'login');
  1037. $this->loadModel('score')->create('user', 'login');
  1038. /* 保持登录状态。*/
  1039. /* Keep login. */
  1040. if($keepLogin) $this->keepLogin($user);
  1041. return $user;
  1042. }
  1043. /**
  1044. * 保持用户的登录状态。
  1045. * Keep user's login state.
  1046. *
  1047. * @param object $user
  1048. * @access public
  1049. * @return bool
  1050. */
  1051. public function keepLogin($user)
  1052. {
  1053. helper::setcookie('keepLogin', 'on');
  1054. helper::setcookie('za', $user->account);
  1055. helper::setcookie('zp', sha1($user->account . $user->password . $this->server->request_time));
  1056. return true;
  1057. }
  1058. /**
  1059. * 判断用户是否已经登录。
  1060. * Check if the user has logged in.
  1061. *
  1062. * @access public
  1063. * @return bool
  1064. */
  1065. public function isLogon()
  1066. {
  1067. $user = $this->session->user;
  1068. return ($user && !empty($user->account) && $user->account != 'guest');
  1069. }
  1070. /**
  1071. * 获取用户所属的权限组。
  1072. * Get groups a user belongs to.
  1073. *
  1074. * @param string $account
  1075. * @access public
  1076. * @return array
  1077. */
  1078. public function getGroups($account)
  1079. {
  1080. return $this->dao->findByAccount($account)->from(TABLE_USERGROUP)->fields('`group`')->fetchPairs();
  1081. }
  1082. /**
  1083. * 根据界面类型获取权限组。
  1084. * Get groups by visions.
  1085. *
  1086. * @param string|array $visions
  1087. * @access public
  1088. * @return array
  1089. */
  1090. public function getGroupsByVisions($visions)
  1091. {
  1092. if(is_string($visions)) $visions = array_unique(array_filter(explode(',', $visions)));
  1093. if(!$visions) return array();
  1094. $groups = $this->dao->select('id, name, vision')->from(TABLE_GROUP)
  1095. ->where('project')->eq(0)
  1096. ->andWhere('role')->ne('projectAdmin')
  1097. ->andWhere('vision')->in($visions)
  1098. ->fetchAll('id');
  1099. $visionCount = count($visions);
  1100. $visionList = getVisions();
  1101. foreach($groups as $id => $group)
  1102. {
  1103. $groups[$id] = $group->name;
  1104. if($visionCount > 1 && !empty($visionList[$group->vision])) $groups[$id] = $visionList[$group->vision] . ' / ' . $group->name;
  1105. }
  1106. return $groups;
  1107. }
  1108. /**
  1109. * 获取某个用户参与的项目。
  1110. * Get the projects that a user participated in.
  1111. *
  1112. * @param string $account
  1113. * @param string $status
  1114. * @param string $orderBy
  1115. * @param object $pager
  1116. * @access public
  1117. * @return array
  1118. */
  1119. public function getProjects($account, $status = 'all', $orderBy = 'id_desc', $pager = null)
  1120. {
  1121. $this->loadModel('project');
  1122. $projects = $this->userTao->fetchProjects($account, $status, $orderBy, $pager);
  1123. if(!$projects) return array();
  1124. $projectStoryCountAndEstimate = $this->userTao->fetchProjectStoryCountAndEstimate(array_keys($projects));
  1125. $projectExecutionCount = $this->userTao->fetchProjectExecutionCount(array_keys($projects));
  1126. foreach($projects as $project)
  1127. {
  1128. /* Judge whether the project is delayed. */
  1129. if($project->status != 'done' && $project->status != 'closed' && $project->status != 'suspended')
  1130. {
  1131. $delay = helper::diffDate(helper::today(), $project->end);
  1132. if($delay > 0) $project->delay = $delay;
  1133. }
  1134. $projectStory = zget($projectStoryCountAndEstimate, $project->id, '');
  1135. $project->storyPoints = $projectStory ? round($projectStory->estimate, 1) : 0;
  1136. $project->storyCount = $projectStory ? $projectStory->count : 0;
  1137. $project->executionCount = zget($projectExecutionCount, $project->id, 0);
  1138. }
  1139. if(in_array($this->config->edition, array('max', 'ipd'))) $projects = $this->project->countDeliverable($projects, 'project');
  1140. return $projects;
  1141. }
  1142. /**
  1143. * 获取某个用户参与的执行。
  1144. * Get the executions that a user participated in.
  1145. *
  1146. * @param string $account
  1147. * @param string $status
  1148. * @param string $orderBy
  1149. * @param object $pager
  1150. * @access public
  1151. * @return array
  1152. */
  1153. public function getExecutions($account, $status = 'all', $orderBy = 'id_desc', $pager = null)
  1154. {
  1155. $executions = $this->userTao->fetchExecutions($account, $status, $orderBy, $pager);
  1156. if(!$executions) return array();
  1157. $projectIdList = array_map(function($execution){return $execution->project;}, $executions);
  1158. $projectPairs = $this->loadModel('project')->getPairsByIdList($projectIdList);
  1159. $taskCountList = $this->userTao->fetchExecutionTaskCount($account, array_keys($executions));
  1160. foreach($executions as $execution)
  1161. {
  1162. /* Judge whether the execution is delayed. */
  1163. if($execution->status != 'done' && $execution->status != 'closed' && $execution->status != 'suspended')
  1164. {
  1165. $delay = helper::diffDate(helper::today(), $execution->end);
  1166. if($delay > 0) $execution->delay = $delay;
  1167. }
  1168. $execution->projectName = zget($projectPairs, $execution->project, '');
  1169. $execution->assignedToMeTasks = zget($taskCountList, $execution->id, 0);
  1170. }
  1171. return $executions;
  1172. }
  1173. /**
  1174. * 登录失败次数加 1。
  1175. * The number of failed login attempts is increased by 1.
  1176. *
  1177. * @param string $account
  1178. * @access public
  1179. * @return int
  1180. */
  1181. public function failPlus($account)
  1182. {
  1183. if(!validater::checkAccount($account)) return 0;
  1184. /* Save session fails. */
  1185. $sessionFails = (int)$this->session->loginFails;
  1186. $sessionFails += 1;
  1187. $this->session->set('loginFails', $sessionFails);
  1188. if($sessionFails >= $this->config->user->failTimes) $this->session->set("{$account}.loginLocked", date('Y-m-d H:i:s'));
  1189. $user = $this->dao->select('fails')->from(TABLE_USER)->where('account')->eq($account)->fetch();
  1190. if(empty($user)) return 0;
  1191. $fails = $user->fails;
  1192. $fails ++;
  1193. if($fails < $this->config->user->failTimes)
  1194. {
  1195. $this->dao->update(TABLE_USER)->set('fails')->eq($fails)->set('locked = NULL')->where('account')->eq($account)->exec();
  1196. return $fails;
  1197. }
  1198. $this->dao->update(TABLE_USER)->set('fails')->eq(0)->set('locked')->eq(date('Y-m-d H:i:s'))->where('account')->eq($account)->exec();
  1199. return $fails;
  1200. }
  1201. /**
  1202. * 检查用户是否被锁定。
  1203. * Check whether the user is locked.
  1204. *
  1205. * @param string $account
  1206. * @access public
  1207. * @return bool
  1208. */
  1209. public function checkLocked($account)
  1210. {
  1211. $user = $this->dao->select('locked')->from(TABLE_USER)->where('account')->eq($account)->fetch();
  1212. if(empty($user) || empty($user->locked)) return false;
  1213. if($this->session->{"{$account}.loginLocked"} && (time() - strtotime($this->session->{"{$account}.loginLocked"})) <= $this->config->user->lockMinutes * 60) return true;
  1214. if((time() - strtotime($user->locked)) > $this->config->user->lockMinutes * 60) return false;
  1215. return true;
  1216. }
  1217. /**
  1218. * 解锁被锁定的用户。
  1219. * Unlock the locked user.
  1220. *
  1221. * @param string $account
  1222. * @access public
  1223. * @return bool
  1224. */
  1225. public function cleanLocked($account)
  1226. {
  1227. $this->dao->update(TABLE_USER)->set('fails')->eq(0)->set('locked = NULL')->where('account')->eq($account)->exec();
  1228. unset($_SESSION['loginFails']);
  1229. unset($_SESSION["{$account}.loginLocked"]);
  1230. return !dao::isError();
  1231. }
  1232. /**
  1233. * 解除禅道账号和 ZDOO 账号的绑定。
  1234. * Unbind ZDOO account and ZenTao account.
  1235. *
  1236. * @param string $account
  1237. * @access public
  1238. * @return bool
  1239. */
  1240. public function unbind($account)
  1241. {
  1242. $this->dao->update(TABLE_USER)->set('ranzhi')->eq('')->where('account')->eq($account)->exec();
  1243. return !dao::isError();
  1244. }
  1245. /**
  1246. * 上传头像。
  1247. * Upload avatar.
  1248. *
  1249. * @access public
  1250. * @return array
  1251. */
  1252. public function uploadAvatar()
  1253. {
  1254. $uploadResult = $this->loadModel('file')->saveUpload('avatar');
  1255. if(!$uploadResult) return array('result' => 'fail', 'message' => $this->lang->fail);
  1256. $fileIdList = array_keys($uploadResult);
  1257. $file = $this->file->getByID(end($fileIdList));
  1258. $imageExtensions = $this->config->file->imageExtensions;
  1259. if(!in_array($file->extension, $imageExtensions)) return array('result' => 'fail', 'message' => sprintf($this->lang->user->error->uploadAvatar, implode(', ', $imageExtensions)));
  1260. return array('result' => 'success', 'message' => '', 'fileID' => $file->id, 'locate' => helper::createLink('user', 'cropavatar', "image={$file->id}"));
  1261. }
  1262. /**
  1263. * 获取某个用户可以查看的联系人列表。
  1264. * Get the contact list of a user.
  1265. *
  1266. * @param string $account
  1267. * @param string $mode pairs|list
  1268. * @access public
  1269. * @return array
  1270. */
  1271. public function getContactLists($account = '', $mode = 'pairs')
  1272. {
  1273. if(!$account) $account = $this->app->user->account;
  1274. $this->dao->select('*')->from(TABLE_USERCONTACT)
  1275. ->where('account')->eq($account)
  1276. ->orWhere('public')->eq(1)
  1277. ->orderBy('public, id_desc');
  1278. if($mode == 'pairs') return $this->dao->fetchPairs('id', 'listName');
  1279. return $this->dao->fetchAll();
  1280. }
  1281. /**
  1282. * 获取拥有迭代访问权限的用户列表。
  1283. * Get users who have access to the parent stage.
  1284. *
  1285. * @param int $stageID
  1286. * @access public
  1287. * @return array
  1288. */
  1289. public function getParentStageAuthedUsers($stageID = 0)
  1290. {
  1291. return $this->dao->select('account')->from(TABLE_USERVIEW)->where("FIND_IN_SET({$stageID}, sprints)")->fetchPairs();
  1292. }
  1293. /**
  1294. * 根据 id 获取一个联系人列表。
  1295. * Get a contact list by id.
  1296. *
  1297. * @param int $listID
  1298. * @access public
  1299. * @return object|false
  1300. */
  1301. public function getContactListByID($listID)
  1302. {
  1303. return $this->dao->select('*')->from(TABLE_USERCONTACT)->where('id')->eq($listID)->fetch();
  1304. }
  1305. /**
  1306. * 创建一个联系人列表。
  1307. * Create a contact list.
  1308. *
  1309. * @param object $userContact
  1310. * @access public
  1311. * @return bool
  1312. */
  1313. public function createContactList($userContact)
  1314. {
  1315. $this->dao->insert(TABLE_USERCONTACT)->data($userContact)
  1316. ->batchCheck('listName,userList', 'notempty')
  1317. ->check('listName', 'unique', "account = '{$userContact->account}'")
  1318. ->autoCheck()
  1319. ->exec();
  1320. return !dao::isError();
  1321. }
  1322. /**
  1323. * 更新一个联系人列表。
  1324. * Update a contact list.
  1325. *
  1326. * @param object $userContact
  1327. * @access public
  1328. * @return bool
  1329. */
  1330. public function updateContactList($userContact)
  1331. {
  1332. $this->dao->update(TABLE_USERCONTACT)->data($userContact)
  1333. ->batchCheck('listName,userList', 'notempty')
  1334. ->check('listName', 'unique', "id != '{$userContact->id}' AND account = '{$userContact->account}'")
  1335. ->autoCheck()
  1336. ->where('id')->eq($userContact->id)
  1337. ->exec();
  1338. return !dao::isError();
  1339. }
  1340. /**
  1341. * 删除一个联系人列表。
  1342. * Delete a contact list.
  1343. *
  1344. * @param int $listID
  1345. * @access public
  1346. * @return bool
  1347. */
  1348. public function deleteContactList($listID)
  1349. {
  1350. $this->dao->delete()->from(TABLE_USERCONTACT)->where('id')->eq($listID)->exec();
  1351. return !dao::isError();
  1352. }
  1353. /**
  1354. * 获取弱密码用户。
  1355. * Get weak users.
  1356. *
  1357. * @access public
  1358. * @return array
  1359. */
  1360. public function getWeakUsers()
  1361. {
  1362. $weaks = array();
  1363. foreach(explode(',', $this->config->safe->weak) as $weak)
  1364. {
  1365. if($weak) $weaks[$weak] = md5(trim($weak));
  1366. }
  1367. $weakUsers = array();
  1368. $users = $this->dao->select('*')->from(TABLE_USER)->where('deleted')->eq('0')->fetchAll();
  1369. foreach($users as $user)
  1370. {
  1371. if(isset($weaks[$user->password]) || in_array($user->password, $weaks))
  1372. {
  1373. $user->weakReason = 'weak';
  1374. $weakUsers[] = $user;
  1375. continue;
  1376. }
  1377. foreach(array('account', 'phone', 'mobile', 'birthday') as $field)
  1378. {
  1379. if(empty($user->$field)) continue;
  1380. if($user->password == $user->$field || $user->password == md5($user->$field))
  1381. {
  1382. $user->weakReason = $field;
  1383. $weakUsers[] = $user;
  1384. break;
  1385. }
  1386. }
  1387. }
  1388. return $weakUsers;
  1389. }
  1390. /**
  1391. * 计算密码强度。
  1392. * Compute password strength.
  1393. *
  1394. * @param string $password
  1395. * @access public
  1396. * @return int
  1397. */
  1398. public function computePasswordStrength($password)
  1399. {
  1400. $length = strlen($password);
  1401. if($length == 0) return 0;
  1402. $complexity = array();
  1403. $chars = str_split($password);
  1404. foreach($chars as $letter)
  1405. {
  1406. $asc = ord($letter);
  1407. if($asc >= 48 && $asc <= 57)
  1408. {
  1409. $complexity[0] = 1;
  1410. }
  1411. elseif($asc >= 65 && $asc <= 90)
  1412. {
  1413. $complexity[1] = 2;
  1414. }
  1415. elseif($asc >= 97 && $asc <= 122)
  1416. {
  1417. $complexity[2] = 4;
  1418. }
  1419. else
  1420. {
  1421. $complexity[3] = 8;
  1422. }
  1423. }
  1424. $sumComplexity = array_sum($complexity);
  1425. if($sumComplexity == 15 && $length >= 10) return 2;
  1426. if(($sumComplexity == 7 || $sumComplexity == 15) && $length >= 6) return 1;
  1427. return 0;
  1428. }
  1429. /**
  1430. * 初始化访问权限所属的数据。
  1431. * Init user view objects.
  1432. *
  1433. * @param string $account
  1434. * @access private
  1435. * @return array
  1436. */
  1437. private function initViewObjects($account)
  1438. {
  1439. $this->loadModel('project');
  1440. static $allProducts, $allProjects, $allPrograms, $allSprints, $teams, $whiteList, $stakeholders;
  1441. if(!$allProducts) $allProducts = $this->loadModel('product')->getListByAcl('private');
  1442. if(!$allProjects) $allProjects = $this->project->getListByAclAndType('private,program', 'project');
  1443. if(!$allPrograms) $allPrograms = $this->project->getListByAclAndType('private,program', 'program');
  1444. if(!$allSprints) $allSprints = $this->project->getListByAclAndType('private', 'sprint,stage,kanban');
  1445. if(empty($teams[$account]))
  1446. {
  1447. $teams[$account] = [];
  1448. $teamList = $this->project->getTeamListByType('project,execution', $account);
  1449. foreach($teamList as $team) $teams[$account][$team->type][$team->root][$team->account] = $team->account;
  1450. }
  1451. /* Get white list. */
  1452. if(empty($whiteList[$account]))
  1453. {
  1454. $whiteList[$account] = [];
  1455. $aclList = $this->project->getAclListByObjectType('program,project,sprint,product', $account);
  1456. foreach($aclList as $acl) $whiteList[$account][$acl->objectType][$acl->objectID][$acl->account] = $acl->account;
  1457. }
  1458. /* Get stakeholders. */
  1459. if(empty($stakeholders[$account]))
  1460. {
  1461. $stakeholders[$account] = [];
  1462. $cachedHolders = $this->dao->select('objectID, objectType, user')->from(TABLE_STAKEHOLDER)->where('deleted')->eq('0')->andWhere('user')->eq($account)->fetchAll();
  1463. foreach($cachedHolders as $holder) $stakeholders[$account][$holder->objectType][$holder->objectID][$holder->user] = $holder->user;
  1464. }
  1465. return array($allProducts, $allProjects, $allPrograms, $allSprints, $teams[$account], $whiteList[$account], $stakeholders[$account]);
  1466. }
  1467. /**
  1468. * 获取用户的可访问项目集。
  1469. * Get program user view.
  1470. *
  1471. * @param string $account
  1472. * @param array $allPrograms
  1473. * @param array $manageObjects
  1474. * @param array $stakeholders
  1475. * @param array $whiteList
  1476. * @param array $programStakeholderGroup
  1477. * @access private
  1478. * @return string
  1479. */
  1480. private function getProgramView($account, $allPrograms, $manageObjects, $stakeholders, $whiteList, $programStakeholderGroup)
  1481. {
  1482. $programView = '';
  1483. if(!empty($manageObjects['programs']['isAdmin']))
  1484. {
  1485. $programView = implode(',', array_keys($allPrograms));
  1486. }
  1487. else
  1488. {
  1489. $programs = array();
  1490. $managePrograms = isset($manageObjects['programs']['list']) ? $manageObjects['programs']['list'] : '';
  1491. foreach($allPrograms as $programID => $program)
  1492. {
  1493. /* 如果是某个项目集的干系人,也可以访问该项目集。 */
  1494. $programStakeholders = !empty($stakeholders['program'][$programID]) ? $stakeholders['program'][$programID] : array();
  1495. if($program->acl == 'program') $programStakeholders += zget($programStakeholderGroup, $programID, array());
  1496. /* 如果是某个项目集的白名单用户,也可以访问该项目集。 */
  1497. $programWhiteList = !empty($whiteList['program'][$programID]) ? $whiteList['program'][$programID] : array();
  1498. if($this->checkProgramPriv($program, $account, $programStakeholders, $programWhiteList)) $programs[$programID] = $programID;
  1499. /* 如果有某个项目集的管理权限,也可以访问该项目集。 */
  1500. if(strpos(",$managePrograms,", ",$programID,") !== false) $programs[$programID] = $programID;
  1501. }
  1502. $programView = implode(',', $programs);
  1503. }
  1504. return $programView;
  1505. }
  1506. /**
  1507. * 获取用户的可访问产品。
  1508. * Get product user view.
  1509. *
  1510. * @param string $account
  1511. * @param array $allProducts
  1512. * @param array $manageObjects
  1513. * @param array $whiteList
  1514. * @access private
  1515. * @return string
  1516. */
  1517. private function getProductView($account, $allProducts, $manageObjects, $whiteList)
  1518. {
  1519. $productView = '';
  1520. if(!empty($manageObjects['products']['isAdmin']))
  1521. {
  1522. $productView = implode(',', array_keys($allProducts));
  1523. }
  1524. else
  1525. {
  1526. $products = array();
  1527. $manageProducts = isset($manageObjects['products']['list']) ? $manageObjects['products']['list'] : '';
  1528. list($productTeams, $productStakeholders) = $this->getProductMembers($allProducts, $account);
  1529. foreach($allProducts as $productID => $product)
  1530. {
  1531. /* 根据团队、干系人、白名单判断是否可以访问该产品。 */
  1532. $productTeam = zget($productTeams, $productID, array());
  1533. $productStakeholder = zget($productStakeholders, $productID, array());
  1534. $productWhiteList = !empty($whiteList['product'][$productID]) ? $whiteList['product'][$productID] : array();
  1535. if($this->checkProductPriv($product, $account, $productTeam, $productStakeholder, $productWhiteList)) $products[$productID] = $productID;
  1536. /* 如果有某个产品的管理权限,也可以访问该产品。 */
  1537. if(strpos(",$manageProducts,", ",$productID,") !== false) $products[$productID] = $productID;
  1538. }
  1539. $productView = implode(',', $products);
  1540. }
  1541. return $productView;
  1542. }
  1543. /**
  1544. * 获取用户的可访问项目。
  1545. * Get project user view.
  1546. *
  1547. * @param string $account
  1548. * @param array $allProjects
  1549. * @param array $manageObjects
  1550. * @param array $teams
  1551. * @param array $stakeholders
  1552. * @param array $whiteList
  1553. * @param array $projectStakeholderGroup
  1554. * @access private
  1555. * @return string
  1556. */
  1557. private function getProjectView($account, $allProjects, $manageObjects, $teams, $stakeholders, $whiteList, $projectStakeholderGroup)
  1558. {
  1559. $projectView = '';
  1560. if(!empty($manageObjects['projects']['isAdmin']))
  1561. {
  1562. $projectView = implode(',', array_keys($allProjects));
  1563. }
  1564. else
  1565. {
  1566. $projects = array();
  1567. $manageProjects = isset($manageObjects['projects']['list']) ? $manageObjects['projects']['list'] : '';
  1568. foreach($allProjects as $projectID => $project)
  1569. {
  1570. /* 根据团队、干系人、白名单判断是否可以访问该项目。 */
  1571. $projectTeams = !empty($teams['project'][$projectID]) ? $teams['project'][$projectID] : array();
  1572. $projectStakeholders = !empty($stakeholders['project'][$projectID]) ? $stakeholders['project'][$projectID] : array();
  1573. $projectWhiteList = !empty($whiteList['project'][$projectID]) ? $whiteList['project'][$projectID] : array();
  1574. if($project->acl == 'program') $projectStakeholders += zget($projectStakeholderGroup, $projectID, array());
  1575. if($this->checkProjectPriv($project, $account, $projectStakeholders, $projectTeams, $projectWhiteList)) $projects[$projectID] = $projectID;
  1576. /* 如果有某个项目管理权限,也可以访问该项目。 */
  1577. if(strpos(",$manageProjects,", ",$projectID,") !== false) $projects[$projectID] = $projectID;
  1578. }
  1579. $projectView = implode(',', $projects);
  1580. }
  1581. return $projectView;
  1582. }
  1583. /**
  1584. * 获取用户的可访问迭代。
  1585. * Get sprint user view.
  1586. *
  1587. * @param string $account
  1588. * @param array $allSprints
  1589. * @param array $manageObjects
  1590. * @param array $teams
  1591. * @param array $stakeholders
  1592. * @param array $whiteList
  1593. * @param array $executionStakeholderGroup
  1594. * @access private
  1595. * @return string
  1596. */
  1597. private function getSprintView($account, $allSprints, $manageObjects, $teams, $stakeholders, $whiteList, $executionStakeholderGroup)
  1598. {
  1599. $sprintView = '';
  1600. if(!empty($manageObjects['executions']['isAdmin']))
  1601. {
  1602. $sprintView = implode(',', array_keys($allSprints));
  1603. }
  1604. else
  1605. {
  1606. $sprints = array();
  1607. $manageExecutions = isset($manageObjects['executions']['list']) ? $manageObjects['executions']['list'] : '';
  1608. foreach($allSprints as $sprintID => $sprint)
  1609. {
  1610. /* 根据团队、干系人、白名单判断是否可以访问该迭代。 */
  1611. $sprintTeams = !empty($teams['execution'][$sprintID]) ? $teams['execution'][$sprintID] : array();
  1612. $sprintStakeholders = !empty($stakeholders['execution'][$sprintID]) ? $stakeholders['execution'][$sprintID] : array();
  1613. $sprintWhiteList = !empty($whiteList['sprint'][$sprintID]) ? $whiteList['sprint'][$sprintID] : array();
  1614. if($sprint->acl == 'private') $sprintStakeholders += zget($executionStakeholderGroup, $sprintID, array());
  1615. if($this->checkProjectPriv($sprint, $account, $sprintStakeholders, $sprintTeams, $sprintWhiteList)) $sprints[$sprintID] = $sprintID;
  1616. /* 如果有某个迭代管理权限,也可以访问该迭代。 */
  1617. if(strpos(",$manageExecutions,", ",$sprintID,") !== false) $sprints[$sprintID] = $sprintID;
  1618. }
  1619. $sprintView = implode(',', $sprints);
  1620. }
  1621. return $sprintView;
  1622. }
  1623. /**
  1624. * 按照类型分组获取用户管理的对象。
  1625. * Get management objects by type grouping.
  1626. *
  1627. * @param string $account
  1628. * @access private
  1629. * @return array
  1630. */
  1631. private function getManageListGroupByType($account)
  1632. {
  1633. $manageObjects = array();
  1634. $projectAdmins = $this->dao->select('`group`,programs,products,projects,executions')->from(TABLE_PROJECTADMIN)->where('account')->eq($account)->fetchAll('group');
  1635. foreach($projectAdmins as $projectAdmin)
  1636. {
  1637. foreach($projectAdmin as $key => $value)
  1638. {
  1639. if(!isset($manageObjects[$key]['list'])) $manageObjects[$key]['list'] = '';
  1640. if($value == 'all')
  1641. {
  1642. $manageObjects[$key]['isAdmin'] = 1;
  1643. }
  1644. else if($value)
  1645. {
  1646. $manageObjects[$key]['list'] .= $value . ',';
  1647. }
  1648. }
  1649. }
  1650. return $manageObjects;
  1651. }
  1652. /**
  1653. * 获取用户的可访问对象。
  1654. * Compute user view.
  1655. *
  1656. * @param string $account
  1657. * @param bool $force 是否重新生成
  1658. * @access public
  1659. * @return object
  1660. */
  1661. public function computeUserView($account = '', $force = false)
  1662. {
  1663. if(empty($account))
  1664. {
  1665. $account = $this->session->user->account;
  1666. if(empty($account))
  1667. {
  1668. $userView = new stdclass();
  1669. $userView->products = $userView->programs = $userView->projects = $userView->sprints = '';
  1670. return $userView;
  1671. }
  1672. }
  1673. $oldUserView = $this->dao->select('*')->from(TABLE_USERVIEW)->where('account')->eq($account)->fetch();
  1674. if(!$force)
  1675. {
  1676. $userviewUpdateTime = $this->config->userview->updateTime ?? 0; // 当前用户访问权限的更新时间。
  1677. $relatedTablesUpdateTime = $this->config->userview->relatedTablesUpdateTime ?? 0; // 访问权限相关表的更新时间。
  1678. $force = empty($userviewUpdateTime) || empty($relatedTablesUpdateTime) || $userviewUpdateTime <= $relatedTablesUpdateTime;
  1679. }
  1680. if(!$force)
  1681. {
  1682. if($oldUserView) return $oldUserView;
  1683. $userView = new stdclass();
  1684. $userView->products = $userView->programs = $userView->projects = $userView->sprints = '';
  1685. return $userView;
  1686. }
  1687. /* Init objects. */
  1688. list($allProducts, $allProjects, $allPrograms, $allSprints, $teams, $whiteList, $stakeholders) = $this->initViewObjects($account);
  1689. /* Init user view. */
  1690. $userView = new stdclass();
  1691. $userView->account = $account;
  1692. $isAdmin = strpos($this->app->company->admins, ',' . $account . ',') !== false;
  1693. if($isAdmin)
  1694. {
  1695. $userView->programs = implode(',', array_keys($allPrograms));
  1696. $userView->products = implode(',', array_keys($allProducts));
  1697. $userView->projects = implode(',', array_keys($allProjects));
  1698. $userView->sprints = implode(',', array_keys($allSprints));
  1699. }
  1700. else
  1701. {
  1702. /* Compute parent stakeholders. */
  1703. $this->loadModel('stakeholder');
  1704. $programStakeholderGroup = $this->stakeholder->getParentStakeholderGroup(array_keys($allPrograms));
  1705. $projectStakeholderGroup = $this->stakeholder->getParentStakeholderGroup(array_keys($allProjects));
  1706. $executionStakeholderGroup = $this->stakeholder->getParentStakeholderGroup(array_keys($allSprints));
  1707. /* 按照类型分组获取当前用户所拥有的的项目管理权限。 */
  1708. $manageObjects = $this->getManageListGroupByType($account);
  1709. /* 分别获取各类型的可浏览ID。 */
  1710. $userView->programs = $this->getProgramView($account, $allPrograms, $manageObjects, $stakeholders, $whiteList, $programStakeholderGroup);
  1711. $userView->products = $this->getProductView($account, $allProducts, $manageObjects, $whiteList);
  1712. $userView->projects = $this->getProjectView($account, $allProjects, $manageObjects, $teams, $stakeholders, $whiteList, $projectStakeholderGroup);
  1713. $userView->sprints = $this->getSprintView($account, $allSprints, $manageObjects, $teams, $stakeholders, $whiteList, $executionStakeholderGroup);
  1714. }
  1715. /* 更新访问权限表。 */
  1716. $this->dao->begin();
  1717. if(empty($oldUserView))
  1718. {
  1719. $this->dao->insert(TABLE_USERVIEW)->data($userView)->exec();
  1720. }
  1721. else
  1722. {
  1723. $this->dao->update(TABLE_USERVIEW)->data($userView)->where('account')->eq($account)->exec();
  1724. }
  1725. $this->loadModel('setting')->setItem("$account|common|userview|updateTime", time(), '|');
  1726. $this->dao->commit();
  1727. return $userView;
  1728. }
  1729. /**
  1730. * 获取产品关联的项目集干系人。
  1731. * Get program stakeholder.
  1732. *
  1733. * @param array $programProduct
  1734. * @access private
  1735. * @return array
  1736. */
  1737. private function getProgramStakeholder($programProduct)
  1738. {
  1739. $stakeholderGroups = array();
  1740. $stmt = $this->dao->select('objectID,user')->from(TABLE_STAKEHOLDER)
  1741. ->where('objectType')->eq('program')
  1742. ->andWhere('objectID')->in(array_keys($programProduct))
  1743. ->query();
  1744. while($programStakeholder = $stmt->fetch())
  1745. {
  1746. $productIDList = zget($programProduct, $programStakeholder->objectID, array());
  1747. foreach($productIDList as $productID) $stakeholderGroups[$productID][$programStakeholder->user] = $programStakeholder->user;
  1748. }
  1749. $programOwners = $this->mao->select('id,PM')->from(TABLE_PROGRAM)
  1750. ->where('type')->eq('program')
  1751. ->andWhere('id')->in(array_keys($programProduct))
  1752. ->fetchAll();
  1753. foreach($programOwners as $programOwner)
  1754. {
  1755. $productIDList = zget($programProduct, $programOwner->id, array());
  1756. foreach($productIDList as $productID) $stakeholderGroups[$productID][$programOwner->PM] = $programOwner->PM;
  1757. }
  1758. return $stakeholderGroups;
  1759. }
  1760. /**
  1761. * 获取产品的所属团队和干系人。
  1762. * Get product teams and stakeholders.
  1763. *
  1764. * @param array $allProducts
  1765. * @param string $account
  1766. * @access protected
  1767. * @return array
  1768. */
  1769. protected function getProductMembers($allProducts, $account = '')
  1770. {
  1771. /* Get product and project relation. */
  1772. $projectProducts = array();
  1773. $stmt = $this->dao->select('t1.project, t1.product')->from(TABLE_PROJECTPRODUCT)->alias('t1')
  1774. ->leftJoin(TABLE_PROJECT)->alias('t2')->on('t1.project = t2.id')
  1775. ->where('t1.product')->in(array_keys($allProducts))
  1776. ->andWhere('t2.deleted')->eq('0')
  1777. ->query();
  1778. while($projectProduct = $stmt->fetch()) $projectProducts[$projectProduct->project][$projectProduct->product] = $projectProduct->product;
  1779. /* Get linked projects stakeholders. */
  1780. $stmt = $this->dao->select('objectID,user')->from(TABLE_STAKEHOLDER)
  1781. ->where('objectType')->eq('project')
  1782. ->andWhere('objectID')->in(array_keys($projectProducts))
  1783. ->andWhere('deleted')->eq(0)
  1784. ->query();
  1785. $stakeholderGroups = array();
  1786. while($stakeholder = $stmt->fetch())
  1787. {
  1788. $productIdList = zget($projectProducts, $stakeholder->objectID, array());
  1789. foreach($productIdList as $productID) $stakeholderGroups[$productID][$stakeholder->user] = $stakeholder->user;
  1790. }
  1791. /* Get linked programs stakeholders. */
  1792. $programProduct = array();
  1793. foreach($allProducts as $product)
  1794. {
  1795. if($product->program) $programProduct[$product->program][$product->id] = $product->id;
  1796. }
  1797. if($programProduct)
  1798. {
  1799. $programStakeholderGroup = $this->getProgramStakeholder($programProduct);
  1800. foreach($programStakeholderGroup as $productID => $stakeholders)
  1801. {
  1802. if(isset($stakeholderGroups[$productID]))
  1803. {
  1804. $stakeholderGroups[$productID] = arrayUnion($stakeholderGroups[$productID], $stakeholders);
  1805. }
  1806. else
  1807. {
  1808. $stakeholderGroups[$productID] = $stakeholders;
  1809. }
  1810. }
  1811. }
  1812. /* Get linked projects teams. */
  1813. $teamsGroup = array();
  1814. $teamList = $this->loadModel('project')->getTeamListByType('project', $account);
  1815. foreach($teamList as $team)
  1816. {
  1817. if(!isset($projectProducts[$team->root])) continue;
  1818. $productIdList = zget($projectProducts, $team->root, array());
  1819. foreach($productIdList as $productID) $teamsGroup[$productID][$team->account] = $team->account;
  1820. }
  1821. return array($teamsGroup, $stakeholderGroups);
  1822. }
  1823. /**
  1824. * 组装最终的用户可访问权限。
  1825. * Grant user view.
  1826. *
  1827. * @param string $account
  1828. * @param array $acls
  1829. * @param string $projects 此人管理的项目列表
  1830. * @access public
  1831. * @return object
  1832. */
  1833. public function grantUserView($account = '', $acls = array(), $projects = '')
  1834. {
  1835. if(empty($account)) $account = $this->session->user->account;
  1836. if(empty($account)) return new stdclass();
  1837. if(empty($acls) && !empty($this->session->user->rights['acls'])) $acls = $this->session->user->rights['acls'];
  1838. if(empty($projects) && !empty($this->session->user->rights['projects'])) $projects = $this->session->user->rights['projects'];
  1839. $userView = $this->computeUserView($account);
  1840. /* Get opened projects, programs, products and set it to userview. */
  1841. $openedProducts = array_keys($this->loadModel('product')->getListByAcl('open'));
  1842. $openedPrograms = array_keys($this->loadModel('project')->getListByAclAndType('open', 'program'));
  1843. $openedProjects = array_keys($this->project->getListByAclAndType('open', 'project'));
  1844. $userView->products = rtrim($userView->products, ',') . ',' . implode(',', $openedProducts);
  1845. $userView->programs = rtrim($userView->programs, ',') . ',' . implode(',', $openedPrograms);
  1846. $userView->projects = rtrim($userView->projects, ',') . ',' . implode(',', $openedProjects);
  1847. /* 合并用户视图权限到用户访问权限。 */
  1848. $userView = $this->mergeAclsToUserView($account, $userView, $acls, $projects);
  1849. $userView->products = trim($userView->products, ',');
  1850. $userView->programs = trim($userView->programs, ',');
  1851. $userView->projects = trim($userView->projects, ',');
  1852. $userView->sprints = trim($userView->sprints, ',');
  1853. return $userView;
  1854. }
  1855. /**
  1856. * 合并用户视图权限到用户访问权限。
  1857. * Merge acls to userView.
  1858. *
  1859. * @param string $account
  1860. * @param object $userView
  1861. * @param array $acls
  1862. * @param string $projects
  1863. * @access private
  1864. * @return object
  1865. */
  1866. private function mergeAclsToUserView($account, $userView, $acls, $projects)
  1867. {
  1868. if(isset($_SESSION['user']->admin)) $isAdmin = $this->session->user->admin;
  1869. if(!isset($isAdmin)) $isAdmin = strpos($this->app->company->admins, ",{$account},") !== false;
  1870. /* 权限分组-视野维护的优先级最高,所以这里进行了替换操作。*/
  1871. /* View management has the highest priority, so there is a substitution. */
  1872. if(!empty($acls['programs']) && !$isAdmin) $userView->programs = implode(',', $acls['programs']);
  1873. if(!empty($acls['products']) && !$isAdmin) $userView->products = implode(',', $acls['products']);
  1874. if(!empty($acls['sprints']) && !$isAdmin) $userView->sprints = implode(',', $acls['sprints']);
  1875. if(!empty($acls['projects']) && !$isAdmin)
  1876. {
  1877. /* If is project admin, set projectID to userview. */
  1878. if($projects) $acls['projects'] = array_merge($acls['projects'], explode(',', $projects));
  1879. $userView->projects = implode(',', $acls['projects']);
  1880. }
  1881. /* 可以看到项目,就能看到项目下公开的迭代。 */
  1882. /* Set opened sprints and stages into userview. */
  1883. $openedSprints = $this->loadModel('project')->getListByAclAndType('open', 'sprint,stage,kanban');
  1884. $openedSprints = array_filter(array_map(function($sprint) use ($userView) { if(strpos(",{$userView->projects},", ",{$sprint->project},") !== false) return $sprint->id; }, $openedSprints));
  1885. $userView->sprints = rtrim($userView->sprints, ',') . ',' . implode(',', $openedSprints);
  1886. $canViewSprints = $this->dao->select('executions')->from(TABLE_PROJECTADMIN)->where('account')->eq($account)->fetch('executions');
  1887. if($canViewSprints != 'all') $userView->sprints .= ',' . $canViewSprints;
  1888. return $userView;
  1889. }
  1890. /**
  1891. * 更新某个对象下的用户可访问视图。
  1892. * Update user view by object type.
  1893. *
  1894. * @param array $objectIDList
  1895. * @param string $objectType
  1896. * @param array $users
  1897. * @access public
  1898. * @return bool
  1899. */
  1900. public function updateUserView($objectIDList, $objectType, $users = array())
  1901. {
  1902. if($objectType == 'program') return $this->updateProgramView($objectIDList, $users);
  1903. if($objectType == 'product') return $this->updateProductView($objectIDList, $users);
  1904. if($objectType == 'project') return $this->updateProjectView($objectIDList, $users);
  1905. if($objectType == 'sprint') return $this->updateSprintView($objectIDList, $users);
  1906. return false;
  1907. }
  1908. /**
  1909. * 更新项目集下的用户访问视图。
  1910. * Update program user view.
  1911. *
  1912. * @param array $programIDList
  1913. * @param array $users
  1914. * @access private
  1915. * @return bool
  1916. */
  1917. public function updateProgramView($programIDList, $users)
  1918. {
  1919. $programs = $this->dao->select('*')->from(TABLE_PROJECT)->where('id')->in($programIDList)->andWhere('acl')->ne('open')->fetchAll('id');
  1920. if(empty($programs)) return false;
  1921. $stakeholderGroup = $this->loadModel('stakeholder')->getStakeholderGroup($programIDList); // Get self stakeholders.
  1922. $parentStakeholderGroup = $this->stakeholder->getParentStakeholderGroup($programIDList); // Get all parent program and subprogram relation.
  1923. $parentPMGroup = $this->loadModel('program')->getParentPM($programIDList); // Get all parent program and subprogram relation.
  1924. $programAdmins = $this->loadModel('group')->getAdmins($programIDList, 'programs'); // Get programs's admins.
  1925. $stmt = $this->dao->select('objectID,account')->from(TABLE_ACL)->where('objectType')->eq('program')->andWhere('objectID')->in($programIDList)->query();
  1926. $whiteListGroup = array();
  1927. while($whiteList = $stmt->fetch()) $whiteListGroup[$whiteList->objectID][$whiteList->account] = $whiteList->account;
  1928. $authedUsers = $users;
  1929. /* 如果没传users参数,则获取项目集关联的所有人。*/
  1930. if(empty($users)) $authedUsers += $this->getObjectsAuthedUsers($programs, 'program', $stakeholderGroup, array(), $whiteListGroup, $programAdmins, $parentStakeholderGroup, $parentPMGroup);
  1931. $userViews = $this->dao->select("account,programs")->from(TABLE_USERVIEW)->where('account')->in($authedUsers)->fetchPairs('account', 'programs');
  1932. /* Judge auth and update view. */
  1933. foreach(array_filter($authedUsers) as $account)
  1934. {
  1935. $view = isset($userViews[$account]) ? $userViews[$account] : '';
  1936. $latestView = $view;
  1937. foreach($programs as $program)
  1938. {
  1939. $latestView = $this->getLatestUserView($account, $latestView, $program, 'program', $stakeholderGroup, array(), $whiteListGroup, $programAdmins, $parentStakeholderGroup, $parentPMGroup);
  1940. }
  1941. if($view != $latestView)
  1942. {
  1943. if(!isset($userViews[$account]))
  1944. {
  1945. $userView = new stdclass();
  1946. $userView->account = $account;
  1947. $userView->programs = $latestView;
  1948. $userView->products = $userView->projects = $userView->sprints = '';
  1949. $this->dao->insert(TABLE_USERVIEW)->data($userView)->exec();
  1950. }
  1951. else
  1952. {
  1953. $this->dao->update(TABLE_USERVIEW)->set('programs')->eq($latestView)->where('account')->eq($account)->exec();
  1954. }
  1955. }
  1956. }
  1957. return true;
  1958. }
  1959. /**
  1960. * 更新项目下的用户访问视图。
  1961. * Update project view.
  1962. *
  1963. * @param array $projectIDList
  1964. * @param array $users
  1965. * @access private
  1966. * @return bool
  1967. */
  1968. public function updateProjectView($projectIDList, $users)
  1969. {
  1970. $projects = $this->dao->select('*')->from(TABLE_PROJECT)->where('id')->in($projectIDList)->andWhere('acl')->ne('open')->fetchAll('id');
  1971. if(empty($projects)) return false;
  1972. /* Get team group. */
  1973. $stmt = $this->dao->select('root,account')->from(TABLE_TEAM)->where('type')->eq('project')->andWhere('root')->in($projectIDList)->andWhere('root')->ne(0)->query();
  1974. $teamsGroup = array();
  1975. while($team = $stmt->fetch()) $teamsGroup[$team->root][$team->account] = $team->account;
  1976. /* Get white list group. */
  1977. $stmt = $this->dao->select('objectID,account')->from(TABLE_ACL)->where('objectType')->eq('project')->andWhere('objectID')->in($projectIDList)->query();
  1978. $whiteListGroup = array();
  1979. while($whiteList = $stmt->fetch()) $whiteListGroup[$whiteList->objectID][$whiteList->account] = $whiteList->account;
  1980. $stakeholderGroup = $this->loadModel('stakeholder')->getStakeholderGroup($projectIDList); // Get self stakeholders.
  1981. $parentStakeholderGroup = $this->stakeholder->getParentStakeholderGroup($projectIDList); // Get all parent program and subprogram relation.
  1982. $projectAdmins = $this->loadModel('group')->getAdmins($projectIDList, 'projects'); // Get projects's admins.
  1983. /* Get auth users. */
  1984. $authedUsers = $users;
  1985. /* 如果没传users参数,则获取项目关联的所有人。*/
  1986. if(empty($users)) $authedUsers += $this->getObjectsAuthedUsers($projects, 'project', $stakeholderGroup, $teamsGroup, $whiteListGroup, $projectAdmins, $parentStakeholderGroup, array());
  1987. /* Get all projects user view. */
  1988. $userViews = $this->dao->select("account,projects")->from(TABLE_USERVIEW)->where('account')->in($authedUsers)->fetchPairs('account', 'projects');
  1989. /* Judge auth and update view. */
  1990. foreach(array_filter($authedUsers) as $account)
  1991. {
  1992. $view = isset($userViews[$account]) ? $userViews[$account] : '';
  1993. $latestView = $view;
  1994. foreach($projects as $project)
  1995. {
  1996. $latestView = $this->getLatestUserView($account, $latestView, $project, 'project', $stakeholderGroup, $teamsGroup, $whiteListGroup, $projectAdmins, $parentStakeholderGroup, array());
  1997. }
  1998. if($view != $latestView)
  1999. {
  2000. if(!isset($userViews[$account]))
  2001. {
  2002. $userView = new stdclass();
  2003. $userView->account = $account;
  2004. $userView->projects = $latestView;
  2005. $userView->products = $userView->programs = $userView->sprints = '';
  2006. $this->dao->insert(TABLE_USERVIEW)->data($userView)->exec();
  2007. }
  2008. else
  2009. {
  2010. $this->dao->update(TABLE_USERVIEW)->set('projects')->eq($latestView)->where('account')->eq($account)->exec();
  2011. }
  2012. }
  2013. }
  2014. return true;
  2015. }
  2016. /**
  2017. * 更新产品下的用户访问视图。
  2018. * Update product user view.
  2019. *
  2020. * @param array $productIDList
  2021. * @param array $user
  2022. * @access private
  2023. * @return bool
  2024. * @param mixed[] $users
  2025. */
  2026. public function updateProductView($productIDList, $users)
  2027. {
  2028. $products = $this->dao->select('*')->from(TABLE_PRODUCT)->where('id')->in($productIDList)->andWhere('acl')->ne('open')->fetchAll('id', false);
  2029. if(empty($products)) return false;
  2030. list($teamsGroup, $stakeholderGroup) = $this->getProductMembers($products);
  2031. /* Get white list group. */
  2032. $stmt = $this->dao->select('objectID,account')->from(TABLE_ACL)->where('objectType')->eq('product')->andWhere('objectID')->in($productIDList)->query();
  2033. $whiteListGroup = array();
  2034. while($whiteList = $stmt->fetch()) $whiteListGroup[$whiteList->objectID][$whiteList->account] = $whiteList->account;
  2035. $productAdmins = $this->loadModel('group')->getAdmins($productIDList, 'products'); // Get products' admins.
  2036. /* Get auth users. */
  2037. $authedUsers = $users;
  2038. /* 如果没传users参数,则获取项目关联的所有人。*/
  2039. if(empty($users)) $authedUsers += $this->getObjectsAuthedUsers($products, 'product', $stakeholderGroup, $teamsGroup, $whiteListGroup, $productAdmins, array(), array());
  2040. /* Get all products user view. */
  2041. $userViews = $this->dao->select("account,products")->from(TABLE_USERVIEW)->where('account')->in($authedUsers)->fetchPairs('account', 'products');
  2042. /* Judge auth and update view. */
  2043. foreach(array_filter($authedUsers) as $account)
  2044. {
  2045. $view = isset($userViews[$account]) ? $userViews[$account] : '';
  2046. $latestView = $view;
  2047. foreach($products as $productID => $product)
  2048. {
  2049. $latestView = $this->getLatestUserView($account, $latestView, $product, 'product', $stakeholderGroup, $teamsGroup, $whiteListGroup, $productAdmins, array(), array());
  2050. }
  2051. if($view != $latestView)
  2052. {
  2053. if(!isset($userViews[$account]))
  2054. {
  2055. $userView = new stdclass();
  2056. $userView->account = $account;
  2057. $userView->products = $latestView;
  2058. $userView->projects = $userView->programs = $userView->sprints = '';
  2059. $this->dao->insert(TABLE_USERVIEW)->data($userView)->exec();
  2060. }
  2061. else
  2062. {
  2063. $this->dao->update(TABLE_USERVIEW)->set('products')->eq($latestView)->where('account')->eq($account)->exec();
  2064. }
  2065. }
  2066. }
  2067. return true;
  2068. }
  2069. /**
  2070. * 更新迭代下的用户访问视图。
  2071. * Update sprint view.
  2072. *
  2073. * @param array $sprintIDList
  2074. * @param array $users
  2075. * @access private
  2076. * @return bool
  2077. */
  2078. public function updateSprintView($sprintIDList, $users)
  2079. {
  2080. $sprints = $this->dao->select('*')->from(TABLE_PROJECT)->where('id')->in($sprintIDList)->andWhere('acl')->ne('open')->fetchAll('id');
  2081. if(empty($sprints)) return false;
  2082. $projectIDList = array();
  2083. foreach($sprints as $sprint) $projectIDList[$sprint->project] = $sprint->project;
  2084. $stmt = $this->dao->select('root,account')->from(TABLE_TEAM)->where('type')->in('project,execution')->andWhere('root')->in(array_merge($sprintIDList, $projectIDList))->andWhere('root')->ne(0)->query();
  2085. $teamsGroup = array();
  2086. while($team = $stmt->fetch()) $teamsGroup[$team->root][$team->account] = $team->account;
  2087. $stmt = $this->dao->select('objectID,account')->from(TABLE_ACL)->where('objectType')->eq('sprint')->andWhere('objectID')->in($sprintIDList)->query();
  2088. $whiteListGroup = array();
  2089. while($whiteList = $stmt->fetch()) $whiteListGroup[$whiteList->objectID][$whiteList->account] = $whiteList->account;
  2090. $stakeholderGroup = $this->loadModel('stakeholder')->getStakeholderGroup($projectIDList); // Get parent project stakeholders.
  2091. $executionAdmins = $this->loadModel('group')->getAdmins($sprintIDList, 'executions'); // Get executions' admins.
  2092. $authedUsers = $users;
  2093. if(empty($users)) $authedUsers += $this->getObjectsAuthedUsers($sprints, 'sprint', $stakeholderGroup, $teamsGroup, $whiteListGroup, $executionAdmins, array(), array());
  2094. $userViews = $this->dao->select("account,sprints")->from(TABLE_USERVIEW)->where('account')->in($authedUsers)->fetchPairs('account', 'sprints'); // Get all sprints user view.
  2095. foreach(array_filter($authedUsers) as $account)
  2096. {
  2097. $view = isset($userViews[$account]) ? $userViews[$account] : '';
  2098. $latestView = $view;
  2099. foreach($sprints as $sprint)
  2100. {
  2101. $latestView = $this->getLatestUserView($account, $latestView, $sprint, 'sprint', $stakeholderGroup, $teamsGroup, $whiteListGroup, $executionAdmins, array(), array());
  2102. }
  2103. if($view != $latestView)
  2104. {
  2105. if(!isset($userViews[$account]))
  2106. {
  2107. $userView = new stdclass();
  2108. $userView->account = $account;
  2109. $userView->sprints = $latestView;
  2110. $userView->projects = $userView->programs = $userView->products = '';
  2111. $this->dao->insert(TABLE_USERVIEW)->data($userView)->exec();
  2112. }
  2113. else
  2114. {
  2115. $this->dao->update(TABLE_USERVIEW)->set('sprints')->eq($latestView)->where('account')->eq($account)->exec();
  2116. }
  2117. }
  2118. }
  2119. return true;
  2120. }
  2121. /**
  2122. * 获取该对象的关联用户。
  2123. * Get objects authed users.
  2124. *
  2125. * @param array $objects
  2126. * @param string $objectType
  2127. * @param array $stakeholderGroup
  2128. * @param array $teamsGroup
  2129. * @param array $whiteListGroup
  2130. * @param array $adminsGroup
  2131. * @param array $parentStakeholderGroup
  2132. * @param array $parentPMGroup
  2133. * @access private
  2134. * @return array
  2135. */
  2136. private function getObjectsAuthedUsers($objects, $objectType, $stakeholderGroup, $teamsGroup, $whiteListGroup, $adminsGroup, $parentStakeholderGroup, $parentPMGroup)
  2137. {
  2138. $authedUsers = array();
  2139. foreach($objects as $object)
  2140. {
  2141. $stakeholders = zget($stakeholderGroup, $object->id, array());
  2142. $teams = zget($teamsGroup, $object->id, array());
  2143. $whiteList = zget($whiteListGroup, $object->id, array());
  2144. $admins = zget($adminsGroup, $object->id, array());
  2145. if($objectType == 'sprint') $parentTeams = zget($teamsGroup, $object->project, array());
  2146. if($objectType == 'program' && $object->acl == 'program')
  2147. {
  2148. $parents = explode(',', $object->path);
  2149. foreach($parents as $parentID)
  2150. {
  2151. $stakeholders += zget($parentStakeholderGroup, $parentID, array());
  2152. $stakeholders += zget($parentPMGroup, $parentID, array());
  2153. }
  2154. }
  2155. else if($objectType == 'project' && $object->acl == 'program')
  2156. {
  2157. $stakeholders += zget($parentStakeholderGroup, $object->id, array());
  2158. }
  2159. if($objectType == 'program') $authedUsers += $this->getProgramAuthedUsers($object, $stakeholders, $whiteList, $admins);
  2160. if($objectType == 'project') $authedUsers += $this->getProjectAuthedUsers($object, $stakeholders, $teams, $whiteList, $admins);
  2161. if($objectType == 'product') $authedUsers += $this->getProductViewListUsers($object, $teams, $stakeholders, $whiteList, $admins);
  2162. if($objectType == 'sprint') $authedUsers += $this->getProjectAuthedUsers($object, $stakeholders, array_merge($teams, $parentTeams), $whiteList, $admins);
  2163. /* If you have parent stage view permissions, you have child stage permissions. */
  2164. if($objectType == 'sprint' && $object->type == 'stage' && $object->grade == 2)
  2165. {
  2166. $parentStageAuthedUsers = $this->getParentStageAuthedUsers($object->parent);
  2167. $authedUsers = array_merge($authedUsers, $parentStageAuthedUsers);
  2168. }
  2169. }
  2170. return $authedUsers;
  2171. }
  2172. /**
  2173. * 获取用户对于该对象的最新访问权限。
  2174. * Get latest user view.
  2175. *
  2176. * @param string $account
  2177. * @param string $view
  2178. * @param object $object
  2179. * @param string $objectType
  2180. * @param array $stakeholderGroup
  2181. * @param array $teamsGroup
  2182. * @param array $whiteListGroup
  2183. * @param array $adminsGroup
  2184. * @param array $parentStakeholderGroup
  2185. * @param array $parentPMGroup
  2186. * @access private
  2187. * @return string
  2188. */
  2189. private function getLatestUserView($account, $view, $object, $objectType, $stakeholderGroup, $teamsGroup, $whiteListGroup, $adminsGroup, $parentStakeholderGroup, $parentPMGroup)
  2190. {
  2191. $stakeholders = zget($stakeholderGroup, $object->id, array());
  2192. $teams = zget($teamsGroup, $object->id, array());
  2193. $whiteList = zget($whiteListGroup, $object->id, array());
  2194. $admins = zget($adminsGroup, $object->id, array());
  2195. if(!empty($object->acl) && $object->acl == 'program')
  2196. {
  2197. $stakeholders += zget($parentStakeholderGroup, $object->id, array());
  2198. if($objectType == 'program')
  2199. {
  2200. $stakeholders += zget($parentPMGroup, $object->id, array());
  2201. }
  2202. }
  2203. $hasPriv = false;
  2204. if($objectType == 'program') $hasPriv = $this->checkProgramPriv($object, $account, $stakeholders, $whiteList, $admins);
  2205. if($objectType == 'project') $hasPriv = $this->checkProjectPriv($object, $account, $stakeholders, $teams, $whiteList, $admins);
  2206. if($objectType == 'product') $hasPriv = $this->checkProductPriv($object, $account, $teams, $stakeholders, $whiteList, $admins);
  2207. if($objectType == 'sprint') $hasPriv = $this->checkProjectPriv($object, $account, $stakeholders, $teams, $whiteList, $admins);
  2208. if($hasPriv && strpos(",{$view},", ",{$object->id},") === false) $view .= ",{$object->id}";
  2209. if(!$hasPriv && strpos(",{$view},", ",{$object->id},") !== false) $view = trim(str_replace(",{$object->id},", ',', ",{$view},"), ',');
  2210. return $view;
  2211. }
  2212. /**
  2213. * 检查用户是否有此项目集的查看权限。
  2214. * Check program priv.
  2215. *
  2216. * @param object $program
  2217. * @param string $account
  2218. * @param array $stakeholders
  2219. * @param array $whiteList
  2220. * @param array $admins
  2221. * @access private
  2222. * @return bool
  2223. */
  2224. private function checkProgramPriv($program, $account, $stakeholders = array(), $whiteList = array(), $admins = array())
  2225. {
  2226. /* 当前用户为管理员则判断为有权限。 */
  2227. if(strpos($this->app->company->admins, ',' . $account . ',') !== false) return true;
  2228. /* 当前用户为项目集的PM或创建者则判断为有权限。 */
  2229. if($program->PM == $account || $program->openedBy == $account) return true;
  2230. if($program->acl == 'open') return true; // 如果项目集为公开则判断为有权限。
  2231. if(isset($stakeholders[$account])) return true; // 如果该用户是项目集的干系人则判断为有权限。
  2232. if(isset($whiteList[$account])) return true; // 如果该用户是项目集的白名单成员则判断为有权限。
  2233. if(isset($admins[$account])) return true; // 如果该用户是项目集的管理人员则判断为有权限。
  2234. /* 如果是项目集内公开,则检查所有父项目集的权限。 */
  2235. if($program->parent != 0 && $program->acl == 'program')
  2236. {
  2237. $path = str_replace(",{$program->id},", ',', "{$program->path}");
  2238. $parents = $this->mao->select('openedBy,PM')->from(TABLE_PROGRAM)->where('id')->in($path)->fetchAll();
  2239. foreach($parents as $parent)
  2240. {
  2241. /* 当前用户是其中一个父项目集的PM或创建者则判断为有权限。 */
  2242. if($parent->PM == $account || $parent->openedBy == $account) return true;
  2243. }
  2244. }
  2245. return false;
  2246. }
  2247. /**
  2248. * 检查用户是否有此项目或者迭代的查看权限。
  2249. * Check project priv.
  2250. *
  2251. * @param object $project
  2252. * @param string $account
  2253. * @param array $stakeholders
  2254. * @param array $teams
  2255. * @param array $whiteList
  2256. * @param array $admins
  2257. * @access private
  2258. * @return bool
  2259. */
  2260. private function checkProjectPriv($project, $account, $stakeholders, $teams, $whiteList, $admins = array())
  2261. {
  2262. /* 当前用户为管理员则判断为有权限。 */
  2263. if(strpos($this->app->company->admins, ',' . $account . ',') !== false) return true;
  2264. /* 当前用户为项目集的PO、QD、RD、PM则判断为有权限。 */
  2265. if($project->PO == $account || $project->QD == $account || $project->RD == $account || $project->PM == $account) return true;
  2266. if($project->acl == 'open') return true; // 如果项目为公开则判断为有权限。
  2267. if(isset($stakeholders[$account])) return true; // 如果该用户是项目的干系人则判断为有权限。
  2268. if(isset($teams[$account])) return true; // 如果该用户是项目的团队成员则判断为有权限。
  2269. if(isset($whiteList[$account])) return true; // 如果该用户是项目的白名单成员则判断为有权限。
  2270. if(isset($admins[$account])) return true; // 如果该用户是项目的管理人员则判断为有权限。
  2271. /* 如果是项目类型并且项目集内公开,则检查所有父项目集的权限。 */
  2272. if($project->type == 'project' && $project->parent != 0 && $project->acl == 'program')
  2273. {
  2274. $path = str_replace(",{$project->id},", ',', "{$project->path}");
  2275. $programs = $this->mao->select('openedBy,PM')->from(TABLE_PROJECT)->where('id')->in($path)->fetchAll();
  2276. foreach($programs as $program)
  2277. {
  2278. /* 当前用户是其中一个父项目集的PM或创建者则判断为有权限。 */
  2279. if($program->PM == $account || $program->openedBy == $account) return true;
  2280. }
  2281. }
  2282. /* 如果是迭代并且是私有的,则检查所属项目的权限。 */
  2283. if(($project->type == 'sprint' || $project->type == 'stage' || $project->type == 'kanban') && $project->acl == 'private')
  2284. {
  2285. $project = $this->mao->select('openedBy,PM')->from(TABLE_PROJECT)->where('id')->eq($project->project)->fetch();
  2286. if(empty($project)) return false;
  2287. /* 当前用户是所属项目的PM或创建者则判断为有权限。 */
  2288. if($project->PM == $account || $project->openedBy == $account) return true;
  2289. }
  2290. return false;
  2291. }
  2292. /**
  2293. * 检查用户是否有此产品的查看权限。
  2294. * Check product priv.
  2295. *
  2296. * @param object $product
  2297. * @param string $account
  2298. * @param array $teams
  2299. * @param array $stakeholders
  2300. * @param array $whiteList
  2301. * @param array $admins
  2302. * @access private
  2303. * @return bool
  2304. */
  2305. private function checkProductPriv($product, $account, $teams, $stakeholders, $whiteList, $admins = array())
  2306. {
  2307. if(strpos($this->app->company->admins, ',' . $account . ',') !== false) return true; // 当前用户为管理员则判断为有权限。
  2308. if(strpos(",{$product->reviewer},", ',' . $account . ',') !== false) return true; // 当前用户为产品的审批人则判断为有权限。
  2309. if(strpos(",{$product->PMT},", ',' . $account . ',') !== false) return true; // 当前用户为产品的PMT则判断为有权限。
  2310. /* 当前产品为公开的则判断为有权限。 */
  2311. if($product->acl == 'open') return true;
  2312. /* 当前用户为产品的PO、QD、RD、创建者、反馈负责人、工单负责人则判断为有权限。 */
  2313. if($product->PO == $account || $product->QD == $account || $product->RD == $account || $product->createdBy == $account) return true;
  2314. if(isset($product->feedback) && $product->feedback == $account) return true;
  2315. if(isset($product->ticket) && $product->ticket == $account) return true;
  2316. if(isset($stakeholders[$account])) return true; // 如果该用户是产品的干系人则判断为有权限。
  2317. if(isset($teams[$account])) return true; // 如果该用户是产品的团队成员则判断为有权限。
  2318. if(isset($whiteList[$account])) return true; // 如果该用户是产品的白名单成员则判断为有权限。
  2319. if(isset($admins[$account])) return true; // 如果该用户是产品的管理人员则判断为有权限。
  2320. return false;
  2321. }
  2322. /**
  2323. * Get program authed users.
  2324. *
  2325. * @param object $program
  2326. * @param array $stakeholders
  2327. * @param array $whiteList
  2328. * @param array $admins
  2329. * @access private
  2330. * @return array
  2331. */
  2332. private function getProgramAuthedUsers($program, $stakeholders, $whiteList, $admins)
  2333. {
  2334. $users = array();
  2335. $users[$program->openedBy] = $program->openedBy;
  2336. $users[$program->PM] = $program->PM;
  2337. $users += $stakeholders ? $stakeholders : array();
  2338. $users += $whiteList ? $whiteList : array();
  2339. $users += $admins ? $admins : array();
  2340. $admins = explode(',', trim($this->app->company->admins, ','));
  2341. foreach($admins as $admin) $users[$admin] = $admin;
  2342. /* 如果是项目集内公开,则所有父项目集的PM和创建者都是关系人。 */
  2343. if($program->parent != 0 && $program->acl == 'program')
  2344. {
  2345. $path = str_replace(",{$program->id},", ',', "{$program->path}");
  2346. $parents = $this->mao->select('openedBy,PM')->from(TABLE_PROGRAM)->where('id')->in($path)->fetchAll();
  2347. foreach($parents as $parent)
  2348. {
  2349. $users[$parent->openedBy] = $parent->openedBy;
  2350. $users[$parent->PM] = $parent->PM;
  2351. }
  2352. }
  2353. return $users;
  2354. }
  2355. /**
  2356. * 获取和项目或者迭代相关联的用户。
  2357. * Get project authed users.
  2358. *
  2359. * @param object $project
  2360. * @param array $stakeholders
  2361. * @param array $teams
  2362. * @param array $whiteList
  2363. * @param array $admins
  2364. * @access private
  2365. * @return array
  2366. */
  2367. private function getProjectAuthedUsers($project, $stakeholders, $teams, $whiteList, $admins = array())
  2368. {
  2369. $users = array();
  2370. $users[$project->openedBy] = $project->openedBy;
  2371. $users[$project->PM] = $project->PM;
  2372. $users[$project->PO] = $project->PO;
  2373. $users[$project->QD] = $project->QD;
  2374. $users[$project->RD] = $project->RD;
  2375. $users += $stakeholders ? $stakeholders : array();
  2376. $users += $teams ? $teams : array();
  2377. $users += $whiteList ? $whiteList : array();
  2378. $users += $admins ? $admins : array();
  2379. $admins = explode(',', trim($this->app->company->admins, ','));
  2380. foreach($admins as $admin) $users[$admin] = $admin;
  2381. /* 如果是项目类型并且项目集内公开,则所有父项目集的PM和创建者都是关系人。 */
  2382. if($project->type == 'project' && $project->parent != 0 && $project->acl == 'program')
  2383. {
  2384. $path = str_replace(",{$project->id},", ',', "{$project->path}");
  2385. $programs = $this->mao->select('openedBy,PM')->from(TABLE_PROJECT)->where('id')->in($path)->fetchAll();
  2386. foreach($programs as $program)
  2387. {
  2388. $users[$program->openedBy] = $program->openedBy;
  2389. $users[$program->PM] = $program->PM;
  2390. }
  2391. }
  2392. /* 如果是迭代类型并且是私有的,则所属项目的PM和创建者是关系人。 */
  2393. if(($project->type == 'sprint' || $project->type == 'stage' || $project->type == 'kanban') && $project->acl == 'private')
  2394. {
  2395. $parent = $this->mao->select('openedBy,PM')->from(TABLE_PROJECT)->where('id')->eq($project->project)->fetch();
  2396. if($parent)
  2397. {
  2398. $users[$parent->openedBy] = $parent->openedBy;
  2399. $users[$parent->PM] = $parent->PM;
  2400. }
  2401. }
  2402. return $users;
  2403. }
  2404. /**
  2405. * 获取和产品相关联的用户。
  2406. * Get product view list users.
  2407. *
  2408. * @param object $product
  2409. * @param array $teams
  2410. * @param array $stakeholders
  2411. * @param array $whiteList
  2412. * @param array $admins
  2413. * @access public
  2414. * @return array
  2415. */
  2416. public function getProductViewListUsers($product, $teams = array(), $stakeholders = array(), $whiteList = array(), $admins = array())
  2417. {
  2418. $users = array();
  2419. $users[$product->PO] = $product->PO;
  2420. $users[$product->QD] = $product->QD;
  2421. $users[$product->RD] = $product->RD;
  2422. $users[$product->createdBy] = $product->createdBy;
  2423. if(isset($product->feedback)) $users[$product->feedback] = $product->feedback;
  2424. if(isset($product->ticket)) $users[$product->ticket] = $product->ticket;
  2425. foreach(explode(',', trim($this->app->company->admins, ',')) as $admin) $users[$admin] = $admin;
  2426. foreach(explode(',', trim(zget($product, 'reviewer', ''), ',')) as $account) $users[$account] = $account;
  2427. foreach(explode(',', trim(zget($product, 'PMT', ''), ',')) as $account) $users[$account] = $account;
  2428. if(!$teams || !$stakeholders)
  2429. {
  2430. list($productTeams, $productStakeholders) = $this->getProductMembers(array($product->id => $product));
  2431. if(!$teams) $teams = isset($productTeams[$product->id]) ? $productTeams[$product->id] : array();
  2432. if(!$stakeholders) $stakeholders = isset($productStakeholders[$product->id]) ? $productStakeholders[$product->id] : array();
  2433. }
  2434. if(!$whiteList) $whiteList = $this->dao->select('account')->from(TABLE_ACL)->where('objectType')->eq('product')->andWhere('objectID')->eq($product->id)->fetchPairs();
  2435. if(!$admins) $admins = $this->dao->select('account')->from(TABLE_PROJECTADMIN)->where("FIND_IN_SET({$product->id}, products)")->orWhere('products')->eq('all')->fetchPairs();
  2436. $users += $teams ? $teams : array();
  2437. $users += $stakeholders ? $stakeholders : array();
  2438. $users += $whiteList ? $whiteList : array();
  2439. $users += $admins ? $admins : array();
  2440. return $users;
  2441. }
  2442. /**
  2443. * 获取项目、执行等对象的团队成员。
  2444. * Get team members in object.
  2445. *
  2446. * @param string|array|int $objects
  2447. * @param string $type project|execution
  2448. * @param string $params
  2449. * @param string|array $usersToAppended
  2450. * @access public
  2451. * @return array
  2452. */
  2453. public function getTeamMemberPairs($objects, $type = 'project', $params = '', $usersToAppended = '')
  2454. {
  2455. if(commonModel::isTutorialMode()) return $this->loadModel('tutorial')->getTeamMembersPairs();
  2456. if(empty($objects) && empty($usersToAppended)) return array();
  2457. $keyField = strpos($params, 'useid') !== false ? 'id' : 'account';
  2458. $users = $this->dao->select("t2.id, t2.account, t2.realname")->from(TABLE_TEAM)->alias('t1')
  2459. ->leftJoin(TABLE_USER)->alias('t2')->on('t1.account = t2.account')
  2460. ->where('t1.type')->eq($type)
  2461. ->andWhere('t1.root')->in($objects)
  2462. ->beginIF($params == 'nodeleted' || empty($this->config->user->showDeleted))->andWhere('t2.deleted')->eq('0')->fi()
  2463. ->fetchAll($keyField);
  2464. if($usersToAppended) $users += $this->dao->select("id, account, realname")->from(TABLE_USER)->where('account')->in($usersToAppended)->fetchAll($keyField);
  2465. if(!$users) return array();
  2466. /* 拼装成用户名为键,真实姓名为值的数组。 */
  2467. foreach($users as $account => $user)
  2468. {
  2469. $firstLetter = ucfirst(substr($user->account, 0, 1)) . ':';
  2470. if(!empty($this->config->isINT)) $firstLetter = '';
  2471. $users[$account] = $firstLetter . ($user->realname ? $user->realname : $user->account);
  2472. }
  2473. /* Put the current user first. */
  2474. return $this->setCurrentUserFirst($users);
  2475. }
  2476. /**
  2477. * 判断一个按钮是否可以点击。
  2478. * Check if a button is clickable.
  2479. *
  2480. * @param object $user
  2481. * @param string $action
  2482. * @static
  2483. * @access public
  2484. * @return bool
  2485. */
  2486. public static function isClickable($user, $action)
  2487. {
  2488. global $config, $app;
  2489. $action = strtolower($action);
  2490. if($action == 'unbind' && empty($user->ranzhi)) return false;
  2491. if($action == 'unlock' && (time() - strtotime($user->locked)) >= $config->user->lockMinutes * 60) return false;
  2492. if($action == 'delete' && strpos($app->company->admins, ",{$user->account},") !== false) return false;
  2493. return true;
  2494. }
  2495. /**
  2496. * 保存一个编辑器模板。
  2497. * Save a editor template.
  2498. *
  2499. * @param object $template
  2500. * @access public
  2501. * @return bool
  2502. */
  2503. public function saveUserTemplate($template)
  2504. {
  2505. $this->dao->insert(TABLE_USERTPL)->data($template)
  2506. ->batchCheck('title, content', 'notempty')
  2507. ->check('title', 'unique', "`type`='{$template->type}' AND account='{$template->account}'")
  2508. ->autoCheck()
  2509. ->exec();
  2510. if(dao::isError()) return false;
  2511. $this->loadModel('score')->create('bug', 'saveTplModal', $this->dao->lastInsertID());
  2512. return !dao::isError();
  2513. }
  2514. /**
  2515. * Save old user template.
  2516. *
  2517. * @param string $type
  2518. * @access public
  2519. * @return void
  2520. */
  2521. public function saveOldUserTemplate($type)
  2522. {
  2523. $template = fixer::input('post')
  2524. ->setDefault('account', $this->app->user->account)
  2525. ->setDefault('type', $type)
  2526. ->stripTags('content', $this->config->allowedTags)
  2527. ->get();
  2528. $condition = "`type`='$type' and account='{$this->app->user->account}'";
  2529. $this->dao->insert(TABLE_USERTPL)->data($template)->batchCheck('title, content', 'notempty')->check('title', 'unique', $condition)->exec();
  2530. if(!dao::isError()) $this->loadModel('score')->create('bug', 'saveTplModal', $this->dao->lastInsertID());
  2531. }
  2532. /**
  2533. * 获取当前用户可以查看的模板列表。
  2534. * Get user templates.
  2535. *
  2536. * @param string $type
  2537. * @access public
  2538. * @return array
  2539. */
  2540. public function getUserTemplates($type)
  2541. {
  2542. return $this->dao->select('id, account, title, content, public')
  2543. ->from(TABLE_USERTPL)
  2544. ->where('type')->eq($type)
  2545. ->andwhere('account', true)->eq($this->app->user->account)
  2546. ->orWhere('public')->eq('1')
  2547. ->markRight(1)
  2548. ->orderBy('id')
  2549. ->fetchAll();
  2550. }
  2551. /**
  2552. * 为 GitLab API 获取用户列表。
  2553. * Get user list for GitLab API.
  2554. *
  2555. * @param array $accountList
  2556. * @access public
  2557. * @return array
  2558. */
  2559. public function getListForGitLabAPI($accountList)
  2560. {
  2561. /* 第二个参数设为空,确保返回的是一个索引数组。*/
  2562. /* Set the second param to empty, to make sure the return is an indexed array. */
  2563. $users = $this->getListByAccounts($accountList, '');
  2564. foreach($users as $user)
  2565. {
  2566. if($user->avatar)
  2567. {
  2568. $user->avatar = common::getSysURL() . $user->avatar;
  2569. continue;
  2570. }
  2571. $user->avatar = "https://www.gravatar.com/avatar/" . md5($user->account) . "?d=identicon&s=80";
  2572. }
  2573. return $users;
  2574. }
  2575. /**
  2576. * 获取可以创建需求的用户。
  2577. * Get users who have authority to create stories.
  2578. *
  2579. * @access public
  2580. * @return array
  2581. */
  2582. public function getCanCreateStoryUsers()
  2583. {
  2584. $users = $this->getPairs('noclosed|nodeleted');
  2585. $groupUsers = $this->dao->select('DISTINCT account')->from(TABLE_USERGROUP)->alias('t1')
  2586. ->leftJoin(TABLE_GROUPPRIV)->alias('t2')->on('t1.group = t2.group')
  2587. ->where('t2.module')->eq('story')
  2588. ->andWhere('t2.method')->in('create,batchCreate')
  2589. ->fetchPairs('account');
  2590. foreach($users as $account => $realname)
  2591. {
  2592. if($realname && (isset($groupUsers[$account]) || strpos($this->app->company->admins, ",{$account},") !== false)) continue;
  2593. unset($users[$account]);
  2594. }
  2595. return $users;
  2596. }
  2597. /**
  2598. * 把第一个超级管理员设置为当前用户。
  2599. * Set the first super admin as current user.
  2600. *
  2601. * @access public
  2602. * @return bool
  2603. */
  2604. public function su()
  2605. {
  2606. $company = $this->dao->select('admins')->from(TABLE_COMPANY)->fetch();
  2607. $admins = explode(',', trim($company->admins, ','));
  2608. if(empty($admins[0])) helper::end('No admin users.');
  2609. $this->app->user = $this->getById($admins[0]);
  2610. return true;
  2611. }
  2612. /**
  2613. * 把当前用户排到最前面。
  2614. * Put the current user first.
  2615. *
  2616. * @param array $users
  2617. * @access public
  2618. * @return array
  2619. */
  2620. public function setCurrentUserFirst($users)
  2621. {
  2622. $account = $this->app->user->account;
  2623. if(!$users || !$account || !isset($users[$account])) return $users;
  2624. return array($account => $users[$account]) + $users;
  2625. }
  2626. }