userrights.class.inc.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * User rights management API
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  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_APPLICATION_DEFINED', 10000); // Application specific actions (CSV import, View schema...)
  37. /**
  38. * User management module API
  39. *
  40. * @package iTopORM
  41. */
  42. abstract class UserRightsAddOnAPI
  43. {
  44. abstract public function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US'); // could be used during initial installation
  45. abstract public function Init(); // loads data (possible optimizations)
  46. // Used to build select queries showing only objects visible for the given user
  47. abstract public function GetSelectFilter($sLogin, $sClass); // returns a filter object
  48. abstract public function IsActionAllowed($oUser, $sClass, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null);
  49. abstract public function IsStimulusAllowed($oUser, $sClass, $sStimulusCode, /*dbObjectSet*/ $oInstanceSet = null);
  50. abstract public function IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null);
  51. abstract public function IsAdministrator($oUser);
  52. abstract public function IsPortalUser($oUser);
  53. abstract public function FlushPrivileges();
  54. }
  55. abstract class User extends cmdbAbstractObject
  56. {
  57. public static function Init()
  58. {
  59. $aParams = array
  60. (
  61. "category" => "core",
  62. "key_type" => "autoincrement",
  63. "name_attcode" => "login",
  64. "state_attcode" => "",
  65. "reconc_keys" => array(),
  66. "db_table" => "priv_user",
  67. "db_key_field" => "id",
  68. "db_finalclass_field" => "",
  69. "display_template" => "",
  70. );
  71. MetaModel::Init_Params($aParams);
  72. //MetaModel::Init_InheritAttributes();
  73. 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())));
  74. MetaModel::Init_AddAttribute(new AttributeExternalField("last_name", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"name")));
  75. MetaModel::Init_AddAttribute(new AttributeExternalField("first_name", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"first_name")));
  76. MetaModel::Init_AddAttribute(new AttributeExternalField("email", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"email")));
  77. MetaModel::Init_AddAttribute(new AttributeString("login", array("allowed_values"=>null, "sql"=>"login", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  78. MetaModel::Init_AddAttribute(new AttributeApplicationLanguage("language", array("sql"=>"language", "default_value"=>"EN US", "is_null_allowed"=>false, "depends_on"=>array())));
  79. 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())));
  80. 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())));
  81. // Display lists
  82. MetaModel::Init_SetZListItems('details', array('contactid', 'first_name', 'email', 'login', 'language', 'profile_list', 'allowed_org_list')); // Attributes to be displayed for the complete details
  83. MetaModel::Init_SetZListItems('list', array('finalclass', 'first_name', 'last_name', 'login')); // Attributes to be displayed for a list
  84. // Search criteria
  85. MetaModel::Init_SetZListItems('standard_search', array('login', 'contactid')); // Criteria of the std search form
  86. MetaModel::Init_SetZListItems('advanced_search', array('login', 'contactid')); // Criteria of the advanced search form
  87. }
  88. abstract public function CheckCredentials($sPassword);
  89. abstract public function TrustWebServerContext();
  90. abstract public function CanChangePassword();
  91. abstract public function ChangePassword($sOldPassword, $sNewPassword);
  92. /*
  93. * Compute a name in best effort mode
  94. */
  95. public function GetFriendlyName()
  96. {
  97. if (!MetaModel::IsValidAttCode(get_class($this), 'contactid'))
  98. {
  99. return $this->Get('login');
  100. }
  101. if ($this->Get('contactid') != 0)
  102. {
  103. $sFirstName = $this->Get('first_name');
  104. $sLastName = $this->Get('last_name');
  105. $sEmail = $this->Get('email');
  106. if (strlen($sFirstName) > 0)
  107. {
  108. return "$sFirstName $sLastName";
  109. }
  110. elseif (strlen($sEmail) > 0)
  111. {
  112. return "$sLastName <$sEmail>";
  113. }
  114. else
  115. {
  116. return $sLastName;
  117. }
  118. }
  119. }
  120. /*
  121. * Overload the standard behavior
  122. */
  123. public function DoCheckToWrite()
  124. {
  125. parent::DoCheckToWrite();
  126. // Note: This MUST be factorized later: declare unique keys (set of columns) in the data model
  127. $aChanges = $this->ListChanges();
  128. if (array_key_exists('login', $aChanges))
  129. {
  130. $sNewLogin = $aChanges['login'];
  131. $oSearch = DBObjectSearch::FromOQL_AllData("SELECT User WHERE login = :newlogin");
  132. $oSet = new DBObjectSet($oSearch, array(), array('newlogin' => $sNewLogin));
  133. if ($oSet->Count() > 0)
  134. {
  135. $this->m_aCheckIssues[] = Dict::Format('Class:User/Error:LoginMustBeUnique', $sNewLogin);
  136. }
  137. }
  138. // Check that this user has at least one profile assigned
  139. $oSet = $this->Get('profile_list');
  140. if ($oSet->Count() == 0)
  141. {
  142. $this->m_aCheckIssues[] = Dict::Format('Class:User/Error:AtLeastOneProfileIsNeeded');
  143. }
  144. }
  145. function GetGrantAsHtml($sClass, $iAction)
  146. {
  147. if (UserRights::IsActionAllowed($sClass, $iAction, null, $this))
  148. {
  149. return '<span style="background-color: #ddffdd;">'.Dict::S('UI:UserManagement:ActionAllowed:Yes').'</span>';
  150. }
  151. else
  152. {
  153. return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
  154. }
  155. }
  156. function DoShowGrantSumary($oPage, $sClassCategory)
  157. {
  158. if (UserRights::IsAdministrator($this))
  159. {
  160. // Looks dirty, but ok that's THE ONE
  161. $oPage->p(Dict::S('UI:UserManagement:AdminProfile+'));
  162. return;
  163. }
  164. $oKPI = new ExecutionKPI();
  165. $aDisplayData = array();
  166. foreach (MetaModel::GetClasses($sClassCategory) as $sClass)
  167. {
  168. $aClassStimuli = MetaModel::EnumStimuli($sClass);
  169. if (count($aClassStimuli) > 0)
  170. {
  171. $aStimuli = array();
  172. foreach ($aClassStimuli as $sStimulusCode => $oStimulus)
  173. {
  174. if (UserRights::IsStimulusAllowed($sClass, $sStimulusCode, null, $this))
  175. {
  176. $aStimuli[] = '<span title="'.$sStimulusCode.': '.htmlentities($oStimulus->GetDescription(), ENT_QUOTES, 'UTF-8').'">'.htmlentities($oStimulus->GetLabel(), ENT_QUOTES, 'UTF-8').'</span>';
  177. }
  178. }
  179. $sStimuli = implode(', ', $aStimuli);
  180. }
  181. else
  182. {
  183. $sStimuli = '<em title="'.Dict::S('UI:UserManagement:NoLifeCycleApplicable+').'">'.Dict::S('UI:UserManagement:NoLifeCycleApplicable').'</em>';
  184. }
  185. $aDisplayData[] = array(
  186. 'class' => MetaModel::GetName($sClass),
  187. 'read' => $this->GetGrantAsHtml($sClass, UR_ACTION_READ),
  188. 'bulkread' => $this->GetGrantAsHtml($sClass, UR_ACTION_BULK_READ),
  189. 'write' => $this->GetGrantAsHtml($sClass, UR_ACTION_MODIFY),
  190. 'bulkwrite' => $this->GetGrantAsHtml($sClass, UR_ACTION_BULK_MODIFY),
  191. 'stimuli' => $sStimuli,
  192. );
  193. }
  194. $oKPI->ComputeAndReport('Computation of user rights');
  195. $aDisplayConfig = array();
  196. $aDisplayConfig['class'] = array('label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+'));
  197. $aDisplayConfig['read'] = array('label' => Dict::S('UI:UserManagement:Action:Read'), 'description' => Dict::S('UI:UserManagement:Action:Read+'));
  198. $aDisplayConfig['bulkread'] = array('label' => Dict::S('UI:UserManagement:Action:BulkRead'), 'description' => Dict::S('UI:UserManagement:Action:BulkRead+'));
  199. $aDisplayConfig['write'] = array('label' => Dict::S('UI:UserManagement:Action:Modify'), 'description' => Dict::S('UI:UserManagement:Action:Modify+'));
  200. $aDisplayConfig['bulkwrite'] = array('label' => Dict::S('UI:UserManagement:Action:BulkModify'), 'description' => Dict::S('UI:UserManagement:Action:BulkModify+'));
  201. $aDisplayConfig['stimuli'] = array('label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+'));
  202. $oPage->table($aDisplayConfig, $aDisplayData);
  203. }
  204. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  205. {
  206. parent::DisplayBareRelations($oPage, $bEditMode);
  207. if (!$bEditMode)
  208. {
  209. $oPage->SetCurrentTab(Dict::S('UI:UserManagement:GrantMatrix'));
  210. $this->DoShowGrantSumary($oPage, 'bizmodel');
  211. // debug
  212. if (false)
  213. {
  214. $oPage->SetCurrentTab('More on user rigths (dev only)');
  215. $oPage->add("<h3>User rights</h3>\n");
  216. $this->DoShowGrantSumary($oPage, 'addon/userrights');
  217. $oPage->add("<h3>Change log</h3>\n");
  218. $this->DoShowGrantSumary($oPage, 'core/cmdb');
  219. $oPage->add("<h3>Application</h3>\n");
  220. $this->DoShowGrantSumary($oPage, 'application');
  221. $oPage->add("<h3>GUI</h3>\n");
  222. $this->DoShowGrantSumary($oPage, 'gui');
  223. }
  224. }
  225. }
  226. }
  227. /**
  228. * Abstract class for all types of "internal" authentication i.e. users
  229. * for which the application is supplied a login and a password opposed
  230. * to "external" users for whom the authentication is performed outside
  231. * of the application (by the web server for example).
  232. * Note that "internal" users do not necessary correspond to a local authentication
  233. * they may be authenticated by a remote system, like in authent-ldap.
  234. */
  235. abstract class UserInternal extends User
  236. {
  237. // Nothing special, just a base class to categorize this type of authenticated users
  238. public static function Init()
  239. {
  240. $aParams = array
  241. (
  242. "category" => "core",
  243. "key_type" => "autoincrement",
  244. "name_attcode" => "login",
  245. "state_attcode" => "",
  246. "reconc_keys" => array('login'),
  247. "db_table" => "priv_internalUser",
  248. "db_key_field" => "id",
  249. "db_finalclass_field" => "",
  250. );
  251. MetaModel::Init_Params($aParams);
  252. MetaModel::Init_InheritAttributes();
  253. // Display lists
  254. MetaModel::Init_SetZListItems('details', array('contactid', 'first_name', 'email', 'login', 'language', 'profile_list', 'allowed_org_list')); // Attributes to be displayed for the complete details
  255. MetaModel::Init_SetZListItems('list', array('finalclass', 'first_name', 'last_name', 'login')); // Attributes to be displayed for a list
  256. // Search criteria
  257. MetaModel::Init_SetZListItems('standard_search', array('login', 'contactid')); // Criteria of the std search form
  258. MetaModel::Init_SetZListItems('advanced_search', array('login', 'contactid')); // Criteria of the advanced search form
  259. }
  260. }
  261. /**
  262. * Self register extension
  263. *
  264. * @package iTopORM
  265. */
  266. interface iSelfRegister
  267. {
  268. /**
  269. * Called when no user is found in iTop for the corresponding 'name'. This method
  270. * can create/synchronize the User in iTop with an external source (such as AD/LDAP) on the fly
  271. * @param string $sName The typed-in user name
  272. * @param string $sPassword The typed-in password
  273. * @param string $sLoginMode The login method used (cas|form|basic|url)
  274. * @param string $sAuthentication The authentication method used (any|internal|external)
  275. * @return bool true if the user is a valid one, false otherwise
  276. */
  277. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication);
  278. /**
  279. * Called after the user has been authenticated and found in iTop. This method can
  280. * Update the user's definition on the fly (profiles...) to keep it in sync with an external source
  281. * @param User $oUser The user to update/synchronize
  282. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  283. * @param string $sAuthentication The authentication method used
  284. * @return void
  285. */
  286. public static function UpdateUser(User $oUser, $sLoginMode, $sAuthentication);
  287. }
  288. /**
  289. * User management core API
  290. *
  291. * @package iTopORM
  292. */
  293. class UserRights
  294. {
  295. protected static $m_oAddOn;
  296. protected static $m_oUser;
  297. protected static $m_oRealUser;
  298. protected static $m_sSelfRegisterAddOn = null;
  299. public static function SelectModule($sModuleName)
  300. {
  301. if (!class_exists($sModuleName))
  302. {
  303. throw new CoreException("Could not select this module, '$sModuleName' in not a valid class name");
  304. return;
  305. }
  306. if (!is_subclass_of($sModuleName, 'UserRightsAddOnAPI'))
  307. {
  308. throw new CoreException("Could not select this module, the class '$sModuleName' is not derived from UserRightsAddOnAPI");
  309. return;
  310. }
  311. self::$m_oAddOn = new $sModuleName;
  312. self::$m_oAddOn->Init();
  313. self::$m_oUser = null;
  314. self::$m_oRealUser = null;
  315. }
  316. public static function SelectSelfRegister($sModuleName)
  317. {
  318. if (!class_exists($sModuleName))
  319. {
  320. throw new CoreException("Could not select the class, '$sModuleName' for self register, is not a valid class name");
  321. }
  322. self::$m_sSelfRegisterAddOn = $sModuleName;
  323. }
  324. public static function GetModuleInstance()
  325. {
  326. return self::$m_oAddOn;
  327. }
  328. // Installation: create the very first user
  329. public static function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US')
  330. {
  331. $bRes = self::$m_oAddOn->CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage);
  332. self::FlushPrivileges(true /* reset admin cache */);
  333. return $bRes;
  334. }
  335. protected static function IsLoggedIn()
  336. {
  337. if (self::$m_oUser == null)
  338. {
  339. return false;
  340. }
  341. else
  342. {
  343. return true;
  344. }
  345. }
  346. public static function Login($sName, $sAuthentication = 'any')
  347. {
  348. $oUser = self::FindUser($sName, $sAuthentication);
  349. if (is_null($oUser))
  350. {
  351. return false;
  352. }
  353. self::$m_oUser = $oUser;
  354. Dict::SetUserLanguage(self::GetUserLanguage());
  355. return true;
  356. }
  357. public static function CheckCredentials($sName, $sPassword, $sLoginMode = 'form', $sAuthentication = 'any')
  358. {
  359. $oUser = self::FindUser($sName, $sAuthentication);
  360. if (is_null($oUser))
  361. {
  362. return self::CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication);
  363. }
  364. if (!$oUser->CheckCredentials($sPassword))
  365. {
  366. return false;
  367. }
  368. self::UpdateUser($oUser, $sLoginMode, $sAuthentication);
  369. return true;
  370. }
  371. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication)
  372. {
  373. if (self::$m_sSelfRegisterAddOn != null)
  374. {
  375. return call_user_func(array(self::$m_sSelfRegisterAddOn, 'CheckCredentialsAndCreateUser'), $sName, $sPassword, $sLoginMode, $sAuthentication);
  376. }
  377. }
  378. public static function UpdateUser($oUser, $sLoginMode, $sAuthentication)
  379. {
  380. if (self::$m_sSelfRegisterAddOn != null)
  381. {
  382. call_user_func(array(self::$m_sSelfRegisterAddOn, 'UpdateUser'), $oUser, $sLoginMode, $sAuthentication);
  383. }
  384. }
  385. public static function TrustWebServerContext()
  386. {
  387. if (!is_null(self::$m_oUser))
  388. {
  389. return self::$m_oUser->TrustWebServerContext();
  390. }
  391. else
  392. {
  393. return false;
  394. }
  395. }
  396. public static function CanChangePassword()
  397. {
  398. if (MetaModel::DBIsReadOnly())
  399. {
  400. return false;
  401. }
  402. if (!is_null(self::$m_oUser))
  403. {
  404. return self::$m_oUser->CanChangePassword();
  405. }
  406. else
  407. {
  408. return false;
  409. }
  410. }
  411. public static function ChangePassword($sOldPassword, $sNewPassword, $sName = '')
  412. {
  413. if (empty($sName))
  414. {
  415. $oUser = self::$m_oUser;
  416. }
  417. else
  418. {
  419. // find the id out of the login string
  420. $oUser = self::FindUser($sName);
  421. }
  422. if (is_null($oUser))
  423. {
  424. return false;
  425. }
  426. else
  427. {
  428. return $oUser->ChangePassword($sOldPassword, $sNewPassword);
  429. }
  430. }
  431. public static function Impersonate($sName, $sPassword)
  432. {
  433. if (!self::CheckLogin()) return false;
  434. $oUser = self::FindUser($sName);
  435. if (is_null($oUser))
  436. {
  437. return false;
  438. }
  439. if (!$oUser->CheckCredentials($sPassword))
  440. {
  441. return false;
  442. }
  443. self::$m_oRealUser = self::$m_oUser;
  444. self::$m_oUser = $oUser;
  445. Dict::SetUserLanguage(self::GetUserLanguage());
  446. return true;
  447. }
  448. public static function GetUser()
  449. {
  450. if (is_null(self::$m_oUser))
  451. {
  452. return '';
  453. }
  454. else
  455. {
  456. return self::$m_oUser->Get('login');
  457. }
  458. }
  459. public static function GetUserObject()
  460. {
  461. if (is_null(self::$m_oUser))
  462. {
  463. return null;
  464. }
  465. else
  466. {
  467. return self::$m_oUser;
  468. }
  469. }
  470. public static function GetUserLanguage()
  471. {
  472. if (is_null(self::$m_oUser))
  473. {
  474. return 'EN US';
  475. }
  476. else
  477. {
  478. return self::$m_oUser->Get('language');
  479. }
  480. }
  481. public static function GetUserId($sName = '')
  482. {
  483. if (empty($sName))
  484. {
  485. // return current user id
  486. if (is_null(self::$m_oUser))
  487. {
  488. return null;
  489. }
  490. return self::$m_oUser->GetKey();
  491. }
  492. else
  493. {
  494. // find the id out of the login string
  495. $oUser = self::$m_oAddOn->FindUser($sName);
  496. if (is_null($oUser))
  497. {
  498. return null;
  499. }
  500. return $oUser->GetKey();
  501. }
  502. }
  503. public static function GetContactId($sName = '')
  504. {
  505. if (empty($sName))
  506. {
  507. $oUser = self::$m_oUser;
  508. }
  509. else
  510. {
  511. $oUser = FindUser($sName);
  512. }
  513. if (is_null($oUser))
  514. {
  515. return '';
  516. }
  517. if (!MetaModel::IsValidAttCode(get_class($oUser), 'contactid'))
  518. {
  519. return '';
  520. }
  521. return $oUser->Get('contactid');
  522. }
  523. // Render the user name in best effort mode
  524. public static function GetUserFriendlyName($sName = '')
  525. {
  526. if (empty($sName))
  527. {
  528. $oUser = self::$m_oUser;
  529. }
  530. else
  531. {
  532. $oUser = FindUser($sName);
  533. }
  534. if (is_null($oUser))
  535. {
  536. return '';
  537. }
  538. return $oUser->GetFriendlyName();
  539. }
  540. public static function IsImpersonated()
  541. {
  542. if (is_null(self::$m_oRealUser))
  543. {
  544. return false;
  545. }
  546. return true;
  547. }
  548. public static function GetRealUser()
  549. {
  550. if (is_null(self::$m_oRealUser))
  551. {
  552. return '';
  553. }
  554. return self::$m_oRealUser->Get('login');
  555. }
  556. public static function GetRealUserId()
  557. {
  558. if (is_null(self::$m_oRealUser))
  559. {
  560. return '';
  561. }
  562. return self::$m_oRealUser->GetKey();
  563. }
  564. public static function GetRealUserFriendlyName()
  565. {
  566. if (is_null(self::$m_oRealUser))
  567. {
  568. return '';
  569. }
  570. return self::$m_oRealUser->GetFriendlyName();
  571. }
  572. protected static function CheckLogin()
  573. {
  574. if (!self::IsLoggedIn())
  575. {
  576. //throw new UserRightException('No user logged in', array());
  577. return false;
  578. }
  579. return true;
  580. }
  581. public static function GetSelectFilter($sClass)
  582. {
  583. // When initializing, we need to let everything pass trough
  584. if (!self::CheckLogin()) return true;
  585. if (self::IsAdministrator()) return true;
  586. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  587. {
  588. return self::$m_oAddOn->GetSelectFilter(self::$m_oUser, $sClass);
  589. }
  590. else
  591. {
  592. return true;
  593. }
  594. }
  595. public static function IsActionAllowed($sClass, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  596. {
  597. // When initializing, we need to let everything pass trough
  598. if (!self::CheckLogin()) return true;
  599. if (MetaModel::DBIsReadOnly())
  600. {
  601. if ($iActionCode == UR_ACTION_MODIFY) return false;
  602. if ($iActionCode == UR_ACTION_DELETE) return false;
  603. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  604. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  605. }
  606. if (self::IsAdministrator($oUser)) return true;
  607. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  608. {
  609. if (is_null($oUser))
  610. {
  611. $oUser = self::$m_oUser;
  612. }
  613. return self::$m_oAddOn->IsActionAllowed($oUser, $sClass, $iActionCode, $oInstanceSet);
  614. }
  615. elseif(($iActionCode == UR_ACTION_READ) && MetaModel::HasCategory($sClass, 'view_in_gui'))
  616. {
  617. return true;
  618. }
  619. else
  620. {
  621. // Other classes could be edited/listed by the administrators
  622. return false;
  623. }
  624. }
  625. public static function IsStimulusAllowed($sClass, $sStimulusCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  626. {
  627. // When initializing, we need to let everything pass trough
  628. if (!self::CheckLogin()) return true;
  629. if (MetaModel::DBIsReadOnly())
  630. {
  631. return false;
  632. }
  633. if (self::IsAdministrator($oUser)) return true;
  634. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  635. {
  636. if (is_null($oUser))
  637. {
  638. $oUser = self::$m_oUser;
  639. }
  640. return self::$m_oAddOn->IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet);
  641. }
  642. else
  643. {
  644. // Other classes could be edited/listed by the administrators
  645. return false;
  646. }
  647. }
  648. public static function IsActionAllowedOnAttribute($sClass, $sAttCode, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  649. {
  650. // When initializing, we need to let everything pass trough
  651. if (!self::CheckLogin()) return true;
  652. if (MetaModel::DBIsReadOnly())
  653. {
  654. if ($iActionCode == UR_ACTION_MODIFY) return false;
  655. if ($iActionCode == UR_ACTION_DELETE) return false;
  656. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  657. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  658. }
  659. if (self::IsAdministrator($oUser)) return true;
  660. // this module is forbidden for non admins
  661. if (MetaModel::HasCategory($sClass, 'addon/userrights')) return false;
  662. // the rest is allowed (#@# to be improved)
  663. if (!MetaModel::HasCategory($sClass, 'bizmodel')) return true;
  664. if (is_null($oUser))
  665. {
  666. $oUser = self::$m_oUser;
  667. }
  668. return self::$m_oAddOn->IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, $oInstanceSet);
  669. }
  670. static $m_aAdmins = array();
  671. public static function IsAdministrator($oUser = null)
  672. {
  673. if (!self::CheckLogin()) return false;
  674. if (is_null($oUser))
  675. {
  676. $oUser = self::$m_oUser;
  677. }
  678. $iUser = $oUser->GetKey();
  679. if (!isset(self::$m_aAdmins[$iUser]))
  680. {
  681. self::$m_aAdmins[$iUser] = self::$m_oAddOn->IsAdministrator($oUser);
  682. }
  683. return self::$m_aAdmins[$iUser];
  684. }
  685. static $m_aPortalUsers = array();
  686. public static function IsPortalUser($oUser = null)
  687. {
  688. if (!self::CheckLogin()) return false;
  689. if (is_null($oUser))
  690. {
  691. $oUser = self::$m_oUser;
  692. }
  693. $iUser = $oUser->GetKey();
  694. if (!isset(self::$m_aPortalUsers[$iUser]))
  695. {
  696. self::$m_aPortalUsers[$iUser] = self::$m_oAddOn->IsPortalUser($oUser);
  697. }
  698. return self::$m_aPortalUsers[$iUser];
  699. }
  700. /**
  701. * Reset cached data
  702. * @param Bool Reset admin cache as well
  703. * @return void
  704. */
  705. // Reset cached data
  706. //
  707. public static function FlushPrivileges($bResetAdminCache = false)
  708. {
  709. if ($bResetAdminCache)
  710. {
  711. self::$m_aAdmins = array();
  712. }
  713. return self::$m_oAddOn->FlushPrivileges();
  714. }
  715. static $m_aCacheUsers;
  716. /**
  717. * Find a user based on its login and its type of authentication
  718. * @param string $sLogin Login/identifier of the user
  719. * @param string $sAuthentication Type of authentication used: internal|external|any
  720. * @return User The found user or null
  721. */
  722. protected static function FindUser($sLogin, $sAuthentication = 'any')
  723. {
  724. if ($sAuthentication == 'any')
  725. {
  726. $oUser = self::FindUser($sLogin, 'internal');
  727. if ($oUser == null)
  728. {
  729. $oUser = self::FindUser($sLogin, 'external');
  730. }
  731. }
  732. else
  733. {
  734. if (!isset(self::$m_aCacheUsers))
  735. {
  736. self::$m_aCacheUsers = array('internal' => array(), 'external' => array());
  737. }
  738. if (!isset(self::$m_aCacheUsers[$sAuthentication][$sLogin]))
  739. {
  740. switch($sAuthentication)
  741. {
  742. case 'external':
  743. $sBaseClass = 'UserExternal';
  744. break;
  745. case 'internal':
  746. $sBaseClass = 'UserInternal';
  747. break;
  748. default:
  749. echo "<p>sAuthentication = $sAuthentication</p>\n";
  750. assert(false); // should never happen
  751. }
  752. $oSearch = DBObjectSearch::FromOQL("SELECT $sBaseClass WHERE login = :login");
  753. $oSet = new DBObjectSet($oSearch, array(), array('login' => $sLogin));
  754. $oUser = $oSet->fetch();
  755. self::$m_aCacheUsers[$sAuthentication][$sLogin] = $oUser;
  756. }
  757. $oUser = self::$m_aCacheUsers[$sAuthentication][$sLogin];
  758. }
  759. return $oUser;
  760. }
  761. }
  762. /**
  763. * Helper class to get the number/list of items for which a given action is allowed/possible
  764. */
  765. class ActionChecker
  766. {
  767. var $oFilter;
  768. var $iActionCode;
  769. var $iAllowedCount = null;
  770. var $aAllowedIDs = null;
  771. public function __construct(DBObjectSearch $oFilter, $iActionCode)
  772. {
  773. $this->oFilter = $oFilter;
  774. $this->iActionCode = $iActionCode;
  775. $this->iAllowedCount = null;
  776. $this->aAllowedIDs = null;
  777. }
  778. /**
  779. * returns the number of objects for which the action is allowed
  780. * @return integer The number of "allowed" objects 0..N
  781. */
  782. public function GetAllowedCount()
  783. {
  784. if ($this->iAllowedCount == null) $this->CheckObjects();
  785. return $this->iAllowedCount;
  786. }
  787. /**
  788. * If IsAllowed returned UR_ALLOWED_DEPENDS, this methods returns
  789. * an array of ObjKey => Status (true|false)
  790. * @return array
  791. */
  792. public function GetAllowedIDs()
  793. {
  794. if ($this->aAllowedIDs == null) $this->IsAllowed();
  795. return $this->aAllowedIDs;
  796. }
  797. /**
  798. * Check if the speficied stimulus is allowed for the set of objects
  799. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  800. */
  801. public function IsAllowed()
  802. {
  803. $sClass = $this->oFilter->GetClass();
  804. $oSet = new DBObjectSet($this->oFilter);
  805. $iActionAllowed = UserRights::IsActionAllowed($sClass, $this->iActionCode, $oSet);
  806. if ($iActionAllowed == UR_ALLOWED_DEPENDS)
  807. {
  808. // Check for each object if the action is allowed or not
  809. $this->aAllowedIDs = array();
  810. $oSet->Rewind();
  811. $this->iAllowedCount = 0;
  812. while($oObj = $oSet->Fetch())
  813. {
  814. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  815. if (UserRights::IsActionAllowed($sClass, $this->iActionCode, $oObjSet) == UR_ALLOWED_NO)
  816. {
  817. $this->aAllowedIDs[$oObj->GetKey()] = false;
  818. }
  819. else
  820. {
  821. // Assume UR_ALLOWED_YES, since there is just one object !
  822. $this->aAllowedIDs[$oObj->GetKey()] = true;
  823. $this->iAllowedCount++;
  824. }
  825. }
  826. }
  827. else if ($iActionAllowed == UR_ALLOWED_YES)
  828. {
  829. $this->iAllowedCount = $oSet->Count();
  830. $this->aAllowedIDs = array(); // Optimization: not filled when Ok for all objects
  831. }
  832. else // UR_ALLOWED_NO
  833. {
  834. $this->iAllowedCount = 0;
  835. $this->aAllowedIDs = array();
  836. }
  837. return $iActionAllowed;
  838. }
  839. }
  840. /**
  841. * Helper class to get the number/list of items for which a given stimulus can be applied (allowed & possible)
  842. */
  843. class StimulusChecker extends ActionChecker
  844. {
  845. var $sState = null;
  846. public function __construct(DBObjectSearch $oFilter, $sState, $iStimulusCode)
  847. {
  848. parent::__construct($oFilter, $iStimulusCode);
  849. $this->sState = $sState;
  850. }
  851. /**
  852. * Check if the speficied stimulus is allowed for the set of objects
  853. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  854. */
  855. public function IsAllowed()
  856. {
  857. $sClass = $this->oFilter->GetClass();
  858. if (MetaModel::IsAbstract($sClass)) return UR_ALLOWED_NO; // Safeguard, not implemented if the base class of the set is abstract !
  859. $oSet = new DBObjectSet($this->oFilter);
  860. $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $this->iActionCode, $oSet);
  861. if ($iActionAllowed == UR_ALLOWED_NO)
  862. {
  863. $this->iAllowedCount = 0;
  864. $this->aAllowedIDs = array();
  865. }
  866. else // Even if UR_ALLOWED_YES, we need to check if each object is in the appropriate state
  867. {
  868. // Hmmm, may not be needed right now because we limit the "multiple" action to object in
  869. // the same state... may be useful later on if we want to extend this behavior...
  870. // Check for each object if the action is allowed or not
  871. $this->aAllowedIDs = array();
  872. $oSet->Rewind();
  873. $iAllowedCount = 0;
  874. $iActionAllowed = UR_ALLOWED_DEPENDS;
  875. while($oObj = $oSet->Fetch())
  876. {
  877. $aTransitions = $oObj->EnumTransitions();
  878. if (array_key_exists($this->iActionCode, $aTransitions))
  879. {
  880. // Temporary optimization possible: since the current implementation
  881. // of IsActionAllowed does not perform a 'per instance' check, we could
  882. // skip this second validation phase and assume it would return UR_ALLOWED_YES
  883. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  884. if (!UserRights::IsStimulusAllowed($sClass, $this->iActionCode, $oObjSet))
  885. {
  886. $this->aAllowedIDs[$oObj->GetKey()] = false;
  887. }
  888. else
  889. {
  890. // Assume UR_ALLOWED_YES, since there is just one object !
  891. $this->aAllowedIDs[$oObj->GetKey()] = true;
  892. $this->iState = $oObj->GetState();
  893. $this->iAllowedCount++;
  894. }
  895. }
  896. else
  897. {
  898. $this->aAllowedIDs[$oObj->GetKey()] = false;
  899. }
  900. }
  901. }
  902. if ($this->iAllowedCount == $oSet->Count())
  903. {
  904. $iActionAllowed = UR_ALLOWED_YES;
  905. }
  906. if ($this->iAllowedCount == 0)
  907. {
  908. $iActionAllowed = UR_ALLOWED_NO;
  909. }
  910. return $iActionAllowed;
  911. }
  912. public function GetState()
  913. {
  914. return $this->iState;
  915. }
  916. }
  917. /**
  918. * Self-register extension to allow the automatic creation & update of CAS users
  919. *
  920. * @package iTopORM
  921. *
  922. */
  923. class CAS_SelfRegister implements iSelfRegister
  924. {
  925. /**
  926. * Called when no user is found in iTop for the corresponding 'name'. This method
  927. * can create/synchronize the User in iTop with an external source (such as AD/LDAP) on the fly
  928. * @param string $sName The CAS authenticated user name
  929. * @param string $sPassword Ignored
  930. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  931. * @param string $sAuthentication The authentication method used
  932. * @return bool true if the user is a valid one, false otherwise
  933. */
  934. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication)
  935. {
  936. if ($sLoginMode != 'cas') return false; // Must be authenticated via CAS
  937. $sCASMemberships = MetaModel::GetConfig()->Get('cas_memberof');
  938. $bFound = false;
  939. if (!empty($sCASMemberships))
  940. {
  941. if (phpCAS::hasAttribute('memberOf'))
  942. {
  943. // A list of groups is specified, the user must a be member of (at least) one of them to pass
  944. $aCASMemberships = array();
  945. $aTmp = explode(';', $sCASMemberships);
  946. setlocale(LC_ALL, "en_US.utf8"); // !!! WARNING: this is needed to have the iconv //TRANSLIT working fine below !!!
  947. foreach($aTmp as $sGroupName)
  948. {
  949. $aCASMemberships[] = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Just in case remove accents and spaces...
  950. }
  951. $aMemberOf = phpCAS::getAttribute('memberOf');
  952. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  953. $aFilteredGroupNames = array();
  954. foreach($aMemberOf as $sGroupName)
  955. {
  956. phpCAS::log("Info: user if a member of the group: ".$sGroupName);
  957. $sGroupName = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Remove accents and spaces as well
  958. $aFilteredGroupNames[] = $sGroupName;
  959. if (in_array($sGroupName, $aCASMemberships))
  960. {
  961. $bCASUserSynchro = MetaModel::GetConfig()->Get('cas_user_synchro');
  962. if ($bCASUserSynchro)
  963. {
  964. // If needed create a new user for this email/profile
  965. phpCAS::log('Info: cas_user_synchro is ON');
  966. $bFound = self::CreateCASUser(phpCAS::getUser(), $aMemberOf);
  967. }
  968. else
  969. {
  970. phpCAS::log('Info: cas_user_synchro is OFF');
  971. }
  972. $bFound = true;
  973. break;
  974. }
  975. }
  976. if(!$bFound)
  977. {
  978. phpCAS::log("User ".phpCAS::getUser().", none of his/her groups (".implode('; ', $aFilteredGroupNames).") match any of the required groups: ".implode('; ', $aCASMemberships));
  979. }
  980. }
  981. else
  982. {
  983. // Too bad, the user is not part of any of the group => not allowed
  984. phpCAS::log("No 'memberOf' attribute found for user ".phpCAS::getUser().". Are you using the SAML protocol (S1) ?");
  985. }
  986. }
  987. else
  988. {
  989. // No membership required, anybody will pass
  990. $bFound = true;
  991. }
  992. if (!$bFound)
  993. {
  994. // The user is not part of the allowed groups, => log out
  995. $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  996. $sCASLogoutUrl = MetaModel::GetConfig()->Get('cas_logout_redirect_service');
  997. if (empty($sCASLogoutUrl))
  998. {
  999. $sCASLogoutUrl = $sUrl;
  1000. }
  1001. phpCAS::logoutWithRedirectService($sCASLogoutUrl); // Redirects to the CAS logout page
  1002. // Will never return !
  1003. }
  1004. return $bFound;
  1005. }
  1006. /**
  1007. * Called after the user has been authenticated and found in iTop. This method can
  1008. * Update the user's definition (profiles...) on the fly to keep it in sync with an external source
  1009. * @param User $oUser The user to update/synchronize
  1010. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  1011. * @param string $sAuthentication The authentication method used
  1012. * @return void
  1013. */
  1014. public static function UpdateUser(User $oUser, $sLoginMode, $sAuthentication)
  1015. {
  1016. if (($sLoginMode == 'cas') && (phpCAS::hasAttribute('memberOf')))
  1017. {
  1018. $aMemberOf = phpCAS::getAttribute('memberOf');
  1019. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  1020. return self::SetProfilesFromCAS($oUser, $aMemberOf);
  1021. }
  1022. // No groups defined in CAS or not CAS at all: do nothing...
  1023. return true;
  1024. }
  1025. /**
  1026. * Helper method to create a CAS based user
  1027. * @param string $sEmail
  1028. * @param array $aGroups
  1029. * @return bool true on success, false otherwise
  1030. */
  1031. protected static function CreateCASUser($sEmail, $aGroups)
  1032. {
  1033. if (!MetaModel::IsValidClass('URP_Profiles'))
  1034. {
  1035. phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry.");
  1036. return false;
  1037. }
  1038. $oUser = MetaModel::GetObjectByName('UserExternal', $sEmail, false);
  1039. if ($oUser == null)
  1040. {
  1041. // Create the user, link it to a contact
  1042. phpCAS::log("Info: the user '$sEmail' does not exist. A new UserExternal will be created.");
  1043. $oSearch = new DBObjectSearch('Person');
  1044. $oSearch->AddCondition('email', $sEmail);
  1045. $oSet = new DBObjectSet($oSearch);
  1046. $iContactId = 0;
  1047. switch($oSet->Count())
  1048. {
  1049. case 0:
  1050. phpCAS::log("Error: found no contact with the email: '$sEmail'. Cannot create the user in iTop.");
  1051. return;
  1052. case 1:
  1053. $oContact = $oSet->Fetch();
  1054. $iContactId = $oContact->GetKey();
  1055. phpCAS::log("Info: Found 1 contact '".$oContact->GetName()."' (id=$iContactId) corresponding to the email '$sEmail'.");
  1056. break;
  1057. default:
  1058. phpCAS::log("Error: ".$oSet->Count()." contacts have the same email: '$sEmail'. Cannot create a user for this email.");
  1059. return;
  1060. }
  1061. $oUser = new UserExternal();
  1062. $oUser->Set('login', $sEmail);
  1063. $oUser->Set('contactid', $iContactId);
  1064. $oUser->Set('language', MetaModel::GetConfig()->GetDefaultLanguage());
  1065. }
  1066. else
  1067. {
  1068. phpCAS::log("Info: the user '$sEmail' already exists (id=".$oUser->GetKey().").");
  1069. }
  1070. // Now synchronize the profiles
  1071. if (!self::SetProfilesFromCAS($oUser, $Groups))
  1072. {
  1073. return false;
  1074. }
  1075. else
  1076. {
  1077. if ($oUser->IsNew() || $oUser->IsModified())
  1078. {
  1079. $oMyChange = MetaModel::NewObject("CMDBChange");
  1080. $oMyChange->Set("date", time());
  1081. $oMyChange->Set("userinfo", 'CAS/LDAP Synchro');
  1082. $oMyChange->DBInsert();
  1083. if ($oUser->IsNew())
  1084. {
  1085. $oUser->DBInsertTracked($oMyChange);
  1086. }
  1087. else
  1088. {
  1089. $oUser->DBUpdateTracked($oMyChange);
  1090. }
  1091. }
  1092. return true;
  1093. }
  1094. }
  1095. protected static function SetProfilesFromCAS($oUser, $Groups)
  1096. {
  1097. if (!MetaModel::IsValidClass('URP_Profiles'))
  1098. {
  1099. phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry.");
  1100. return false;
  1101. }
  1102. // read all the existing profiles
  1103. $oProfilesSearch = new DBObjectSearch('URP_Profiles');
  1104. $oProfilesSet = new DBObjectSet($oProfilesSearch);
  1105. $aAllProfiles = array();
  1106. while($oProfile = $oProfilesSet->Fetch())
  1107. {
  1108. $aAllProfiles[strtolower($oProfile->GetName())] = $oProfile->GetKey();
  1109. }
  1110. // Translate the CAS/LDAP group names into iTop profile names
  1111. $aProfiles = array();
  1112. $sPattern = MetaModel::GetConfig()->Get('cas_profile_pattern');
  1113. foreach($aGroups as $sGroupName)
  1114. {
  1115. if (preg_match($sPattern, $sGroupName, $aMatches))
  1116. {
  1117. if (array_key_exists(strtolower($aMatches[1]), $aAllProfiles))
  1118. {
  1119. $aProfiles[] = $aAllProfiles[strtolower($aMatches[1])];
  1120. }
  1121. else
  1122. {
  1123. phpCAS::log("Warning: {$aMatches[1]} is not a valid iTop profile (extracted from group name: '$sGroupName'). Ignored.");
  1124. }
  1125. }
  1126. }
  1127. if (count($aProfiles) == 0)
  1128. {
  1129. phpCAS::log("Error: no group name matches the pattern: '$sPattern'. The user '$sEmail' has no profiles in iTop, and therefore cannot be created.");
  1130. return false;
  1131. }
  1132. // Now synchronize the profiles
  1133. $oProfilesSet = DBObjectSet::FromScratch('URP_UserProfile');
  1134. foreach($aProfiles as $iProfileId)
  1135. {
  1136. $oLink = new URP_UserProfile();
  1137. $oLink->Set('profileid', $iProfileId);
  1138. $oLink->Set('reason', 'CAS/LDAP Synchro');
  1139. $oProfilesSet->AddObject($oLink);
  1140. }
  1141. $oUser->Set('profile_list', $oProfilesSet);
  1142. phpCAS::log("Info: the user $sEmail (id=".$oUser->GetKey().") now has the following profiles: '".implode("', '", $aProfiles)."'.");
  1143. return true;
  1144. }
  1145. /**
  1146. * Helper function to check if the supplied string is a litteral string or a regular expression pattern
  1147. * @param string $sCASPattern
  1148. * @return bool True if it's a regular expression pattern, false otherwise
  1149. */
  1150. protected static function IsPattern($sCASPattern)
  1151. {
  1152. if ((substr($sCASPattern, 0, 1) == '/') && (substr($sCASPattern, -1) == '/'))
  1153. {
  1154. // the string is enclosed by slashes, let's assume it's a pattern
  1155. return true;
  1156. }
  1157. else
  1158. {
  1159. return false;
  1160. }
  1161. }
  1162. }
  1163. // By default enable the 'CAS_SelfRegister' defined above
  1164. UserRights::SelectSelfRegister('CAS_SelfRegister');
  1165. ?>