userrights.class.inc.php 50 KB

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