PhpManager.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\rbac;
  8. use Yii;
  9. use yii\base\InvalidArgumentException;
  10. use yii\base\InvalidCallException;
  11. use yii\helpers\VarDumper;
  12. /**
  13. * PhpManager represents an authorization manager that stores authorization
  14. * information in terms of a PHP script file.
  15. *
  16. * The authorization data will be saved to and loaded from three files
  17. * specified by [[itemFile]], [[assignmentFile]] and [[ruleFile]].
  18. *
  19. * PhpManager is mainly suitable for authorization data that is not too big
  20. * (for example, the authorization data for a personal blog system).
  21. * Use [[DbManager]] for more complex authorization data.
  22. *
  23. * Note that PhpManager is not compatible with facebooks [HHVM](http://hhvm.com/) because
  24. * it relies on writing php files and including them afterwards which is not supported by HHVM.
  25. *
  26. * For more details and usage information on PhpManager, see the [guide article on security authorization](guide:security-authorization).
  27. *
  28. * @author Qiang Xue <qiang.xue@gmail.com>
  29. * @author Alexander Kochetov <creocoder@gmail.com>
  30. * @author Christophe Boulain <christophe.boulain@gmail.com>
  31. * @author Alexander Makarov <sam@rmcreative.ru>
  32. * @since 2.0
  33. */
  34. class PhpManager extends BaseManager
  35. {
  36. /**
  37. * @var string the path of the PHP script that contains the authorization items.
  38. * This can be either a file path or a [path alias](guide:concept-aliases) to the file.
  39. * Make sure this file is writable by the Web server process if the authorization needs to be changed online.
  40. * @see loadFromFile()
  41. * @see saveToFile()
  42. */
  43. public $itemFile = '@app/rbac/items.php';
  44. /**
  45. * @var string the path of the PHP script that contains the authorization assignments.
  46. * This can be either a file path or a [path alias](guide:concept-aliases) to the file.
  47. * Make sure this file is writable by the Web server process if the authorization needs to be changed online.
  48. * @see loadFromFile()
  49. * @see saveToFile()
  50. */
  51. public $assignmentFile = '@app/rbac/assignments.php';
  52. /**
  53. * @var string the path of the PHP script that contains the authorization rules.
  54. * This can be either a file path or a [path alias](guide:concept-aliases) to the file.
  55. * Make sure this file is writable by the Web server process if the authorization needs to be changed online.
  56. * @see loadFromFile()
  57. * @see saveToFile()
  58. */
  59. public $ruleFile = '@app/rbac/rules.php';
  60. /**
  61. * @var Item[]
  62. */
  63. protected $items = []; // itemName => item
  64. /**
  65. * @var array
  66. */
  67. protected $children = []; // itemName, childName => child
  68. /**
  69. * @var array
  70. */
  71. protected $assignments = []; // userId, itemName => assignment
  72. /**
  73. * @var Rule[]
  74. */
  75. protected $rules = []; // ruleName => rule
  76. /**
  77. * Initializes the application component.
  78. * This method overrides parent implementation by loading the authorization data
  79. * from PHP script.
  80. */
  81. public function init()
  82. {
  83. parent::init();
  84. $this->itemFile = Yii::getAlias($this->itemFile);
  85. $this->assignmentFile = Yii::getAlias($this->assignmentFile);
  86. $this->ruleFile = Yii::getAlias($this->ruleFile);
  87. $this->load();
  88. }
  89. /**
  90. * {@inheritdoc}
  91. */
  92. public function checkAccess($userId, $permissionName, $params = [])
  93. {
  94. $assignments = $this->getAssignments($userId);
  95. if ($this->hasNoAssignments($assignments)) {
  96. return false;
  97. }
  98. return $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
  99. }
  100. /**
  101. * {@inheritdoc}
  102. */
  103. public function getAssignments($userId)
  104. {
  105. return isset($this->assignments[$userId]) ? $this->assignments[$userId] : [];
  106. }
  107. /**
  108. * Performs access check for the specified user.
  109. * This method is internally called by [[checkAccess()]].
  110. *
  111. * @param string|int $user the user ID. This should can be either an integer or a string representing
  112. * the unique identifier of a user. See [[\yii\web\User::id]].
  113. * @param string $itemName the name of the operation that need access check
  114. * @param array $params name-value pairs that would be passed to rules associated
  115. * with the tasks and roles assigned to the user. A param with name 'user' is added to this array,
  116. * which holds the value of `$userId`.
  117. * @param Assignment[] $assignments the assignments to the specified user
  118. * @return bool whether the operations can be performed by the user.
  119. */
  120. protected function checkAccessRecursive($user, $itemName, $params, $assignments)
  121. {
  122. if (!isset($this->items[$itemName])) {
  123. return false;
  124. }
  125. /* @var $item Item */
  126. $item = $this->items[$itemName];
  127. Yii::debug($item instanceof Role ? "Checking role: $itemName" : "Checking permission : $itemName", __METHOD__);
  128. if (!$this->executeRule($user, $item, $params)) {
  129. return false;
  130. }
  131. if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
  132. return true;
  133. }
  134. foreach ($this->children as $parentName => $children) {
  135. if (isset($children[$itemName]) && $this->checkAccessRecursive($user, $parentName, $params, $assignments)) {
  136. return true;
  137. }
  138. }
  139. return false;
  140. }
  141. /**
  142. * {@inheritdoc}
  143. * @since 2.0.8
  144. */
  145. public function canAddChild($parent, $child)
  146. {
  147. return !$this->detectLoop($parent, $child);
  148. }
  149. /**
  150. * {@inheritdoc}
  151. */
  152. public function addChild($parent, $child)
  153. {
  154. if (!isset($this->items[$parent->name], $this->items[$child->name])) {
  155. throw new InvalidArgumentException("Either '{$parent->name}' or '{$child->name}' does not exist.");
  156. }
  157. if ($parent->name === $child->name) {
  158. throw new InvalidArgumentException("Cannot add '{$parent->name} ' as a child of itself.");
  159. }
  160. if ($parent instanceof Permission && $child instanceof Role) {
  161. throw new InvalidArgumentException('Cannot add a role as a child of a permission.');
  162. }
  163. if ($this->detectLoop($parent, $child)) {
  164. throw new InvalidCallException("Cannot add '{$child->name}' as a child of '{$parent->name}'. A loop has been detected.");
  165. }
  166. if (isset($this->children[$parent->name][$child->name])) {
  167. throw new InvalidCallException("The item '{$parent->name}' already has a child '{$child->name}'.");
  168. }
  169. $this->children[$parent->name][$child->name] = $this->items[$child->name];
  170. $this->saveItems();
  171. return true;
  172. }
  173. /**
  174. * Checks whether there is a loop in the authorization item hierarchy.
  175. *
  176. * @param Item $parent parent item
  177. * @param Item $child the child item that is to be added to the hierarchy
  178. * @return bool whether a loop exists
  179. */
  180. protected function detectLoop($parent, $child)
  181. {
  182. if ($child->name === $parent->name) {
  183. return true;
  184. }
  185. if (!isset($this->children[$child->name], $this->items[$parent->name])) {
  186. return false;
  187. }
  188. foreach ($this->children[$child->name] as $grandchild) {
  189. /* @var $grandchild Item */
  190. if ($this->detectLoop($parent, $grandchild)) {
  191. return true;
  192. }
  193. }
  194. return false;
  195. }
  196. /**
  197. * {@inheritdoc}
  198. */
  199. public function removeChild($parent, $child)
  200. {
  201. if (isset($this->children[$parent->name][$child->name])) {
  202. unset($this->children[$parent->name][$child->name]);
  203. $this->saveItems();
  204. return true;
  205. }
  206. return false;
  207. }
  208. /**
  209. * {@inheritdoc}
  210. */
  211. public function removeChildren($parent)
  212. {
  213. if (isset($this->children[$parent->name])) {
  214. unset($this->children[$parent->name]);
  215. $this->saveItems();
  216. return true;
  217. }
  218. return false;
  219. }
  220. /**
  221. * {@inheritdoc}
  222. */
  223. public function hasChild($parent, $child)
  224. {
  225. return isset($this->children[$parent->name][$child->name]);
  226. }
  227. /**
  228. * {@inheritdoc}
  229. */
  230. public function assign($role, $userId)
  231. {
  232. if (!isset($this->items[$role->name])) {
  233. throw new InvalidArgumentException("Unknown role '{$role->name}'.");
  234. } elseif (isset($this->assignments[$userId][$role->name])) {
  235. throw new InvalidArgumentException("Authorization item '{$role->name}' has already been assigned to user '$userId'.");
  236. }
  237. $this->assignments[$userId][$role->name] = new Assignment([
  238. 'userId' => $userId,
  239. 'roleName' => $role->name,
  240. 'createdAt' => time(),
  241. ]);
  242. $this->saveAssignments();
  243. return $this->assignments[$userId][$role->name];
  244. }
  245. /**
  246. * {@inheritdoc}
  247. */
  248. public function revoke($role, $userId)
  249. {
  250. if (isset($this->assignments[$userId][$role->name])) {
  251. unset($this->assignments[$userId][$role->name]);
  252. $this->saveAssignments();
  253. return true;
  254. }
  255. return false;
  256. }
  257. /**
  258. * {@inheritdoc}
  259. */
  260. public function revokeAll($userId)
  261. {
  262. if (isset($this->assignments[$userId]) && is_array($this->assignments[$userId])) {
  263. foreach ($this->assignments[$userId] as $itemName => $value) {
  264. unset($this->assignments[$userId][$itemName]);
  265. }
  266. $this->saveAssignments();
  267. return true;
  268. }
  269. return false;
  270. }
  271. /**
  272. * {@inheritdoc}
  273. */
  274. public function getAssignment($roleName, $userId)
  275. {
  276. return isset($this->assignments[$userId][$roleName]) ? $this->assignments[$userId][$roleName] : null;
  277. }
  278. /**
  279. * {@inheritdoc}
  280. */
  281. public function getItems($type)
  282. {
  283. $items = [];
  284. foreach ($this->items as $name => $item) {
  285. /* @var $item Item */
  286. if ($item->type == $type) {
  287. $items[$name] = $item;
  288. }
  289. }
  290. return $items;
  291. }
  292. /**
  293. * {@inheritdoc}
  294. */
  295. public function removeItem($item)
  296. {
  297. if (isset($this->items[$item->name])) {
  298. foreach ($this->children as &$children) {
  299. unset($children[$item->name]);
  300. }
  301. foreach ($this->assignments as &$assignments) {
  302. unset($assignments[$item->name]);
  303. }
  304. unset($this->items[$item->name]);
  305. $this->saveItems();
  306. $this->saveAssignments();
  307. return true;
  308. }
  309. return false;
  310. }
  311. /**
  312. * {@inheritdoc}
  313. */
  314. public function getItem($name)
  315. {
  316. return isset($this->items[$name]) ? $this->items[$name] : null;
  317. }
  318. /**
  319. * {@inheritdoc}
  320. */
  321. public function updateRule($name, $rule)
  322. {
  323. if ($rule->name !== $name) {
  324. unset($this->rules[$name]);
  325. }
  326. $this->rules[$rule->name] = $rule;
  327. $this->saveRules();
  328. return true;
  329. }
  330. /**
  331. * {@inheritdoc}
  332. */
  333. public function getRule($name)
  334. {
  335. return isset($this->rules[$name]) ? $this->rules[$name] : null;
  336. }
  337. /**
  338. * {@inheritdoc}
  339. */
  340. public function getRules()
  341. {
  342. return $this->rules;
  343. }
  344. /**
  345. * {@inheritdoc}
  346. * The roles returned by this method include the roles assigned via [[$defaultRoles]].
  347. */
  348. public function getRolesByUser($userId)
  349. {
  350. $roles = $this->getDefaultRoleInstances();
  351. foreach ($this->getAssignments($userId) as $name => $assignment) {
  352. $role = $this->items[$assignment->roleName];
  353. if ($role->type === Item::TYPE_ROLE) {
  354. $roles[$name] = $role;
  355. }
  356. }
  357. return $roles;
  358. }
  359. /**
  360. * {@inheritdoc}
  361. */
  362. public function getChildRoles($roleName)
  363. {
  364. $role = $this->getRole($roleName);
  365. if ($role === null) {
  366. throw new InvalidArgumentException("Role \"$roleName\" not found.");
  367. }
  368. $result = [];
  369. $this->getChildrenRecursive($roleName, $result);
  370. $roles = [$roleName => $role];
  371. $roles += array_filter($this->getRoles(), function (Role $roleItem) use ($result) {
  372. return array_key_exists($roleItem->name, $result);
  373. });
  374. return $roles;
  375. }
  376. /**
  377. * {@inheritdoc}
  378. */
  379. public function getPermissionsByRole($roleName)
  380. {
  381. $result = [];
  382. $this->getChildrenRecursive($roleName, $result);
  383. if (empty($result)) {
  384. return [];
  385. }
  386. $permissions = [];
  387. foreach (array_keys($result) as $itemName) {
  388. if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
  389. $permissions[$itemName] = $this->items[$itemName];
  390. }
  391. }
  392. return $permissions;
  393. }
  394. /**
  395. * Recursively finds all children and grand children of the specified item.
  396. *
  397. * @param string $name the name of the item whose children are to be looked for.
  398. * @param array $result the children and grand children (in array keys)
  399. */
  400. protected function getChildrenRecursive($name, &$result)
  401. {
  402. if (isset($this->children[$name])) {
  403. foreach ($this->children[$name] as $child) {
  404. $result[$child->name] = true;
  405. $this->getChildrenRecursive($child->name, $result);
  406. }
  407. }
  408. }
  409. /**
  410. * {@inheritdoc}
  411. */
  412. public function getPermissionsByUser($userId)
  413. {
  414. $directPermission = $this->getDirectPermissionsByUser($userId);
  415. $inheritedPermission = $this->getInheritedPermissionsByUser($userId);
  416. return array_merge($directPermission, $inheritedPermission);
  417. }
  418. /**
  419. * Returns all permissions that are directly assigned to user.
  420. * @param string|int $userId the user ID (see [[\yii\web\User::id]])
  421. * @return Permission[] all direct permissions that the user has. The array is indexed by the permission names.
  422. * @since 2.0.7
  423. */
  424. protected function getDirectPermissionsByUser($userId)
  425. {
  426. $permissions = [];
  427. foreach ($this->getAssignments($userId) as $name => $assignment) {
  428. $permission = $this->items[$assignment->roleName];
  429. if ($permission->type === Item::TYPE_PERMISSION) {
  430. $permissions[$name] = $permission;
  431. }
  432. }
  433. return $permissions;
  434. }
  435. /**
  436. * Returns all permissions that the user inherits from the roles assigned to him.
  437. * @param string|int $userId the user ID (see [[\yii\web\User::id]])
  438. * @return Permission[] all inherited permissions that the user has. The array is indexed by the permission names.
  439. * @since 2.0.7
  440. */
  441. protected function getInheritedPermissionsByUser($userId)
  442. {
  443. $assignments = $this->getAssignments($userId);
  444. $result = [];
  445. foreach (array_keys($assignments) as $roleName) {
  446. $this->getChildrenRecursive($roleName, $result);
  447. }
  448. if (empty($result)) {
  449. return [];
  450. }
  451. $permissions = [];
  452. foreach (array_keys($result) as $itemName) {
  453. if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
  454. $permissions[$itemName] = $this->items[$itemName];
  455. }
  456. }
  457. return $permissions;
  458. }
  459. /**
  460. * {@inheritdoc}
  461. */
  462. public function getChildren($name)
  463. {
  464. return isset($this->children[$name]) ? $this->children[$name] : [];
  465. }
  466. /**
  467. * {@inheritdoc}
  468. */
  469. public function removeAll()
  470. {
  471. $this->children = [];
  472. $this->items = [];
  473. $this->assignments = [];
  474. $this->rules = [];
  475. $this->save();
  476. }
  477. /**
  478. * {@inheritdoc}
  479. */
  480. public function removeAllPermissions()
  481. {
  482. $this->removeAllItems(Item::TYPE_PERMISSION);
  483. }
  484. /**
  485. * {@inheritdoc}
  486. */
  487. public function removeAllRoles()
  488. {
  489. $this->removeAllItems(Item::TYPE_ROLE);
  490. }
  491. /**
  492. * Removes all auth items of the specified type.
  493. * @param int $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE)
  494. */
  495. protected function removeAllItems($type)
  496. {
  497. $names = [];
  498. foreach ($this->items as $name => $item) {
  499. if ($item->type == $type) {
  500. unset($this->items[$name]);
  501. $names[$name] = true;
  502. }
  503. }
  504. if (empty($names)) {
  505. return;
  506. }
  507. foreach ($this->assignments as $i => $assignments) {
  508. foreach ($assignments as $n => $assignment) {
  509. if (isset($names[$assignment->roleName])) {
  510. unset($this->assignments[$i][$n]);
  511. }
  512. }
  513. }
  514. foreach ($this->children as $name => $children) {
  515. if (isset($names[$name])) {
  516. unset($this->children[$name]);
  517. } else {
  518. foreach ($children as $childName => $item) {
  519. if (isset($names[$childName])) {
  520. unset($children[$childName]);
  521. }
  522. }
  523. $this->children[$name] = $children;
  524. }
  525. }
  526. $this->saveItems();
  527. }
  528. /**
  529. * {@inheritdoc}
  530. */
  531. public function removeAllRules()
  532. {
  533. foreach ($this->items as $item) {
  534. $item->ruleName = null;
  535. }
  536. $this->rules = [];
  537. $this->saveRules();
  538. }
  539. /**
  540. * {@inheritdoc}
  541. */
  542. public function removeAllAssignments()
  543. {
  544. $this->assignments = [];
  545. $this->saveAssignments();
  546. }
  547. /**
  548. * {@inheritdoc}
  549. */
  550. protected function removeRule($rule)
  551. {
  552. if (isset($this->rules[$rule->name])) {
  553. unset($this->rules[$rule->name]);
  554. foreach ($this->items as $item) {
  555. if ($item->ruleName === $rule->name) {
  556. $item->ruleName = null;
  557. }
  558. }
  559. $this->saveRules();
  560. return true;
  561. }
  562. return false;
  563. }
  564. /**
  565. * {@inheritdoc}
  566. */
  567. protected function addRule($rule)
  568. {
  569. $this->rules[$rule->name] = $rule;
  570. $this->saveRules();
  571. return true;
  572. }
  573. /**
  574. * {@inheritdoc}
  575. */
  576. protected function updateItem($name, $item)
  577. {
  578. if ($name !== $item->name) {
  579. if (isset($this->items[$item->name])) {
  580. throw new InvalidArgumentException("Unable to change the item name. The name '{$item->name}' is already used by another item.");
  581. }
  582. // Remove old item in case of renaming
  583. unset($this->items[$name]);
  584. if (isset($this->children[$name])) {
  585. $this->children[$item->name] = $this->children[$name];
  586. unset($this->children[$name]);
  587. }
  588. foreach ($this->children as &$children) {
  589. if (isset($children[$name])) {
  590. $children[$item->name] = $children[$name];
  591. unset($children[$name]);
  592. }
  593. }
  594. foreach ($this->assignments as &$assignments) {
  595. if (isset($assignments[$name])) {
  596. $assignments[$item->name] = $assignments[$name];
  597. $assignments[$item->name]->roleName = $item->name;
  598. unset($assignments[$name]);
  599. }
  600. }
  601. $this->saveAssignments();
  602. }
  603. $this->items[$item->name] = $item;
  604. $this->saveItems();
  605. return true;
  606. }
  607. /**
  608. * {@inheritdoc}
  609. */
  610. protected function addItem($item)
  611. {
  612. $time = time();
  613. if ($item->createdAt === null) {
  614. $item->createdAt = $time;
  615. }
  616. if ($item->updatedAt === null) {
  617. $item->updatedAt = $time;
  618. }
  619. $this->items[$item->name] = $item;
  620. $this->saveItems();
  621. return true;
  622. }
  623. /**
  624. * Loads authorization data from persistent storage.
  625. */
  626. protected function load()
  627. {
  628. $this->children = [];
  629. $this->rules = [];
  630. $this->assignments = [];
  631. $this->items = [];
  632. $items = $this->loadFromFile($this->itemFile);
  633. $itemsMtime = @filemtime($this->itemFile);
  634. $assignments = $this->loadFromFile($this->assignmentFile);
  635. $assignmentsMtime = @filemtime($this->assignmentFile);
  636. $rules = $this->loadFromFile($this->ruleFile);
  637. foreach ($items as $name => $item) {
  638. $class = $item['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className();
  639. $this->items[$name] = new $class([
  640. 'name' => $name,
  641. 'description' => isset($item['description']) ? $item['description'] : null,
  642. 'ruleName' => isset($item['ruleName']) ? $item['ruleName'] : null,
  643. 'data' => isset($item['data']) ? $item['data'] : null,
  644. 'createdAt' => $itemsMtime,
  645. 'updatedAt' => $itemsMtime,
  646. ]);
  647. }
  648. foreach ($items as $name => $item) {
  649. if (isset($item['children'])) {
  650. foreach ($item['children'] as $childName) {
  651. if (isset($this->items[$childName])) {
  652. $this->children[$name][$childName] = $this->items[$childName];
  653. }
  654. }
  655. }
  656. }
  657. foreach ($assignments as $userId => $roles) {
  658. foreach ($roles as $role) {
  659. $this->assignments[$userId][$role] = new Assignment([
  660. 'userId' => $userId,
  661. 'roleName' => $role,
  662. 'createdAt' => $assignmentsMtime,
  663. ]);
  664. }
  665. }
  666. foreach ($rules as $name => $ruleData) {
  667. $this->rules[$name] = unserialize($ruleData);
  668. }
  669. }
  670. /**
  671. * Saves authorization data into persistent storage.
  672. */
  673. protected function save()
  674. {
  675. $this->saveItems();
  676. $this->saveAssignments();
  677. $this->saveRules();
  678. }
  679. /**
  680. * Loads the authorization data from a PHP script file.
  681. *
  682. * @param string $file the file path.
  683. * @return array the authorization data
  684. * @see saveToFile()
  685. */
  686. protected function loadFromFile($file)
  687. {
  688. if (is_file($file)) {
  689. return require $file;
  690. }
  691. return [];
  692. }
  693. /**
  694. * Saves the authorization data to a PHP script file.
  695. *
  696. * @param array $data the authorization data
  697. * @param string $file the file path.
  698. * @see loadFromFile()
  699. */
  700. protected function saveToFile($data, $file)
  701. {
  702. file_put_contents($file, "<?php\nreturn " . VarDumper::export($data) . ";\n", LOCK_EX);
  703. $this->invalidateScriptCache($file);
  704. }
  705. /**
  706. * Invalidates precompiled script cache (such as OPCache or APC) for the given file.
  707. * @param string $file the file path.
  708. * @since 2.0.9
  709. */
  710. protected function invalidateScriptCache($file)
  711. {
  712. if (function_exists('opcache_invalidate')) {
  713. opcache_invalidate($file, true);
  714. }
  715. if (function_exists('apc_delete_file')) {
  716. @apc_delete_file($file);
  717. }
  718. }
  719. /**
  720. * Saves items data into persistent storage.
  721. */
  722. protected function saveItems()
  723. {
  724. $items = [];
  725. foreach ($this->items as $name => $item) {
  726. /* @var $item Item */
  727. $items[$name] = array_filter(
  728. [
  729. 'type' => $item->type,
  730. 'description' => $item->description,
  731. 'ruleName' => $item->ruleName,
  732. 'data' => $item->data,
  733. ]
  734. );
  735. if (isset($this->children[$name])) {
  736. foreach ($this->children[$name] as $child) {
  737. /* @var $child Item */
  738. $items[$name]['children'][] = $child->name;
  739. }
  740. }
  741. }
  742. $this->saveToFile($items, $this->itemFile);
  743. }
  744. /**
  745. * Saves assignments data into persistent storage.
  746. */
  747. protected function saveAssignments()
  748. {
  749. $assignmentData = [];
  750. foreach ($this->assignments as $userId => $assignments) {
  751. foreach ($assignments as $name => $assignment) {
  752. /* @var $assignment Assignment */
  753. $assignmentData[$userId][] = $assignment->roleName;
  754. }
  755. }
  756. $this->saveToFile($assignmentData, $this->assignmentFile);
  757. }
  758. /**
  759. * Saves rules data into persistent storage.
  760. */
  761. protected function saveRules()
  762. {
  763. $rules = [];
  764. foreach ($this->rules as $name => $rule) {
  765. $rules[$name] = serialize($rule);
  766. }
  767. $this->saveToFile($rules, $this->ruleFile);
  768. }
  769. /**
  770. * {@inheritdoc}
  771. * @since 2.0.7
  772. */
  773. public function getUserIdsByRole($roleName)
  774. {
  775. $result = [];
  776. foreach ($this->assignments as $userID => $assignments) {
  777. foreach ($assignments as $userAssignment) {
  778. if ($userAssignment->roleName === $roleName && $userAssignment->userId == $userID) {
  779. $result[] = (string) $userID;
  780. }
  781. }
  782. }
  783. return $result;
  784. }
  785. }