userrights.class.inc.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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. * User management core API
  263. *
  264. * @package iTopORM
  265. */
  266. class UserRights
  267. {
  268. protected static $m_oAddOn;
  269. protected static $m_oUser;
  270. protected static $m_oRealUser;
  271. public static function SelectModule($sModuleName)
  272. {
  273. if (!class_exists($sModuleName))
  274. {
  275. throw new CoreException("Could not select this module, '$sModuleName' in not a valid class name");
  276. return;
  277. }
  278. if (!is_subclass_of($sModuleName, 'UserRightsAddOnAPI'))
  279. {
  280. throw new CoreException("Could not select this module, the class '$sModuleName' is not derived from UserRightsAddOnAPI");
  281. return;
  282. }
  283. self::$m_oAddOn = new $sModuleName;
  284. self::$m_oAddOn->Init();
  285. self::$m_oUser = null;
  286. self::$m_oRealUser = null;
  287. }
  288. public static function GetModuleInstance()
  289. {
  290. return self::$m_oAddOn;
  291. }
  292. // Installation: create the very first user
  293. public static function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US')
  294. {
  295. $bRes = self::$m_oAddOn->CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage);
  296. self::FlushPrivileges(true /* reset admin cache */);
  297. return $bRes;
  298. }
  299. protected static function IsLoggedIn()
  300. {
  301. if (self::$m_oUser == null)
  302. {
  303. return false;
  304. }
  305. else
  306. {
  307. return true;
  308. }
  309. }
  310. public static function Login($sName, $sAuthentication = 'any')
  311. {
  312. $oUser = self::FindUser($sName, $sAuthentication);
  313. if (is_null($oUser))
  314. {
  315. return false;
  316. }
  317. self::$m_oUser = $oUser;
  318. Dict::SetUserLanguage(self::GetUserLanguage());
  319. return true;
  320. }
  321. public static function CheckCredentials($sName, $sPassword, $sAuthentication = 'any')
  322. {
  323. $oUser = self::FindUser($sName, $sAuthentication);
  324. if (is_null($oUser))
  325. {
  326. return false;
  327. }
  328. if (!$oUser->CheckCredentials($sPassword))
  329. {
  330. return false;
  331. }
  332. return true;
  333. }
  334. public static function TrustWebServerContext()
  335. {
  336. if (!is_null(self::$m_oUser))
  337. {
  338. return self::$m_oUser->TrustWebServerContext();
  339. }
  340. else
  341. {
  342. return false;
  343. }
  344. }
  345. public static function CanChangePassword()
  346. {
  347. if (MetaModel::DBIsReadOnly())
  348. {
  349. return false;
  350. }
  351. if (!is_null(self::$m_oUser))
  352. {
  353. return self::$m_oUser->CanChangePassword();
  354. }
  355. else
  356. {
  357. return false;
  358. }
  359. }
  360. public static function CanLogOff()
  361. {
  362. if (!is_null(self::$m_oUser))
  363. {
  364. return self::$m_oUser->CanLogOff();
  365. }
  366. else
  367. {
  368. return false;
  369. }
  370. }
  371. public static function ChangePassword($sOldPassword, $sNewPassword, $sName = '')
  372. {
  373. if (empty($sName))
  374. {
  375. $oUser = self::$m_oUser;
  376. }
  377. else
  378. {
  379. // find the id out of the login string
  380. $oUser = self::FindUser($sName);
  381. }
  382. if (is_null($oUser))
  383. {
  384. return false;
  385. }
  386. else
  387. {
  388. return $oUser->ChangePassword($sOldPassword, $sNewPassword);
  389. }
  390. }
  391. public static function Impersonate($sName, $sPassword)
  392. {
  393. if (!self::CheckLogin()) return false;
  394. $oUser = self::FindUser($sName);
  395. if (is_null($oUser))
  396. {
  397. return false;
  398. }
  399. if (!$oUser->CheckCredentials($sPassword))
  400. {
  401. return false;
  402. }
  403. self::$m_oRealUser = self::$m_oUser;
  404. self::$m_oUser = $oUser;
  405. Dict::SetUserLanguage(self::GetUserLanguage());
  406. return true;
  407. }
  408. public static function GetUser()
  409. {
  410. if (is_null(self::$m_oUser))
  411. {
  412. return '';
  413. }
  414. else
  415. {
  416. return self::$m_oUser->Get('login');
  417. }
  418. }
  419. public static function GetUserObject()
  420. {
  421. if (is_null(self::$m_oUser))
  422. {
  423. return null;
  424. }
  425. else
  426. {
  427. return self::$m_oUser;
  428. }
  429. }
  430. public static function GetUserLanguage()
  431. {
  432. if (is_null(self::$m_oUser))
  433. {
  434. return 'EN US';
  435. }
  436. else
  437. {
  438. return self::$m_oUser->Get('language');
  439. }
  440. }
  441. public static function GetUserId($sName = '')
  442. {
  443. if (empty($sName))
  444. {
  445. // return current user id
  446. if (is_null(self::$m_oUser))
  447. {
  448. return null;
  449. }
  450. return self::$m_oUser->GetKey();
  451. }
  452. else
  453. {
  454. // find the id out of the login string
  455. $oUser = self::$m_oAddOn->FindUser($sName);
  456. if (is_null($oUser))
  457. {
  458. return null;
  459. }
  460. return $oUser->GetKey();
  461. }
  462. }
  463. public static function GetContactId($sName = '')
  464. {
  465. if (empty($sName))
  466. {
  467. $oUser = self::$m_oUser;
  468. }
  469. else
  470. {
  471. $oUser = FindUser($sName);
  472. }
  473. if (is_null($oUser))
  474. {
  475. return '';
  476. }
  477. if (!MetaModel::IsValidAttCode(get_class($oUser), 'contactid'))
  478. {
  479. return '';
  480. }
  481. return $oUser->Get('contactid');
  482. }
  483. // Render the user name in best effort mode
  484. public static function GetUserFriendlyName($sName = '')
  485. {
  486. if (empty($sName))
  487. {
  488. $oUser = self::$m_oUser;
  489. }
  490. else
  491. {
  492. $oUser = FindUser($sName);
  493. }
  494. if (is_null($oUser))
  495. {
  496. return '';
  497. }
  498. return $oUser->GetFriendlyName();
  499. }
  500. public static function IsImpersonated()
  501. {
  502. if (is_null(self::$m_oRealUser))
  503. {
  504. return false;
  505. }
  506. return true;
  507. }
  508. public static function GetRealUser()
  509. {
  510. if (is_null(self::$m_oRealUser))
  511. {
  512. return '';
  513. }
  514. return self::$m_oRealUser->Get('login');
  515. }
  516. public static function GetRealUserId()
  517. {
  518. if (is_null(self::$m_oRealUser))
  519. {
  520. return '';
  521. }
  522. return self::$m_oRealUser->GetKey();
  523. }
  524. public static function GetRealUserFriendlyName()
  525. {
  526. if (is_null(self::$m_oRealUser))
  527. {
  528. return '';
  529. }
  530. return self::$m_oRealUser->GetFriendlyName();
  531. }
  532. protected static function CheckLogin()
  533. {
  534. if (!self::IsLoggedIn())
  535. {
  536. //throw new UserRightException('No user logged in', array());
  537. return false;
  538. }
  539. return true;
  540. }
  541. public static function GetSelectFilter($sClass)
  542. {
  543. // When initializing, we need to let everything pass trough
  544. if (!self::CheckLogin()) return true;
  545. if (self::IsAdministrator()) return true;
  546. // Portal users actions are limited by the portal page...
  547. if (self::IsPortalUser()) return true;
  548. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  549. {
  550. return self::$m_oAddOn->GetSelectFilter(self::$m_oUser, $sClass);
  551. }
  552. else
  553. {
  554. return true;
  555. }
  556. }
  557. public static function IsActionAllowed($sClass, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  558. {
  559. // When initializing, we need to let everything pass trough
  560. if (!self::CheckLogin()) return true;
  561. if (MetaModel::DBIsReadOnly())
  562. {
  563. if ($iActionCode == UR_ACTION_MODIFY) return false;
  564. if ($iActionCode == UR_ACTION_DELETE) return false;
  565. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  566. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  567. }
  568. if (self::IsAdministrator($oUser)) return true;
  569. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  570. {
  571. // #@# Temporary?????
  572. // The read access is controlled in MetaModel::MakeSelectQuery()
  573. if ($iActionCode == UR_ACTION_READ) return true;
  574. if (is_null($oUser))
  575. {
  576. $oUser = self::$m_oUser;
  577. }
  578. return self::$m_oAddOn->IsActionAllowed($oUser, $sClass, $iActionCode, $oInstanceSet);
  579. }
  580. elseif(($iActionCode == UR_ACTION_READ) && MetaModel::HasCategory($sClass, 'view_in_gui'))
  581. {
  582. return true;
  583. }
  584. else
  585. {
  586. // Other classes could be edited/listed by the administrators
  587. return false;
  588. }
  589. }
  590. public static function IsStimulusAllowed($sClass, $sStimulusCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  591. {
  592. // When initializing, we need to let everything pass trough
  593. if (!self::CheckLogin()) return true;
  594. if (MetaModel::DBIsReadOnly())
  595. {
  596. return false;
  597. }
  598. if (self::IsAdministrator($oUser)) return true;
  599. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  600. {
  601. if (is_null($oUser))
  602. {
  603. $oUser = self::$m_oUser;
  604. }
  605. return self::$m_oAddOn->IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet);
  606. }
  607. else
  608. {
  609. // Other classes could be edited/listed by the administrators
  610. return false;
  611. }
  612. }
  613. public static function IsActionAllowedOnAttribute($sClass, $sAttCode, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  614. {
  615. // When initializing, we need to let everything pass trough
  616. if (!self::CheckLogin()) return true;
  617. if (MetaModel::DBIsReadOnly())
  618. {
  619. if ($iActionCode == UR_ACTION_MODIFY) return false;
  620. if ($iActionCode == UR_ACTION_DELETE) return false;
  621. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  622. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  623. }
  624. if (self::IsAdministrator($oUser)) return true;
  625. // this module is forbidden for non admins
  626. if (MetaModel::HasCategory($sClass, 'addon/userrights')) return false;
  627. // the rest is allowed (#@# to be improved)
  628. if (!MetaModel::HasCategory($sClass, 'bizmodel')) return true;
  629. if (is_null($oUser))
  630. {
  631. $oUser = self::$m_oUser;
  632. }
  633. return self::$m_oAddOn->IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, $oInstanceSet);
  634. }
  635. static $m_aAdmins = array();
  636. public static function IsAdministrator($oUser = null)
  637. {
  638. if (!self::CheckLogin()) return false;
  639. if (is_null($oUser))
  640. {
  641. $oUser = self::$m_oUser;
  642. }
  643. $iUser = $oUser->GetKey();
  644. if (!isset(self::$m_aAdmins[$iUser]))
  645. {
  646. self::$m_aAdmins[$iUser] = self::$m_oAddOn->IsAdministrator($oUser);
  647. }
  648. return self::$m_aAdmins[$iUser];
  649. }
  650. static $m_aPortalUsers = array();
  651. public static function IsPortalUser($oUser = null)
  652. {
  653. if (!self::CheckLogin()) return false;
  654. if (is_null($oUser))
  655. {
  656. $oUser = self::$m_oUser;
  657. }
  658. $iUser = $oUser->GetKey();
  659. if (!isset(self::$m_aPortalUsers[$iUser]))
  660. {
  661. self::$m_aPortalUsers[$iUser] = self::$m_oAddOn->IsPortalUser($oUser);
  662. }
  663. return self::$m_aPortalUsers[$iUser];
  664. }
  665. /**
  666. * Reset cached data
  667. * @param Bool Reset admin cache as well
  668. * @return void
  669. */
  670. // Reset cached data
  671. //
  672. public static function FlushPrivileges($bResetAdminCache = false)
  673. {
  674. if ($bResetAdminCache)
  675. {
  676. self::$m_aAdmins = array();
  677. }
  678. return self::$m_oAddOn->FlushPrivileges();
  679. }
  680. static $m_aCacheUsers;
  681. /**
  682. * Find a user based on its login and its type of authentication
  683. * @param string $sLogin Login/identifier of the user
  684. * @param string $sAuthentication Type of authentication used: internal|external|any
  685. * @return User The found user or null
  686. */
  687. protected static function FindUser($sLogin, $sAuthentication = 'any')
  688. {
  689. if ($sAuthentication == 'any')
  690. {
  691. $oUser = self::FindUser($sLogin, 'internal');
  692. if ($oUser == null)
  693. {
  694. $oUser = self::FindUser($sLogin, 'external');
  695. }
  696. }
  697. else
  698. {
  699. if (!isset(self::$m_aCacheUsers))
  700. {
  701. self::$m_aCacheUsers = array('internal' => array(), 'external' => array());
  702. }
  703. if (!isset(self::$m_aCacheUsers[$sAuthentication][$sLogin]))
  704. {
  705. switch($sAuthentication)
  706. {
  707. case 'external':
  708. $sBaseClass = 'UserExternal';
  709. break;
  710. case 'internal':
  711. $sBaseClass = 'UserInternal';
  712. break;
  713. default:
  714. echo "<p>sAuthentication = $sAuthentication</p>\n";
  715. assert(false); // should never happen
  716. }
  717. $oSearch = DBObjectSearch::FromOQL("SELECT $sBaseClass WHERE login = :login");
  718. $oSet = new DBObjectSet($oSearch, array(), array('login' => $sLogin));
  719. $oUser = $oSet->fetch();
  720. self::$m_aCacheUsers[$sAuthentication][$sLogin] = $oUser;
  721. }
  722. $oUser = self::$m_aCacheUsers[$sAuthentication][$sLogin];
  723. }
  724. return $oUser;
  725. }
  726. }
  727. /**
  728. * Helper class to get the number/list of items for which a given action is allowed/possible
  729. */
  730. class ActionChecker
  731. {
  732. var $oFilter;
  733. var $iActionCode;
  734. var $iAllowedCount = null;
  735. var $aAllowedIDs = null;
  736. public function __construct(DBObjectSearch $oFilter, $iActionCode)
  737. {
  738. $this->oFilter = $oFilter;
  739. $this->iActionCode = $iActionCode;
  740. $this->iAllowedCount = null;
  741. $this->aAllowedIDs = null;
  742. }
  743. /**
  744. * returns the number of objects for which the action is allowed
  745. * @return integer The number of "allowed" objects 0..N
  746. */
  747. public function GetAllowedCount()
  748. {
  749. if ($this->iAllowedCount == null) $this->CheckObjects();
  750. return $this->iAllowedCount;
  751. }
  752. /**
  753. * If IsAllowed returned UR_ALLOWED_DEPENDS, this methods returns
  754. * an array of ObjKey => Status (true|false)
  755. * @return array
  756. */
  757. public function GetAllowedIDs()
  758. {
  759. if ($this->aAllowedIDs == null) $this->IsAllowed();
  760. return $this->aAllowedIDs;
  761. }
  762. /**
  763. * Check if the speficied stimulus is allowed for the set of objects
  764. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  765. */
  766. public function IsAllowed()
  767. {
  768. $sClass = $this->oFilter->GetClass();
  769. $oSet = new DBObjectSet($this->oFilter);
  770. $iActionAllowed = UserRights::IsActionAllowed($sClass, $oSet, $this->iActionCode);
  771. if ($iActionAllowed == UR_ALLOWED_DEPENDS)
  772. {
  773. // Check for each object if the action is allowed or not
  774. $this->aAllowedIDs = array();
  775. $oSet->Rewind();
  776. $this->iAllowedCount = 0;
  777. while($oObj = $oSet->Fetch())
  778. {
  779. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  780. if (UserRights::IsActionAllowed($sClass, $this->iActionCode, $oObjSet) == UR_ALLOWED_NO)
  781. {
  782. $this->aAllowedIDs[$oObj->GetKey()] = false;
  783. }
  784. else
  785. {
  786. // Assume UR_ALLOWED_YES, since there is just one object !
  787. $this->aAllowedIDs[$oObj->GetKey()] = true;
  788. $this->iAllowedCount++;
  789. }
  790. }
  791. }
  792. else if ($iActionAllowed == UR_ALLOWED_YES)
  793. {
  794. $this->iAllowedCount = $oSet->Count();
  795. $this->aAllowedIDs = array(); // Optimization: not filled when Ok for all objects
  796. }
  797. else // UR_ALLOWED_NO
  798. {
  799. $this->iAllowedCount = 0;
  800. $this->aAllowedIDs = array();
  801. }
  802. return $iActionAllowed;
  803. }
  804. }
  805. /**
  806. * Helper class to get the number/list of items for which a given stimulus can be applied (allowed & possible)
  807. */
  808. class StimulusChecker extends ActionChecker
  809. {
  810. var $sState = null;
  811. public function __construct(DBObjectSearch $oFilter, $sState, $iStimulusCode)
  812. {
  813. parent::__construct($oFilter, $iStimulusCode);
  814. $this->sState = $sState;
  815. }
  816. /**
  817. * Check if the speficied stimulus is allowed for the set of objects
  818. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  819. */
  820. public function IsAllowed()
  821. {
  822. $sClass = $this->oFilter->GetClass();
  823. $oSet = new DBObjectSet($this->oFilter);
  824. $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $oSet, $this->iActionCode);
  825. if ($iActionAllowed == UR_ALLOWED_NO)
  826. {
  827. $this->iAllowedCount = 0;
  828. $this->aAllowedIDs = array();
  829. }
  830. else // Even if UR_ALLOWED_YES, we need to check if each object is in the appropriate state
  831. {
  832. // Hmmm, may not be needed right now because we limit the "multiple" action to object in
  833. // the same state... may be useful later on if we want to extend this behavior...
  834. // Check for each object if the action is allowed or not
  835. $this->aAllowedIDs = array();
  836. $oSet->Rewind();
  837. $iAllowedCount = 0;
  838. $iActionAllowed = UR_ALLOWED_DEPENDS;
  839. while($oObj = $oSet->Fetch())
  840. {
  841. $aTransitions = $oObj->EnumTransitions();
  842. if (array_key_exists($this->iActionCode, $aTransitions))
  843. {
  844. // Temporary optimization possible: since the current implementation
  845. // of IsActionAllowed does not perform a 'per instance' check, we could
  846. // skip this second validation phase and assume it would return UR_ALLOWED_YES
  847. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  848. if (UserRights::IsActionAllowed($sClass, $this->iActionCode, $oObjSet) == UR_ALLOWED_NO)
  849. {
  850. $this->aAllowedIDs[$oObj->GetKey()] = false;
  851. }
  852. else
  853. {
  854. // Assume UR_ALLOWED_YES, since there is just one object !
  855. $this->aAllowedIDs[$oObj->GetKey()] = true;
  856. $this->iState = $oObj->GetState();
  857. $this->iAllowedCount++;
  858. }
  859. }
  860. else
  861. {
  862. $this->aAllowedIDs[$oObj->GetKey()] = false;
  863. }
  864. }
  865. }
  866. if ($this->iAllowedCount == $oSet->Count())
  867. {
  868. $iActionAllowed = UR_ALLOWED_YES;
  869. }
  870. if ($this->iAllowedCount == 0)
  871. {
  872. $iActionAllowed = UR_ALLOWED_NO;
  873. }
  874. return $iActionAllowed;
  875. }
  876. public function GetState()
  877. {
  878. return $this->iState;
  879. }
  880. }
  881. ?>