userrights.class.inc.php 42 KB

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