userrights.class.inc.php 28 KB

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