userrights.class.inc.php 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  1. <?php
  2. // Copyright (C) 2010-2017 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * User rights management API
  20. *
  21. * @copyright Copyright (C) 2010-2017 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class UserRightException extends CoreException
  25. {
  26. }
  27. define('UR_ALLOWED_NO', 0);
  28. define('UR_ALLOWED_YES', 1);
  29. define('UR_ALLOWED_DEPENDS', 2);
  30. define('UR_ACTION_READ', 1); // View an object
  31. define('UR_ACTION_MODIFY', 2); // Create/modify an object/attribute
  32. define('UR_ACTION_DELETE', 3); // Delete an object
  33. define('UR_ACTION_BULK_READ', 4); // Export multiple objects
  34. define('UR_ACTION_BULK_MODIFY', 5); // Create/modify multiple objects
  35. define('UR_ACTION_BULK_DELETE', 6); // Delete multiple objects
  36. define('UR_ACTION_CREATE', 7); // Instantiate an object
  37. define('UR_ACTION_APPLICATION_DEFINED', 10000); // Application specific actions (CSV import, View schema...)
  38. /**
  39. * User management module API
  40. *
  41. * @package iTopORM
  42. */
  43. abstract class UserRightsAddOnAPI
  44. {
  45. abstract public function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US'); // could be used during initial installation
  46. abstract public function Init(); // loads data (possible optimizations)
  47. // Used to build select queries showing only objects visible for the given user
  48. abstract public function GetSelectFilter($sLogin, $sClass, $aSettings = array()); // returns a filter object
  49. abstract public function IsActionAllowed($oUser, $sClass, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null);
  50. abstract public function IsStimulusAllowed($oUser, $sClass, $sStimulusCode, /*dbObjectSet*/ $oInstanceSet = null);
  51. abstract public function IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null);
  52. abstract public function IsAdministrator($oUser);
  53. abstract public function IsPortalUser($oUser);
  54. abstract public function FlushPrivileges();
  55. /**
  56. * Default behavior for addons that do not support profiles
  57. *
  58. * @param $oUser User
  59. * @return array
  60. */
  61. public function ListProfiles($oUser)
  62. {
  63. return array();
  64. }
  65. /**
  66. * ...
  67. */
  68. public function MakeSelectFilter($sClass, $aAllowedOrgs, $aSettings = array(), $sAttCode = null)
  69. {
  70. if ($sAttCode == null)
  71. {
  72. $sAttCode = $this->GetOwnerOrganizationAttCode($sClass);
  73. }
  74. if (empty($sAttCode))
  75. {
  76. return $oFilter = new DBObjectSearch($sClass);
  77. }
  78. $oExpression = new FieldExpression($sAttCode, $sClass);
  79. $oFilter = new DBObjectSearch($sClass);
  80. $oListExpr = ListExpression::FromScalars($aAllowedOrgs);
  81. $oCondition = new BinaryExpression($oExpression, 'IN', $oListExpr);
  82. $oFilter->AddConditionExpression($oCondition);
  83. if ($this->HasSharing())
  84. {
  85. if (($sAttCode == 'id') && isset($aSettings['bSearchMode']) && $aSettings['bSearchMode'])
  86. {
  87. // Querying organizations (or derived)
  88. // and the expected list of organizations will be used as a search criteria
  89. // Therefore the query can also return organization having objects shared with the allowed organizations
  90. //
  91. // 1) build the list of organizations sharing something with the allowed organizations
  92. // Organization <== sharing_org_id == SharedObject having org_id IN {user orgs}
  93. $oShareSearch = new DBObjectSearch('SharedObject');
  94. $oOrgField = new FieldExpression('org_id', 'SharedObject');
  95. $oShareSearch->AddConditionExpression(new BinaryExpression($oOrgField, 'IN', $oListExpr));
  96. $oSearchSharers = new DBObjectSearch('Organization');
  97. $oSearchSharers->AllowAllData();
  98. $oSearchSharers->AddCondition_ReferencedBy($oShareSearch, 'sharing_org_id');
  99. $aSharers = array();
  100. foreach($oSearchSharers->ToDataArray(array('id')) as $aRow)
  101. {
  102. $aSharers[] = $aRow['id'];
  103. }
  104. // 2) Enlarge the overall results: ... OR id IN(id1, id2, id3)
  105. if (count($aSharers) > 0)
  106. {
  107. $oSharersList = ListExpression::FromScalars($aSharers);
  108. $oFilter->MergeConditionExpression(new BinaryExpression($oExpression, 'IN', $oSharersList));
  109. }
  110. }
  111. $aShareProperties = SharedObject::GetSharedClassProperties($sClass);
  112. if ($aShareProperties)
  113. {
  114. $sShareClass = $aShareProperties['share_class'];
  115. $sShareAttCode = $aShareProperties['attcode'];
  116. $oSearchShares = new DBObjectSearch($sShareClass);
  117. $oSearchShares->AllowAllData();
  118. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass('Organization');
  119. $oOrgField = new FieldExpression('org_id', $sShareClass);
  120. $oSearchShares->AddConditionExpression(new BinaryExpression($oOrgField, 'IN', $oListExpr));
  121. $aShared = array();
  122. foreach($oSearchShares->ToDataArray(array($sShareAttCode)) as $aRow)
  123. {
  124. $aShared[] = $aRow[$sShareAttCode];
  125. }
  126. if (count($aShared) > 0)
  127. {
  128. $oObjId = new FieldExpression('id', $sClass);
  129. $oSharedIdList = ListExpression::FromScalars($aShared);
  130. $oFilter->MergeConditionExpression(new BinaryExpression($oObjId, 'IN', $oSharedIdList));
  131. }
  132. }
  133. } // if HasSharing
  134. return $oFilter;
  135. }
  136. }
  137. abstract class User extends cmdbAbstractObject
  138. {
  139. public static function Init()
  140. {
  141. $aParams = array
  142. (
  143. "category" => "core",
  144. "key_type" => "autoincrement",
  145. "name_attcode" => "login",
  146. "state_attcode" => "",
  147. "reconc_keys" => array(),
  148. "db_table" => "priv_user",
  149. "db_key_field" => "id",
  150. "db_finalclass_field" => "",
  151. "display_template" => "",
  152. );
  153. MetaModel::Init_Params($aParams);
  154. //MetaModel::Init_InheritAttributes();
  155. MetaModel::Init_AddAttribute(new AttributeExternalKey("contactid", array("targetclass"=>"Person", "allowed_values"=>null, "sql"=>"contactid", "is_null_allowed"=>true, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  156. MetaModel::Init_AddAttribute(new AttributeExternalField("last_name", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"name")));
  157. MetaModel::Init_AddAttribute(new AttributeExternalField("first_name", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"first_name")));
  158. MetaModel::Init_AddAttribute(new AttributeExternalField("email", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"email")));
  159. MetaModel::Init_AddAttribute(new AttributeString("login", array("allowed_values"=>null, "sql"=>"login", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  160. MetaModel::Init_AddAttribute(new AttributeApplicationLanguage("language", array("sql"=>"language", "default_value"=>"EN US", "is_null_allowed"=>false, "depends_on"=>array())));
  161. MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values" => new ValueSetEnum('enabled,disabled'), "sql"=>"status", "default_value"=>"enabled", "is_null_allowed"=>false, "depends_on"=>array())));
  162. MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("profile_list", array("linked_class"=>"URP_UserProfile", "ext_key_to_me"=>"userid", "ext_key_to_remote"=>"profileid", "allowed_values"=>null, "count_min"=>1, "count_max"=>0, "depends_on"=>array())));
  163. MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("allowed_org_list", array("linked_class"=>"URP_UserOrg", "ext_key_to_me"=>"userid", "ext_key_to_remote"=>"allowed_org_id", "allowed_values"=>null, "count_min"=>1, "count_max"=>0, "depends_on"=>array())));
  164. // Display lists
  165. MetaModel::Init_SetZListItems('details', array('contactid', 'first_name', 'email', 'login', 'language', 'status', 'profile_list', 'allowed_org_list')); // Attributes to be displayed for the complete details
  166. MetaModel::Init_SetZListItems('list', array('finalclass', 'first_name', 'last_name', 'login', 'status')); // Attributes to be displayed for a list
  167. // Search criteria
  168. MetaModel::Init_SetZListItems('standard_search', array('login', 'contactid', 'status')); // Criteria of the std search form
  169. MetaModel::Init_SetZListItems('advanced_search', array('login', 'contactid')); // Criteria of the advanced search form
  170. }
  171. abstract public function CheckCredentials($sPassword);
  172. abstract public function TrustWebServerContext();
  173. abstract public function CanChangePassword();
  174. abstract public function ChangePassword($sOldPassword, $sNewPassword);
  175. /*
  176. * Compute a name in best effort mode
  177. */
  178. public function GetFriendlyName()
  179. {
  180. if (!MetaModel::IsValidAttCode(get_class($this), 'contactid'))
  181. {
  182. return $this->Get('login');
  183. }
  184. if ($this->Get('contactid') != 0)
  185. {
  186. $sFirstName = $this->Get('first_name');
  187. $sLastName = $this->Get('last_name');
  188. $sEmail = $this->Get('email');
  189. if (strlen($sFirstName) > 0)
  190. {
  191. return "$sFirstName $sLastName";
  192. }
  193. elseif (strlen($sEmail) > 0)
  194. {
  195. return "$sLastName <$sEmail>";
  196. }
  197. else
  198. {
  199. return $sLastName;
  200. }
  201. }
  202. return $this->Get('login');
  203. }
  204. protected $oContactObject;
  205. /**
  206. * Fetch and memoize the associated contact (if any)
  207. */
  208. public function GetContactObject()
  209. {
  210. if (is_null($this->oContactObject))
  211. {
  212. if (MetaModel::IsValidAttCode(get_class($this), 'contactid') && ($this->Get('contactid') != 0))
  213. {
  214. $this->oContactObject = MetaModel::GetObject('Contact', $this->Get('contactid'));
  215. }
  216. }
  217. return $this->oContactObject;
  218. }
  219. /*
  220. * Overload the standard behavior
  221. */
  222. public function DoCheckToWrite()
  223. {
  224. parent::DoCheckToWrite();
  225. // Note: This MUST be factorized later: declare unique keys (set of columns) in the data model
  226. $aChanges = $this->ListChanges();
  227. if (array_key_exists('login', $aChanges))
  228. {
  229. if (strcasecmp($this->Get('login'), $this->GetOriginal('login')) !== 0)
  230. {
  231. $sNewLogin = $aChanges['login'];
  232. $oSearch = DBObjectSearch::FromOQL_AllData("SELECT User WHERE login = :newlogin");
  233. if (!$this->IsNew())
  234. {
  235. $oSearch->AddCondition('id', $this->GetKey(), '!=');
  236. }
  237. $oSet = new DBObjectSet($oSearch, array(), array('newlogin' => $sNewLogin));
  238. if ($oSet->Count() > 0)
  239. {
  240. $this->m_aCheckIssues[] = Dict::Format('Class:User/Error:LoginMustBeUnique', $sNewLogin);
  241. }
  242. }
  243. }
  244. // Check that this user has at least one profile assigned
  245. $oSet = $this->Get('profile_list');
  246. if ($oSet->Count() == 0)
  247. {
  248. $this->m_aCheckIssues[] = Dict::Format('Class:User/Error:AtLeastOneProfileIsNeeded');
  249. }
  250. }
  251. function GetGrantAsHtml($sClass, $iAction)
  252. {
  253. if (UserRights::IsActionAllowed($sClass, $iAction, null, $this))
  254. {
  255. return '<span style="background-color: #ddffdd;">'.Dict::S('UI:UserManagement:ActionAllowed:Yes').'</span>';
  256. }
  257. else
  258. {
  259. return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
  260. }
  261. }
  262. function DoShowGrantSumary($oPage, $sClassCategory)
  263. {
  264. if (UserRights::IsAdministrator($this))
  265. {
  266. // Looks dirty, but ok that's THE ONE
  267. $oPage->p(Dict::S('UI:UserManagement:AdminProfile+'));
  268. return;
  269. }
  270. $oKPI = new ExecutionKPI();
  271. $aDisplayData = array();
  272. foreach (MetaModel::GetClasses($sClassCategory) as $sClass)
  273. {
  274. $aClassStimuli = MetaModel::EnumStimuli($sClass);
  275. if (count($aClassStimuli) > 0)
  276. {
  277. $aStimuli = array();
  278. foreach ($aClassStimuli as $sStimulusCode => $oStimulus)
  279. {
  280. if (UserRights::IsStimulusAllowed($sClass, $sStimulusCode, null, $this))
  281. {
  282. $aStimuli[] = '<span title="'.$sStimulusCode.': '.htmlentities($oStimulus->GetDescription(), ENT_QUOTES, 'UTF-8').'">'.htmlentities($oStimulus->GetLabel(), ENT_QUOTES, 'UTF-8').'</span>';
  283. }
  284. }
  285. $sStimuli = implode(', ', $aStimuli);
  286. }
  287. else
  288. {
  289. $sStimuli = '<em title="'.Dict::S('UI:UserManagement:NoLifeCycleApplicable+').'">'.Dict::S('UI:UserManagement:NoLifeCycleApplicable').'</em>';
  290. }
  291. $aDisplayData[] = array(
  292. 'class' => MetaModel::GetName($sClass),
  293. 'read' => $this->GetGrantAsHtml($sClass, UR_ACTION_READ),
  294. 'bulkread' => $this->GetGrantAsHtml($sClass, UR_ACTION_BULK_READ),
  295. 'write' => $this->GetGrantAsHtml($sClass, UR_ACTION_MODIFY),
  296. 'bulkwrite' => $this->GetGrantAsHtml($sClass, UR_ACTION_BULK_MODIFY),
  297. 'stimuli' => $sStimuli,
  298. );
  299. }
  300. $oKPI->ComputeAndReport('Computation of user rights');
  301. $aDisplayConfig = array();
  302. $aDisplayConfig['class'] = array('label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+'));
  303. $aDisplayConfig['read'] = array('label' => Dict::S('UI:UserManagement:Action:Read'), 'description' => Dict::S('UI:UserManagement:Action:Read+'));
  304. $aDisplayConfig['bulkread'] = array('label' => Dict::S('UI:UserManagement:Action:BulkRead'), 'description' => Dict::S('UI:UserManagement:Action:BulkRead+'));
  305. $aDisplayConfig['write'] = array('label' => Dict::S('UI:UserManagement:Action:Modify'), 'description' => Dict::S('UI:UserManagement:Action:Modify+'));
  306. $aDisplayConfig['bulkwrite'] = array('label' => Dict::S('UI:UserManagement:Action:BulkModify'), 'description' => Dict::S('UI:UserManagement:Action:BulkModify+'));
  307. $aDisplayConfig['stimuli'] = array('label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+'));
  308. $oPage->table($aDisplayConfig, $aDisplayData);
  309. }
  310. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  311. {
  312. parent::DisplayBareRelations($oPage, $bEditMode);
  313. if (!$bEditMode)
  314. {
  315. $oPage->SetCurrentTab(Dict::S('UI:UserManagement:GrantMatrix'));
  316. $this->DoShowGrantSumary($oPage, 'bizmodel');
  317. // debug
  318. if (false)
  319. {
  320. $oPage->SetCurrentTab('More on user rigths (dev only)');
  321. $oPage->add("<h3>User rights</h3>\n");
  322. $this->DoShowGrantSumary($oPage, 'addon/userrights');
  323. $oPage->add("<h3>Change log</h3>\n");
  324. $this->DoShowGrantSumary($oPage, 'core/cmdb');
  325. $oPage->add("<h3>Application</h3>\n");
  326. $this->DoShowGrantSumary($oPage, 'application');
  327. $oPage->add("<h3>GUI</h3>\n");
  328. $this->DoShowGrantSumary($oPage, 'gui');
  329. }
  330. }
  331. }
  332. public function CheckToDelete(&$oDeletionPlan)
  333. {
  334. if (MetaModel::GetConfig()->Get('demo_mode'))
  335. {
  336. // Users deletion is NOT allowed in demo mode
  337. $oDeletionPlan->AddToDelete($this, null);
  338. $oDeletionPlan->SetDeletionIssues($this, array('deletion not allowed in demo mode.'), true);
  339. $oDeletionPlan->ComputeResults();
  340. return false;
  341. }
  342. return parent::CheckToDelete($oDeletionPlan);
  343. }
  344. protected function DBDeleteSingleObject()
  345. {
  346. if (MetaModel::GetConfig()->Get('demo_mode'))
  347. {
  348. // Users deletion is NOT allowed in demo mode
  349. return;
  350. }
  351. parent::DBDeleteSingleObject();
  352. }
  353. }
  354. /**
  355. * Abstract class for all types of "internal" authentication i.e. users
  356. * for which the application is supplied a login and a password opposed
  357. * to "external" users for whom the authentication is performed outside
  358. * of the application (by the web server for example).
  359. * Note that "internal" users do not necessary correspond to a local authentication
  360. * they may be authenticated by a remote system, like in authent-ldap.
  361. */
  362. abstract class UserInternal extends User
  363. {
  364. // Nothing special, just a base class to categorize this type of authenticated users
  365. public static function Init()
  366. {
  367. $aParams = array
  368. (
  369. "category" => "core",
  370. "key_type" => "autoincrement",
  371. "name_attcode" => "login",
  372. "state_attcode" => "",
  373. "reconc_keys" => array('login'),
  374. "db_table" => "priv_internaluser",
  375. "db_key_field" => "id",
  376. "db_finalclass_field" => "",
  377. );
  378. MetaModel::Init_Params($aParams);
  379. MetaModel::Init_InheritAttributes();
  380. // When set, this token allows for password reset
  381. MetaModel::Init_AddAttribute(new AttributeOneWayPassword("reset_pwd_token", array("allowed_values"=>null, "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  382. // Display lists
  383. MetaModel::Init_SetZListItems('details', array('contactid', 'first_name', 'email', 'login', 'status', 'language', 'profile_list', 'allowed_org_list')); // Attributes to be displayed for the complete details
  384. MetaModel::Init_SetZListItems('list', array('finalclass', 'first_name', 'last_name', 'login', 'status')); // Attributes to be displayed for a list
  385. // Search criteria
  386. MetaModel::Init_SetZListItems('standard_search', array('login', 'contactid', 'status')); // Criteria of the std search form
  387. MetaModel::Init_SetZListItems('advanced_search', array('login', 'contactid')); // Criteria of the advanced search form
  388. }
  389. /**
  390. * Use with care!
  391. */
  392. public function SetPassword($sNewPassword)
  393. {
  394. }
  395. /**
  396. * The email recipient is the person who is allowed to regain control when the password gets lost
  397. * Throws an exception if the feature cannot be available
  398. */
  399. public function GetResetPasswordEmail()
  400. {
  401. if (!MetaModel::IsValidAttCode(get_class($this), 'contactid'))
  402. {
  403. throw new Exception(Dict::S('UI:ResetPwd-Error-NoContact'));
  404. }
  405. $iContactId = $this->Get('contactid');
  406. if ($iContactId == 0)
  407. {
  408. throw new Exception(Dict::S('UI:ResetPwd-Error-NoContact'));
  409. }
  410. $oContact = MetaModel::GetObject('Contact', $iContactId);
  411. // Determine the email attribute (the first one will be our choice)
  412. foreach (MetaModel::ListAttributeDefs(get_class($oContact)) as $sAttCode => $oAttDef)
  413. {
  414. if ($oAttDef instanceof AttributeEmailAddress)
  415. {
  416. $sEmailAttCode = $sAttCode;
  417. // we've got one, exit the loop
  418. break;
  419. }
  420. }
  421. if (!isset($sEmailAttCode))
  422. {
  423. throw new Exception(Dict::S('UI:ResetPwd-Error-NoEmailAtt'));
  424. }
  425. $sRes = trim($oContact->Get($sEmailAttCode));
  426. return $sRes;
  427. }
  428. }
  429. /**
  430. * Self register extension
  431. *
  432. * @package iTopORM
  433. */
  434. interface iSelfRegister
  435. {
  436. /**
  437. * Called when no user is found in iTop for the corresponding 'name'. This method
  438. * can create/synchronize the User in iTop with an external source (such as AD/LDAP) on the fly
  439. * @param string $sName The typed-in user name
  440. * @param string $sPassword The typed-in password
  441. * @param string $sLoginMode The login method used (cas|form|basic|url)
  442. * @param string $sAuthentication The authentication method used (any|internal|external)
  443. * @return bool true if the user is a valid one, false otherwise
  444. */
  445. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication);
  446. /**
  447. * Called after the user has been authenticated and found in iTop. This method can
  448. * Update the user's definition on the fly (profiles...) to keep it in sync with an external source
  449. * @param User $oUser The user to update/synchronize
  450. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  451. * @param string $sAuthentication The authentication method used
  452. * @return void
  453. */
  454. public static function UpdateUser(User $oUser, $sLoginMode, $sAuthentication);
  455. }
  456. /**
  457. * User management core API
  458. *
  459. * @package iTopORM
  460. */
  461. class UserRights
  462. {
  463. protected static $m_oAddOn;
  464. protected static $m_oUser;
  465. protected static $m_oRealUser;
  466. protected static $m_sSelfRegisterAddOn = null;
  467. public static function SelectModule($sModuleName)
  468. {
  469. if (!class_exists($sModuleName))
  470. {
  471. throw new CoreException("Could not select this module, '$sModuleName' in not a valid class name");
  472. return;
  473. }
  474. if (!is_subclass_of($sModuleName, 'UserRightsAddOnAPI'))
  475. {
  476. throw new CoreException("Could not select this module, the class '$sModuleName' is not derived from UserRightsAddOnAPI");
  477. return;
  478. }
  479. self::$m_oAddOn = new $sModuleName;
  480. self::$m_oAddOn->Init();
  481. self::$m_oUser = null;
  482. self::$m_oRealUser = null;
  483. }
  484. public static function SelectSelfRegister($sModuleName)
  485. {
  486. if (!class_exists($sModuleName))
  487. {
  488. throw new CoreException("Could not select the class, '$sModuleName' for self register, is not a valid class name");
  489. }
  490. self::$m_sSelfRegisterAddOn = $sModuleName;
  491. }
  492. public static function GetModuleInstance()
  493. {
  494. return self::$m_oAddOn;
  495. }
  496. // Installation: create the very first user
  497. public static function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US')
  498. {
  499. $bRes = self::$m_oAddOn->CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage);
  500. self::FlushPrivileges(true /* reset admin cache */);
  501. return $bRes;
  502. }
  503. protected static function IsLoggedIn()
  504. {
  505. if (self::$m_oUser == null)
  506. {
  507. return false;
  508. }
  509. else
  510. {
  511. return true;
  512. }
  513. }
  514. public static function Login($sName, $sAuthentication = 'any')
  515. {
  516. $oUser = self::FindUser($sName, $sAuthentication);
  517. if (is_null($oUser))
  518. {
  519. return false;
  520. }
  521. self::$m_oUser = $oUser;
  522. if (isset($_SESSION['impersonate_user']))
  523. {
  524. self::$m_oRealUser = self::$m_oUser;
  525. self::$m_oUser = self::FindUser($_SESSION['impersonate_user']);
  526. }
  527. Dict::SetUserLanguage(self::GetUserLanguage());
  528. return true;
  529. }
  530. public static function CheckCredentials($sName, $sPassword, $sLoginMode = 'form', $sAuthentication = 'any')
  531. {
  532. $oUser = self::FindUser($sName, $sAuthentication);
  533. if (is_null($oUser))
  534. {
  535. // Check if the user does not exist at all or if it is just disabled
  536. if (self::FindUser($sName, $sAuthentication, true) == null)
  537. {
  538. // User does not exist at all
  539. return self::CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication);
  540. }
  541. else
  542. {
  543. // User is actually disabled
  544. return false;
  545. }
  546. }
  547. if (!$oUser->CheckCredentials($sPassword))
  548. {
  549. return false;
  550. }
  551. self::UpdateUser($oUser, $sLoginMode, $sAuthentication);
  552. return true;
  553. }
  554. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication)
  555. {
  556. if (self::$m_sSelfRegisterAddOn != null)
  557. {
  558. return call_user_func(array(self::$m_sSelfRegisterAddOn, 'CheckCredentialsAndCreateUser'), $sName, $sPassword, $sLoginMode, $sAuthentication);
  559. }
  560. }
  561. public static function UpdateUser($oUser, $sLoginMode, $sAuthentication)
  562. {
  563. if (self::$m_sSelfRegisterAddOn != null)
  564. {
  565. call_user_func(array(self::$m_sSelfRegisterAddOn, 'UpdateUser'), $oUser, $sLoginMode, $sAuthentication);
  566. }
  567. }
  568. public static function TrustWebServerContext()
  569. {
  570. if (!is_null(self::$m_oUser))
  571. {
  572. return self::$m_oUser->TrustWebServerContext();
  573. }
  574. else
  575. {
  576. return false;
  577. }
  578. }
  579. /**
  580. * Tells whether or not the archive mode is allowed to the current user
  581. * @return boolean
  582. */
  583. static function CanBrowseArchive()
  584. {
  585. if (is_null(self::$m_oUser))
  586. {
  587. $bRet = false;
  588. }
  589. elseif (isset($_SESSION['archive_allowed']))
  590. {
  591. $bRet = $_SESSION['archive_allowed'];
  592. }
  593. else
  594. {
  595. // As of now, anybody can switch to the archive mode as soon as there is an archivable class
  596. $bRet = (count(MetaModel::EnumArchivableClasses()) > 0);
  597. $_SESSION['archive_allowed'] = $bRet;
  598. }
  599. return $bRet;
  600. }
  601. public static function CanChangePassword()
  602. {
  603. if (MetaModel::DBIsReadOnly())
  604. {
  605. return false;
  606. }
  607. if (!is_null(self::$m_oUser))
  608. {
  609. return self::$m_oUser->CanChangePassword();
  610. }
  611. else
  612. {
  613. return false;
  614. }
  615. }
  616. public static function ChangePassword($sOldPassword, $sNewPassword, $sName = '')
  617. {
  618. if (empty($sName))
  619. {
  620. $oUser = self::$m_oUser;
  621. }
  622. else
  623. {
  624. // find the id out of the login string
  625. $oUser = self::FindUser($sName);
  626. }
  627. if (is_null($oUser))
  628. {
  629. return false;
  630. }
  631. else
  632. {
  633. return $oUser->ChangePassword($sOldPassword, $sNewPassword);
  634. }
  635. }
  636. /**
  637. * @param string $sName Login identifier of the user to impersonate
  638. * @return bool True if an impersonation occurred
  639. */
  640. public static function Impersonate($sName)
  641. {
  642. if (!self::CheckLogin()) return false;
  643. $bRet = false;
  644. $oUser = self::FindUser($sName);
  645. if ($oUser)
  646. {
  647. $bRet = true;
  648. if (is_null(self::$m_oRealUser))
  649. {
  650. // First impersonation
  651. self::$m_oRealUser = self::$m_oUser;
  652. }
  653. if (self::$m_oRealUser && (self::$m_oRealUser->GetKey() == $oUser->GetKey()))
  654. {
  655. // Equivalent to "Deimpersonate"
  656. self::Deimpersonate();
  657. }
  658. else
  659. {
  660. // Do impersonate!
  661. self::$m_oUser = $oUser;
  662. Dict::SetUserLanguage(self::GetUserLanguage());
  663. $_SESSION['impersonate_user'] = $sName;
  664. self::_ResetSessionCache();
  665. }
  666. }
  667. return $bRet;
  668. }
  669. public static function Deimpersonate()
  670. {
  671. if (!is_null(self::$m_oRealUser))
  672. {
  673. self::$m_oUser = self::$m_oRealUser;
  674. Dict::SetUserLanguage(self::GetUserLanguage());
  675. unset($_SESSION['impersonate_user']);
  676. self::_ResetSessionCache();
  677. }
  678. }
  679. public static function GetUser()
  680. {
  681. if (is_null(self::$m_oUser))
  682. {
  683. return '';
  684. }
  685. else
  686. {
  687. return self::$m_oUser->Get('login');
  688. }
  689. }
  690. public static function GetUserObject()
  691. {
  692. if (is_null(self::$m_oUser))
  693. {
  694. return null;
  695. }
  696. else
  697. {
  698. return self::$m_oUser;
  699. }
  700. }
  701. public static function GetUserLanguage()
  702. {
  703. if (is_null(self::$m_oUser))
  704. {
  705. return 'EN US';
  706. }
  707. else
  708. {
  709. return self::$m_oUser->Get('language');
  710. }
  711. }
  712. public static function GetUserId($sName = '')
  713. {
  714. if (empty($sName))
  715. {
  716. // return current user id
  717. if (is_null(self::$m_oUser))
  718. {
  719. return null;
  720. }
  721. return self::$m_oUser->GetKey();
  722. }
  723. else
  724. {
  725. // find the id out of the login string
  726. $oUser = self::$m_oAddOn->FindUser($sName);
  727. if (is_null($oUser))
  728. {
  729. return null;
  730. }
  731. return $oUser->GetKey();
  732. }
  733. }
  734. public static function GetContactId($sName = '')
  735. {
  736. if (empty($sName))
  737. {
  738. $oUser = self::$m_oUser;
  739. }
  740. else
  741. {
  742. $oUser = FindUser($sName);
  743. }
  744. if (is_null($oUser))
  745. {
  746. return '';
  747. }
  748. if (!MetaModel::IsValidAttCode(get_class($oUser), 'contactid'))
  749. {
  750. return '';
  751. }
  752. return $oUser->Get('contactid');
  753. }
  754. public static function GetContactObject()
  755. {
  756. if (is_null(self::$m_oUser))
  757. {
  758. return null;
  759. }
  760. else
  761. {
  762. return self::$m_oUser->GetContactObject();
  763. }
  764. }
  765. // Render the user name in best effort mode
  766. public static function GetUserFriendlyName($sName = '')
  767. {
  768. if (empty($sName))
  769. {
  770. $oUser = self::$m_oUser;
  771. }
  772. else
  773. {
  774. $oUser = FindUser($sName);
  775. }
  776. if (is_null($oUser))
  777. {
  778. return '';
  779. }
  780. return $oUser->GetFriendlyName();
  781. }
  782. public static function IsImpersonated()
  783. {
  784. if (is_null(self::$m_oRealUser))
  785. {
  786. return false;
  787. }
  788. return true;
  789. }
  790. public static function GetRealUser()
  791. {
  792. if (is_null(self::$m_oRealUser))
  793. {
  794. return '';
  795. }
  796. return self::$m_oRealUser->Get('login');
  797. }
  798. public static function GetRealUserObject()
  799. {
  800. return self::$m_oRealUser;
  801. }
  802. public static function GetRealUserId()
  803. {
  804. if (is_null(self::$m_oRealUser))
  805. {
  806. return '';
  807. }
  808. return self::$m_oRealUser->GetKey();
  809. }
  810. public static function GetRealUserFriendlyName()
  811. {
  812. if (is_null(self::$m_oRealUser))
  813. {
  814. return '';
  815. }
  816. return self::$m_oRealUser->GetFriendlyName();
  817. }
  818. protected static function CheckLogin()
  819. {
  820. if (!self::IsLoggedIn())
  821. {
  822. //throw new UserRightException('No user logged in', array());
  823. return false;
  824. }
  825. return true;
  826. }
  827. public static function GetSelectFilter($sClass, $aSettings = array())
  828. {
  829. // When initializing, we need to let everything pass trough
  830. if (!self::CheckLogin()) return true;
  831. if (self::IsAdministrator()) return true;
  832. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  833. {
  834. return self::$m_oAddOn->GetSelectFilter(self::$m_oUser, $sClass, $aSettings);
  835. }
  836. else
  837. {
  838. return true;
  839. }
  840. }
  841. public static function IsActionAllowed($sClass, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  842. {
  843. // When initializing, we need to let everything pass trough
  844. if (!self::CheckLogin()) return true;
  845. if (MetaModel::DBIsReadOnly())
  846. {
  847. if ($iActionCode == UR_ACTION_CREATE) return false;
  848. if ($iActionCode == UR_ACTION_MODIFY) return false;
  849. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  850. if ($iActionCode == UR_ACTION_DELETE) return false;
  851. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  852. }
  853. $aPredefinedObjects = call_user_func(array($sClass, 'GetPredefinedObjects'));
  854. if ($aPredefinedObjects != null)
  855. {
  856. // As opposed to the read-only DB, modifying an object is allowed
  857. // (the constant columns will be marked as read-only)
  858. //
  859. if ($iActionCode == UR_ACTION_CREATE) return false;
  860. if ($iActionCode == UR_ACTION_DELETE) return false;
  861. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  862. }
  863. if (self::IsAdministrator($oUser)) return true;
  864. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  865. {
  866. if (is_null($oUser))
  867. {
  868. $oUser = self::$m_oUser;
  869. }
  870. if ($iActionCode == UR_ACTION_CREATE)
  871. {
  872. // The addons currently DO NOT handle the case "CREATE"
  873. // Therefore it is considered to be equivalent to "MODIFY"
  874. $iActionCode = UR_ACTION_MODIFY;
  875. }
  876. return self::$m_oAddOn->IsActionAllowed($oUser, $sClass, $iActionCode, $oInstanceSet);
  877. }
  878. elseif(($iActionCode == UR_ACTION_READ) && MetaModel::HasCategory($sClass, 'view_in_gui'))
  879. {
  880. return true;
  881. }
  882. else
  883. {
  884. // Other classes could be edited/listed by the administrators
  885. return false;
  886. }
  887. }
  888. public static function IsStimulusAllowed($sClass, $sStimulusCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  889. {
  890. // When initializing, we need to let everything pass trough
  891. if (!self::CheckLogin()) return true;
  892. if (MetaModel::DBIsReadOnly())
  893. {
  894. return false;
  895. }
  896. if (self::IsAdministrator($oUser)) return true;
  897. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  898. {
  899. if (is_null($oUser))
  900. {
  901. $oUser = self::$m_oUser;
  902. }
  903. return self::$m_oAddOn->IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet);
  904. }
  905. else
  906. {
  907. // Other classes could be edited/listed by the administrators
  908. return false;
  909. }
  910. }
  911. public static function IsActionAllowedOnAttribute($sClass, $sAttCode, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  912. {
  913. // When initializing, we need to let everything pass trough
  914. if (!self::CheckLogin()) return true;
  915. if (MetaModel::DBIsReadOnly())
  916. {
  917. if ($iActionCode == UR_ACTION_MODIFY) return false;
  918. if ($iActionCode == UR_ACTION_DELETE) return false;
  919. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  920. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  921. }
  922. if (self::IsAdministrator($oUser)) return true;
  923. // this module is forbidden for non admins
  924. if (MetaModel::HasCategory($sClass, 'addon/userrights')) return false;
  925. // the rest is allowed (#@# to be improved)
  926. if (!MetaModel::HasCategory($sClass, 'bizmodel')) return true;
  927. if (is_null($oUser))
  928. {
  929. $oUser = self::$m_oUser;
  930. }
  931. return self::$m_oAddOn->IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, $oInstanceSet);
  932. }
  933. protected static $m_aAdmins = array();
  934. public static function IsAdministrator($oUser = null)
  935. {
  936. if (!self::CheckLogin()) return false;
  937. if (is_null($oUser))
  938. {
  939. $oUser = self::$m_oUser;
  940. }
  941. $iUser = $oUser->GetKey();
  942. if (!isset(self::$m_aAdmins[$iUser]))
  943. {
  944. self::$m_aAdmins[$iUser] = self::$m_oAddOn->IsAdministrator($oUser);
  945. }
  946. return self::$m_aAdmins[$iUser];
  947. }
  948. protected static $m_aPortalUsers = array();
  949. public static function IsPortalUser($oUser = null)
  950. {
  951. if (!self::CheckLogin()) return false;
  952. if (is_null($oUser))
  953. {
  954. $oUser = self::$m_oUser;
  955. }
  956. $iUser = $oUser->GetKey();
  957. if (!isset(self::$m_aPortalUsers[$iUser]))
  958. {
  959. self::$m_aPortalUsers[$iUser] = self::$m_oAddOn->IsPortalUser($oUser);
  960. }
  961. return self::$m_aPortalUsers[$iUser];
  962. }
  963. public static function GetAllowedPortals()
  964. {
  965. $aAllowedPortals = array();
  966. $aPortalsConf = PortalDispatcherData::GetData();
  967. $aDispatchers = array();
  968. foreach ($aPortalsConf as $sPortalId => $aConf)
  969. {
  970. $sHandlerClass = $aConf['handler'];
  971. $aDispatchers[$sPortalId] = new $sHandlerClass($sPortalId);
  972. }
  973. foreach ($aDispatchers as $sPortalId => $oDispatcher)
  974. {
  975. if ($oDispatcher->IsUserAllowed())
  976. {
  977. $aAllowedPortals[] = array(
  978. 'id' => $sPortalId,
  979. 'label' => $oDispatcher->GetLabel(),
  980. 'url' => $oDispatcher->GetUrl(),
  981. );
  982. }
  983. }
  984. return $aAllowedPortals;
  985. }
  986. public static function ListProfiles($oUser = null)
  987. {
  988. if (is_null($oUser))
  989. {
  990. $oUser = self::$m_oUser;
  991. }
  992. if ($oUser === null)
  993. {
  994. // Not logged in: no profile at all
  995. $aProfiles = array();
  996. }
  997. elseif ((self::$m_oUser !== null) && ($oUser->GetKey() == self::$m_oUser->GetKey()))
  998. {
  999. // Data about the current user can be found into the session data
  1000. if (array_key_exists('profile_list', $_SESSION))
  1001. {
  1002. $aProfiles = $_SESSION['profile_list'];
  1003. }
  1004. }
  1005. if (!isset($aProfiles))
  1006. {
  1007. $aProfiles = self::$m_oAddOn->ListProfiles($oUser);
  1008. }
  1009. return $aProfiles;
  1010. }
  1011. /**
  1012. * @param $sProfileName Profile name to search for
  1013. * @param $oUser User|null
  1014. * @return bool
  1015. */
  1016. public static function HasProfile($sProfileName, $oUser = null)
  1017. {
  1018. $bRet = in_array($sProfileName, self::ListProfiles($oUser));
  1019. return $bRet;
  1020. }
  1021. /**
  1022. * Reset cached data
  1023. * @param Bool Reset admin cache as well
  1024. * @return void
  1025. */
  1026. // Reset cached data
  1027. //
  1028. public static function FlushPrivileges($bResetAdminCache = false)
  1029. {
  1030. if ($bResetAdminCache)
  1031. {
  1032. self::$m_aAdmins = array();
  1033. self::$m_aPortalUsers = array();
  1034. }
  1035. if (!isset($_SESSION))
  1036. {
  1037. session_name('itop-'.md5(APPROOT));
  1038. session_start();
  1039. }
  1040. self::_ResetSessionCache();
  1041. if (self::$m_oAddOn)
  1042. {
  1043. self::$m_oAddOn->FlushPrivileges();
  1044. }
  1045. }
  1046. static $m_aCacheUsers;
  1047. /**
  1048. * Find a user based on its login and its type of authentication
  1049. * @param string $sLogin Login/identifier of the user
  1050. * @param string $sAuthentication Type of authentication used: internal|external|any
  1051. * @param bool $bAllowDisabledUsers Whether or not to retrieve disabled users (status != enabled)
  1052. * @return User The found user or null
  1053. */
  1054. protected static function FindUser($sLogin, $sAuthentication = 'any', $bAllowDisabledUsers = false)
  1055. {
  1056. if ($sAuthentication == 'any')
  1057. {
  1058. $oUser = self::FindUser($sLogin, 'internal');
  1059. if ($oUser == null)
  1060. {
  1061. $oUser = self::FindUser($sLogin, 'external');
  1062. }
  1063. }
  1064. else
  1065. {
  1066. if (!isset(self::$m_aCacheUsers))
  1067. {
  1068. self::$m_aCacheUsers = array('internal' => array(), 'external' => array());
  1069. }
  1070. if (!isset(self::$m_aCacheUsers[$sAuthentication][$sLogin]))
  1071. {
  1072. switch($sAuthentication)
  1073. {
  1074. case 'external':
  1075. $sBaseClass = 'UserExternal';
  1076. break;
  1077. case 'internal':
  1078. $sBaseClass = 'UserInternal';
  1079. break;
  1080. default:
  1081. echo "<p>sAuthentication = $sAuthentication</p>\n";
  1082. assert(false); // should never happen
  1083. }
  1084. $oSearch = DBObjectSearch::FromOQL("SELECT $sBaseClass WHERE login = :login");
  1085. if (!$bAllowDisabledUsers)
  1086. {
  1087. $oSearch->AddCondition('status', 'enabled');
  1088. }
  1089. $oSet = new DBObjectSet($oSearch, array(), array('login' => $sLogin));
  1090. $oUser = $oSet->fetch();
  1091. self::$m_aCacheUsers[$sAuthentication][$sLogin] = $oUser;
  1092. }
  1093. $oUser = self::$m_aCacheUsers[$sAuthentication][$sLogin];
  1094. }
  1095. return $oUser;
  1096. }
  1097. public static function MakeSelectFilter($sClass, $aAllowedOrgs, $aSettings = array(), $sAttCode = null)
  1098. {
  1099. return self::$m_oAddOn->MakeSelectFilter($sClass, $aAllowedOrgs, $aSettings, $sAttCode);
  1100. }
  1101. public static function _InitSessionCache()
  1102. {
  1103. // Cache data about the current user into the session
  1104. if (isset($_SESSION))
  1105. {
  1106. $_SESSION['profile_list'] = self::ListProfiles();
  1107. }
  1108. }
  1109. public static function _ResetSessionCache()
  1110. {
  1111. if (isset($_SESSION['profile_list']))
  1112. {
  1113. unset($_SESSION['profile_list']);
  1114. }
  1115. if (isset($_SESSION['archive_allowed']))
  1116. {
  1117. unset($_SESSION['archive_allowed']);
  1118. }
  1119. }
  1120. }
  1121. /**
  1122. * Helper class to get the number/list of items for which a given action is allowed/possible
  1123. */
  1124. class ActionChecker
  1125. {
  1126. var $oFilter;
  1127. var $iActionCode;
  1128. var $iAllowedCount = null;
  1129. var $aAllowedIDs = null;
  1130. public function __construct(DBSearch $oFilter, $iActionCode)
  1131. {
  1132. $this->oFilter = $oFilter;
  1133. $this->iActionCode = $iActionCode;
  1134. $this->iAllowedCount = null;
  1135. $this->aAllowedIDs = null;
  1136. }
  1137. /**
  1138. * returns the number of objects for which the action is allowed
  1139. * @return integer The number of "allowed" objects 0..N
  1140. */
  1141. public function GetAllowedCount()
  1142. {
  1143. if ($this->iAllowedCount == null) $this->CheckObjects();
  1144. return $this->iAllowedCount;
  1145. }
  1146. /**
  1147. * If IsAllowed returned UR_ALLOWED_DEPENDS, this methods returns
  1148. * an array of ObjKey => Status (true|false)
  1149. * @return array
  1150. */
  1151. public function GetAllowedIDs()
  1152. {
  1153. if ($this->aAllowedIDs == null) $this->IsAllowed();
  1154. return $this->aAllowedIDs;
  1155. }
  1156. /**
  1157. * Check if the speficied stimulus is allowed for the set of objects
  1158. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  1159. */
  1160. public function IsAllowed()
  1161. {
  1162. $sClass = $this->oFilter->GetClass();
  1163. $oSet = new DBObjectSet($this->oFilter);
  1164. $iActionAllowed = UserRights::IsActionAllowed($sClass, $this->iActionCode, $oSet);
  1165. if ($iActionAllowed == UR_ALLOWED_DEPENDS)
  1166. {
  1167. // Check for each object if the action is allowed or not
  1168. $this->aAllowedIDs = array();
  1169. $oSet->Rewind();
  1170. $this->iAllowedCount = 0;
  1171. while($oObj = $oSet->Fetch())
  1172. {
  1173. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  1174. if (UserRights::IsActionAllowed($sClass, $this->iActionCode, $oObjSet) == UR_ALLOWED_NO)
  1175. {
  1176. $this->aAllowedIDs[$oObj->GetKey()] = false;
  1177. }
  1178. else
  1179. {
  1180. // Assume UR_ALLOWED_YES, since there is just one object !
  1181. $this->aAllowedIDs[$oObj->GetKey()] = true;
  1182. $this->iAllowedCount++;
  1183. }
  1184. }
  1185. }
  1186. else if ($iActionAllowed == UR_ALLOWED_YES)
  1187. {
  1188. $this->iAllowedCount = $oSet->Count();
  1189. $this->aAllowedIDs = array(); // Optimization: not filled when Ok for all objects
  1190. }
  1191. else // UR_ALLOWED_NO
  1192. {
  1193. $this->iAllowedCount = 0;
  1194. $this->aAllowedIDs = array();
  1195. }
  1196. return $iActionAllowed;
  1197. }
  1198. }
  1199. /**
  1200. * Helper class to get the number/list of items for which a given stimulus can be applied (allowed & possible)
  1201. */
  1202. class StimulusChecker extends ActionChecker
  1203. {
  1204. var $sState = null;
  1205. public function __construct(DBSearch $oFilter, $sState, $iStimulusCode)
  1206. {
  1207. parent::__construct($oFilter, $iStimulusCode);
  1208. $this->sState = $sState;
  1209. }
  1210. /**
  1211. * Check if the speficied stimulus is allowed for the set of objects
  1212. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  1213. */
  1214. public function IsAllowed()
  1215. {
  1216. $sClass = $this->oFilter->GetClass();
  1217. if (MetaModel::IsAbstract($sClass)) return UR_ALLOWED_NO; // Safeguard, not implemented if the base class of the set is abstract !
  1218. $oSet = new DBObjectSet($this->oFilter);
  1219. $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $this->iActionCode, $oSet);
  1220. if ($iActionAllowed == UR_ALLOWED_NO)
  1221. {
  1222. $this->iAllowedCount = 0;
  1223. $this->aAllowedIDs = array();
  1224. }
  1225. else // Even if UR_ALLOWED_YES, we need to check if each object is in the appropriate state
  1226. {
  1227. // Hmmm, may not be needed right now because we limit the "multiple" action to object in
  1228. // the same state... may be useful later on if we want to extend this behavior...
  1229. // Check for each object if the action is allowed or not
  1230. $this->aAllowedIDs = array();
  1231. $oSet->Rewind();
  1232. $iAllowedCount = 0;
  1233. $iActionAllowed = UR_ALLOWED_DEPENDS;
  1234. while($oObj = $oSet->Fetch())
  1235. {
  1236. $aTransitions = $oObj->EnumTransitions();
  1237. if (array_key_exists($this->iActionCode, $aTransitions))
  1238. {
  1239. // Temporary optimization possible: since the current implementation
  1240. // of IsActionAllowed does not perform a 'per instance' check, we could
  1241. // skip this second validation phase and assume it would return UR_ALLOWED_YES
  1242. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  1243. if (!UserRights::IsStimulusAllowed($sClass, $this->iActionCode, $oObjSet))
  1244. {
  1245. $this->aAllowedIDs[$oObj->GetKey()] = false;
  1246. }
  1247. else
  1248. {
  1249. // Assume UR_ALLOWED_YES, since there is just one object !
  1250. $this->aAllowedIDs[$oObj->GetKey()] = true;
  1251. $this->iState = $oObj->GetState();
  1252. $this->iAllowedCount++;
  1253. }
  1254. }
  1255. else
  1256. {
  1257. $this->aAllowedIDs[$oObj->GetKey()] = false;
  1258. }
  1259. }
  1260. }
  1261. if ($this->iAllowedCount == $oSet->Count())
  1262. {
  1263. $iActionAllowed = UR_ALLOWED_YES;
  1264. }
  1265. if ($this->iAllowedCount == 0)
  1266. {
  1267. $iActionAllowed = UR_ALLOWED_NO;
  1268. }
  1269. return $iActionAllowed;
  1270. }
  1271. public function GetState()
  1272. {
  1273. return $this->iState;
  1274. }
  1275. }
  1276. /**
  1277. * Self-register extension to allow the automatic creation & update of CAS users
  1278. *
  1279. * @package iTopORM
  1280. *
  1281. */
  1282. class CAS_SelfRegister implements iSelfRegister
  1283. {
  1284. /**
  1285. * Called when no user is found in iTop for the corresponding 'name'. This method
  1286. * can create/synchronize the User in iTop with an external source (such as AD/LDAP) on the fly
  1287. * @param string $sName The CAS authenticated user name
  1288. * @param string $sPassword Ignored
  1289. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  1290. * @param string $sAuthentication The authentication method used
  1291. * @return bool true if the user is a valid one, false otherwise
  1292. */
  1293. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication)
  1294. {
  1295. $bOk = true;
  1296. if ($sLoginMode != 'cas') return false; // Must be authenticated via CAS
  1297. $sCASMemberships = MetaModel::GetConfig()->Get('cas_memberof');
  1298. $bFound = false;
  1299. if (!empty($sCASMemberships))
  1300. {
  1301. if (phpCAS::hasAttribute('memberOf'))
  1302. {
  1303. // A list of groups is specified, the user must a be member of (at least) one of them to pass
  1304. $aCASMemberships = array();
  1305. $aTmp = explode(';', $sCASMemberships);
  1306. setlocale(LC_ALL, "en_US.utf8"); // !!! WARNING: this is needed to have the iconv //TRANSLIT working fine below !!!
  1307. foreach($aTmp as $sGroupName)
  1308. {
  1309. $aCASMemberships[] = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Just in case remove accents and spaces...
  1310. }
  1311. $aMemberOf = phpCAS::getAttribute('memberOf');
  1312. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  1313. $aFilteredGroupNames = array();
  1314. foreach($aMemberOf as $sGroupName)
  1315. {
  1316. phpCAS::log("Info: user if a member of the group: ".$sGroupName);
  1317. $sGroupName = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Remove accents and spaces as well
  1318. $aFilteredGroupNames[] = $sGroupName;
  1319. $bIsMember = false;
  1320. foreach($aCASMemberships as $sCASPattern)
  1321. {
  1322. if (self::IsPattern($sCASPattern))
  1323. {
  1324. if (preg_match($sCASPattern, $sGroupName))
  1325. {
  1326. $bIsMember = true;
  1327. break;
  1328. }
  1329. }
  1330. else if ($sCASPattern == $sGroupName)
  1331. {
  1332. $bIsMember = true;
  1333. break;
  1334. }
  1335. }
  1336. if ($bIsMember)
  1337. {
  1338. $bCASUserSynchro = MetaModel::GetConfig()->Get('cas_user_synchro');
  1339. if ($bCASUserSynchro)
  1340. {
  1341. // If needed create a new user for this email/profile
  1342. phpCAS::log('Info: cas_user_synchro is ON');
  1343. $bOk = self::CreateCASUser(phpCAS::getUser(), $aMemberOf);
  1344. if($bOk)
  1345. {
  1346. $bFound = true;
  1347. }
  1348. else
  1349. {
  1350. phpCAS::log("User ".phpCAS::getUser()." cannot be created in iTop. Logging off...");
  1351. }
  1352. }
  1353. else
  1354. {
  1355. phpCAS::log('Info: cas_user_synchro is OFF');
  1356. $bFound = true;
  1357. }
  1358. break;
  1359. }
  1360. }
  1361. if($bOk && !$bFound)
  1362. {
  1363. phpCAS::log("User ".phpCAS::getUser().", none of his/her groups (".implode('; ', $aFilteredGroupNames).") match any of the required groups: ".implode('; ', $aCASMemberships));
  1364. }
  1365. }
  1366. else
  1367. {
  1368. // Too bad, the user is not part of any of the group => not allowed
  1369. phpCAS::log("No 'memberOf' attribute found for user ".phpCAS::getUser().". Are you using the SAML protocol (S1) ?");
  1370. }
  1371. }
  1372. else
  1373. {
  1374. // No membership: no way to create the user that should exist prior to authentication
  1375. phpCAS::log("User ".phpCAS::getUser().": missing user account in iTop (or iTop badly configured, Cf setting cas_memberof)");
  1376. $bFound = false;
  1377. }
  1378. if (!$bFound)
  1379. {
  1380. // The user is not part of the allowed groups, => log out
  1381. $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  1382. $sCASLogoutUrl = MetaModel::GetConfig()->Get('cas_logout_redirect_service');
  1383. if (empty($sCASLogoutUrl))
  1384. {
  1385. $sCASLogoutUrl = $sUrl;
  1386. }
  1387. phpCAS::logoutWithRedirectService($sCASLogoutUrl); // Redirects to the CAS logout page
  1388. // Will never return !
  1389. }
  1390. return $bFound;
  1391. }
  1392. /**
  1393. * Called after the user has been authenticated and found in iTop. This method can
  1394. * Update the user's definition (profiles...) on the fly to keep it in sync with an external source
  1395. * @param User $oUser The user to update/synchronize
  1396. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  1397. * @param string $sAuthentication The authentication method used
  1398. * @return void
  1399. */
  1400. public static function UpdateUser(User $oUser, $sLoginMode, $sAuthentication)
  1401. {
  1402. $bCASUpdateProfiles = MetaModel::GetConfig()->Get('cas_update_profiles');
  1403. if (($sLoginMode == 'cas') && $bCASUpdateProfiles && (phpCAS::hasAttribute('memberOf')))
  1404. {
  1405. $aMemberOf = phpCAS::getAttribute('memberOf');
  1406. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  1407. return self::SetProfilesFromCAS($oUser, $aMemberOf);
  1408. }
  1409. // No groups defined in CAS or not CAS at all: do nothing...
  1410. return true;
  1411. }
  1412. /**
  1413. * Helper method to create a CAS based user
  1414. * @param string $sEmail
  1415. * @param array $aGroups
  1416. * @return bool true on success, false otherwise
  1417. */
  1418. protected static function CreateCASUser($sEmail, $aGroups)
  1419. {
  1420. if (!MetaModel::IsValidClass('URP_Profiles'))
  1421. {
  1422. phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry.");
  1423. return false;
  1424. }
  1425. $oUser = MetaModel::GetObjectByName('UserExternal', $sEmail, false);
  1426. if ($oUser == null)
  1427. {
  1428. // Create the user, link it to a contact
  1429. phpCAS::log("Info: the user '$sEmail' does not exist. A new UserExternal will be created.");
  1430. $oSearch = new DBObjectSearch('Person');
  1431. $oSearch->AddCondition('email', $sEmail);
  1432. $oSet = new DBObjectSet($oSearch);
  1433. $iContactId = 0;
  1434. switch($oSet->Count())
  1435. {
  1436. case 0:
  1437. phpCAS::log("Error: found no contact with the email: '$sEmail'. Cannot create the user in iTop.");
  1438. return false;
  1439. case 1:
  1440. $oContact = $oSet->Fetch();
  1441. $iContactId = $oContact->GetKey();
  1442. phpCAS::log("Info: Found 1 contact '".$oContact->GetName()."' (id=$iContactId) corresponding to the email '$sEmail'.");
  1443. break;
  1444. default:
  1445. phpCAS::log("Error: ".$oSet->Count()." contacts have the same email: '$sEmail'. Cannot create a user for this email.");
  1446. return false;
  1447. }
  1448. $oUser = new UserExternal();
  1449. $oUser->Set('login', $sEmail);
  1450. $oUser->Set('contactid', $iContactId);
  1451. $oUser->Set('language', MetaModel::GetConfig()->GetDefaultLanguage());
  1452. }
  1453. else
  1454. {
  1455. phpCAS::log("Info: the user '$sEmail' already exists (id=".$oUser->GetKey().").");
  1456. }
  1457. // Now synchronize the profiles
  1458. if (!self::SetProfilesFromCAS($oUser, $aGroups))
  1459. {
  1460. return false;
  1461. }
  1462. else
  1463. {
  1464. if ($oUser->IsNew() || $oUser->IsModified())
  1465. {
  1466. $oMyChange = MetaModel::NewObject("CMDBChange");
  1467. $oMyChange->Set("date", time());
  1468. $oMyChange->Set("userinfo", 'CAS/LDAP Synchro');
  1469. $oMyChange->DBInsert();
  1470. if ($oUser->IsNew())
  1471. {
  1472. $oUser->DBInsertTracked($oMyChange);
  1473. }
  1474. else
  1475. {
  1476. $oUser->DBUpdateTracked($oMyChange);
  1477. }
  1478. }
  1479. return true;
  1480. }
  1481. }
  1482. protected static function SetProfilesFromCAS($oUser, $aGroups)
  1483. {
  1484. if (!MetaModel::IsValidClass('URP_Profiles'))
  1485. {
  1486. phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry.");
  1487. return false;
  1488. }
  1489. // read all the existing profiles
  1490. $oProfilesSearch = new DBObjectSearch('URP_Profiles');
  1491. $oProfilesSet = new DBObjectSet($oProfilesSearch);
  1492. $aAllProfiles = array();
  1493. while($oProfile = $oProfilesSet->Fetch())
  1494. {
  1495. $aAllProfiles[strtolower($oProfile->GetName())] = $oProfile->GetKey();
  1496. }
  1497. // Translate the CAS/LDAP group names into iTop profile names
  1498. $aProfiles = array();
  1499. $sPattern = MetaModel::GetConfig()->Get('cas_profile_pattern');
  1500. foreach($aGroups as $sGroupName)
  1501. {
  1502. if (preg_match($sPattern, $sGroupName, $aMatches))
  1503. {
  1504. if (array_key_exists(strtolower($aMatches[1]), $aAllProfiles))
  1505. {
  1506. $aProfiles[] = $aAllProfiles[strtolower($aMatches[1])];
  1507. phpCAS::log("Info: Adding the profile '{$aMatches[1]}' from CAS.");
  1508. }
  1509. else
  1510. {
  1511. phpCAS::log("Warning: {$aMatches[1]} is not a valid iTop profile (extracted from group name: '$sGroupName'). Ignored.");
  1512. }
  1513. }
  1514. else
  1515. {
  1516. phpCAS::log("Info: The CAS group '$sGroupName' does not seem to match an iTop pattern. Ignored.");
  1517. }
  1518. }
  1519. if (count($aProfiles) == 0)
  1520. {
  1521. phpCAS::log("Info: The user '".$oUser->GetName()."' has no profiles retrieved from CAS. Default profile(s) will be used.");
  1522. // Second attempt: check if there is/are valid default profile(s)
  1523. $sCASDefaultProfiles = MetaModel::GetConfig()->Get('cas_default_profiles');
  1524. $aCASDefaultProfiles = explode(';', $sCASDefaultProfiles);
  1525. foreach($aCASDefaultProfiles as $sDefaultProfileName)
  1526. {
  1527. if (array_key_exists(strtolower($sDefaultProfileName), $aAllProfiles))
  1528. {
  1529. $aProfiles[] = $aAllProfiles[strtolower($sDefaultProfileName)];
  1530. phpCAS::log("Info: Adding the default profile '".$aAllProfiles[strtolower($sDefaultProfileName)]."' from CAS.");
  1531. }
  1532. else
  1533. {
  1534. phpCAS::log("Warning: the default profile {$sDefaultProfileName} is not a valid iTop profile. Ignored.");
  1535. }
  1536. }
  1537. if (count($aProfiles) == 0)
  1538. {
  1539. phpCAS::log("Error: The user '".$oUser->GetName()."' has no profiles in iTop, and therefore cannot be created.");
  1540. return false;
  1541. }
  1542. }
  1543. // Now synchronize the profiles
  1544. $oProfilesSet = DBObjectSet::FromScratch('URP_UserProfile');
  1545. foreach($aProfiles as $iProfileId)
  1546. {
  1547. $oLink = new URP_UserProfile();
  1548. $oLink->Set('profileid', $iProfileId);
  1549. $oLink->Set('reason', 'CAS/LDAP Synchro');
  1550. $oProfilesSet->AddObject($oLink);
  1551. }
  1552. $oUser->Set('profile_list', $oProfilesSet);
  1553. phpCAS::log("Info: the user '".$oUser->GetName()."' (id=".$oUser->GetKey().") now has the following profiles: '".implode("', '", $aProfiles)."'.");
  1554. if ($oUser->IsModified())
  1555. {
  1556. $oMyChange = MetaModel::NewObject("CMDBChange");
  1557. $oMyChange->Set("date", time());
  1558. $oMyChange->Set("userinfo", 'CAS/LDAP Synchro');
  1559. $oMyChange->DBInsert();
  1560. if ($oUser->IsNew())
  1561. {
  1562. $oUser->DBInsertTracked($oMyChange);
  1563. }
  1564. else
  1565. {
  1566. $oUser->DBUpdateTracked($oMyChange);
  1567. }
  1568. }
  1569. return true;
  1570. }
  1571. /**
  1572. * Helper function to check if the supplied string is a litteral string or a regular expression pattern
  1573. * @param string $sCASPattern
  1574. * @return bool True if it's a regular expression pattern, false otherwise
  1575. */
  1576. protected static function IsPattern($sCASPattern)
  1577. {
  1578. if ((substr($sCASPattern, 0, 1) == '/') && (substr($sCASPattern, -1) == '/'))
  1579. {
  1580. // the string is enclosed by slashes, let's assume it's a pattern
  1581. return true;
  1582. }
  1583. else
  1584. {
  1585. return false;
  1586. }
  1587. }
  1588. }
  1589. // By default enable the 'CAS_SelfRegister' defined above
  1590. UserRights::SelectSelfRegister('CAS_SelfRegister');