PhpManager.php 21.3 KB
Newer Older
tof06 committed
1 2 3 4 5 6 7 8 9 10 11 12
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\rbac;

use yii\base\InvalidCallException;
use yii\base\InvalidParamException;
use Yii;
13
use yii\helpers\VarDumper;
tof06 committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

/**
 * PhpManager represents an authorization manager that stores authorization
 * information in terms of a PHP script file.
 *
 * The authorization data will be saved to and loaded from a file
 * specified by [[authFile]], which defaults to 'protected/data/rbac.php'.
 *
 * PhpManager is mainly suitable for authorization data that is not too big
 * (for example, the authorization data for a personal blog system).
 * Use [[DbManager]] for more complex authorization data.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Alexander Kochetov <creocoder@gmail.com>
 * @author Christophe Boulain <christophe.boulain@gmail.com>
29
 * @author Alexander Makarov <sam@rmcreative.ru>
tof06 committed
30 31 32 33 34
 * @since 2.0
 */
class PhpManager extends BaseManager
{
    /**
35
     * @var string the path of the PHP script that contains the authorization items.
tof06 committed
36 37 38 39 40
     * This can be either a file path or a path alias to the file.
     * Make sure this file is writable by the Web server process if the authorization needs to be changed online.
     * @see loadFromFile()
     * @see saveToFile()
     */
Alexander Makarov committed
41
    public $itemFile = '@app/rbac/items.php';
42 43 44 45 46 47 48
    /**
     * @var string the path of the PHP script that contains the authorization assignments.
     * This can be either a file path or a path alias to the file.
     * Make sure this file is writable by the Web server process if the authorization needs to be changed online.
     * @see loadFromFile()
     * @see saveToFile()
     */
Alexander Makarov committed
49
    public $assignmentFile = '@app/rbac/assignments.php';
50 51 52 53 54 55 56 57

    /**
     * @var string the path of the PHP script that contains the authorization rules.
     * This can be either a file path or a path alias to the file.
     * Make sure this file is writable by the Web server process if the authorization needs to be changed online.
     * @see loadFromFile()
     * @see saveToFile()
     */
Alexander Makarov committed
58
    public $ruleFile = '@app/rbac/rules.php';
59 60 61
    /**
     * @var Item[]
     */
62
    protected $items = []; // itemName => item
63 64 65
    /**
     * @var array
     */
66
    protected $children = []; // itemName, childName => child
67 68 69
    /**
     * @var Assignment[]
     */
70
    protected $assignments = []; // userId, itemName => assignment
71 72 73
    /**
     * @var Rule[]
     */
74
    protected $rules = []; // ruleName => rule
tof06 committed
75 76 77 78 79 80 81 82 83 84


    /**
     * Initializes the application component.
     * This method overrides parent implementation by loading the authorization data
     * from PHP script.
     */
    public function init()
    {
        parent::init();
Alexander Makarov committed
85 86 87
        $this->itemFile = Yii::getAlias($this->itemFile);
        $this->assignmentFile = Yii::getAlias($this->assignmentFile);
        $this->ruleFile = Yii::getAlias($this->ruleFile);
tof06 committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
        $this->load();
    }

    /**
     * @inheritdoc
     */
    public function checkAccess($userId, $permissionName, $params = [])
    {
        $assignments = $this->getAssignments($userId);
        return $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
    }

    /**
     * @inheritdoc
     */
    public function getAssignments($userId)
    {
105
        return isset($this->assignments[$userId]) ? $this->assignments[$userId] : [];
tof06 committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    }

    /**
     * Performs access check for the specified user.
     * This method is internally called by [[checkAccess()]].
     *
     * @param string|integer $user the user ID. This should can be either an integer or a string representing
     * the unique identifier of a user. See [[\yii\web\User::id]].
     * @param string $itemName the name of the operation that need access check
     * @param array $params name-value pairs that would be passed to rules associated
     * with the tasks and roles assigned to the user. A param with name 'user' is added to this array,
     * which holds the value of `$userId`.
     * @param Assignment[] $assignments the assignments to the specified user
     * @return boolean whether the operations can be performed by the user.
     */
121
    protected function checkAccessRecursive($user, $itemName, $params, $assignments)
tof06 committed
122
    {
123
        if (!isset($this->items[$itemName])) {
tof06 committed
124 125 126
            return false;
        }

127
        /* @var $item Item */
128
        $item = $this->items[$itemName];
tof06 committed
129 130
        Yii::trace($item instanceof Role ? "Checking role: $itemName" : "Checking permission : $itemName", __METHOD__);

131
        if (!$this->executeRule($user, $item, $params)) {
tof06 committed
132 133 134
            return false;
        }

135
        if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
tof06 committed
136 137 138
            return true;
        }

139
        foreach ($this->children as $parentName => $children) {
tof06 committed
140 141 142 143 144 145 146 147 148 149 150 151 152
            if (isset($children[$itemName]) && $this->checkAccessRecursive($user, $parentName, $params, $assignments)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @inheritdoc
     */
    public function addChild($parent, $child)
    {
153
        if (!isset($this->items[$parent->name], $this->items[$child->name])) {
tof06 committed
154 155 156 157 158 159 160 161 162 163 164 165 166
            throw new InvalidParamException("Either '{$parent->name}' or '{$child->name}' does not exist.");
        }

        if ($parent->name == $child->name) {
            throw new InvalidParamException("Cannot add '{$parent->name} ' as a child of itself.");
        }
        if ($parent instanceof Permission && $child instanceof Role) {
            throw new InvalidParamException("Cannot add a role as a child of a permission.");
        }

        if ($this->detectLoop($parent, $child)) {
            throw new InvalidCallException("Cannot add '{$child->name}' as a child of '{$parent->name}'. A loop has been detected.");
        }
167
        if (isset($this->children[$parent->name][$child->name])) {
tof06 committed
168 169
            throw new InvalidCallException("The item '{$parent->name}' already has a child '{$child->name}'.");
        }
170 171
        $this->children[$parent->name][$child->name] = $this->items[$child->name];
        $this->saveItems();
tof06 committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187

        return true;
    }

    /**
     * Checks whether there is a loop in the authorization item hierarchy.
     *
     * @param Item $parent parent item
     * @param Item $child the child item that is to be added to the hierarchy
     * @return boolean whether a loop exists
     */
    protected function detectLoop($parent, $child)
    {
        if ($child->name === $parent->name) {
            return true;
        }
188
        if (!isset($this->children[$child->name], $this->items[$parent->name])) {
tof06 committed
189 190
            return false;
        }
191
        foreach ($this->children[$child->name] as $grandchild) {
192
            /* @var $grandchild Item */
tof06 committed
193 194 195 196 197 198 199 200 201 202 203 204 205
            if ($this->detectLoop($parent, $grandchild)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @inheritdoc
     */
    public function removeChild($parent, $child)
    {
206 207 208
        if (isset($this->children[$parent->name][$child->name])) {
            unset($this->children[$parent->name][$child->name]);
            $this->saveItems();
tof06 committed
209 210 211 212 213 214 215
            return true;
        } else {
            return false;
        }
    }

    /**
216
     * @inheritdoc
tof06 committed
217
     */
218
    public function hasChild($parent, $child)
tof06 committed
219
    {
220
        return isset($this->children[$parent->name][$child->name]);
tof06 committed
221 222 223 224 225 226 227
    }

    /**
     * @inheritdoc
     */
    public function assign($role, $userId, $ruleName = null, $data = null)
    {
228
        if (!isset($this->items[$role->name])) {
tof06 committed
229
            throw new InvalidParamException("Unknown role '{$role->name}'.");
230
        } elseif (isset($this->assignments[$userId][$role->name])) {
tof06 committed
231 232
            throw new InvalidParamException("Authorization item '{$role->name}' has already been assigned to user '$userId'.");
        } else {
233
            $this->assignments[$userId][$role->name] = new Assignment([
tof06 committed
234 235 236 237
                'userId' => $userId,
                'roleName' => $role->name,
                'createdAt' => time(),
            ]);
238 239
            $this->saveAssignments();
            return $this->assignments[$userId][$role->name];
tof06 committed
240 241 242 243 244 245 246 247
        }
    }

    /**
     * @inheritdoc
     */
    public function revoke($role, $userId)
    {
248 249 250
        if (isset($this->assignments[$userId][$role->name])) {
            unset($this->assignments[$userId][$role->name]);
            $this->saveAssignments();
tof06 committed
251 252 253 254 255 256 257 258 259 260 261
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function revokeAll($userId)
    {
262 263 264
        if (isset($this->assignments[$userId]) && is_array($this->assignments[$userId])) {
            foreach ($this->assignments[$userId] as $itemName => $value) {
                unset($this->assignments[$userId][$itemName]);
tof06 committed
265
            }
266
            $this->saveAssignments();
tof06 committed
267 268 269 270 271 272 273 274 275 276 277
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function getAssignment($roleName, $userId)
    {
278
        return isset($this->assignments[$userId][$roleName]) ? $this->assignments[$userId][$roleName] : null;
tof06 committed
279 280 281 282 283 284 285 286 287
    }

    /**
     * @inheritdoc
     */
    public function getItems($type)
    {
        $items = [];

288
        foreach ($this->items as $name => $item) {
289
            /* @var $item Item */
tof06 committed
290 291 292 293 294 295 296 297 298 299 300 301 302 303
            if ($item->type == $type) {
                $items[$name] = $item;
            }
        }

        return $items;
    }


    /**
     * @inheritdoc
     */
    public function removeItem($item)
    {
304 305
        if (isset($this->items[$item->name])) {
            foreach ($this->children as &$children) {
tof06 committed
306 307
                unset($children[$item->name]);
            }
308
            foreach ($this->assignments as &$assignments) {
tof06 committed
309 310
                unset($assignments[$item->name]);
            }
311 312
            unset($this->items[$item->name]);
            $this->saveItems();
tof06 committed
313 314 315 316 317 318 319 320 321 322 323
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function getItem($name)
    {
324
        return isset($this->items[$name]) ? $this->items[$name] : null;
tof06 committed
325 326 327 328 329 330 331 332
    }

    /**
     * @inheritdoc
     */
    public function updateRule($name, $rule)
    {
        if ($rule->name !== $name) {
333
            unset($this->rules[$name]);
tof06 committed
334
        }
335 336
        $this->rules[$rule->name] = $rule;
        $this->saveRules();
tof06 committed
337 338 339 340 341 342 343 344
        return true;
    }

    /**
     * @inheritdoc
     */
    public function getRule($name)
    {
345
        return isset($this->rules[$name]) ? $this->rules[$name] : null;
tof06 committed
346 347 348 349 350 351 352
    }

    /**
     * @inheritdoc
     */
    public function getRules()
    {
353
        return $this->rules;
tof06 committed
354 355 356 357 358 359 360 361 362
    }

    /**
     * @inheritdoc
     */
    public function getRolesByUser($userId)
    {
        $roles = [];
        foreach ($this->getAssignments($userId) as $name => $assignment) {
363
            $roles[$name] = $this->items[$assignment->roleName];
tof06 committed
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
        }

        return $roles;
    }

    /**
     * @inheritdoc
     */
    public function getPermissionsByRole($roleName)
    {
        $result = [];
        $this->getChildrenRecursive($roleName, $result);
        if (empty($result)) {
            return [];
        }
        $permissions = [];
        foreach (array_keys($result) as $itemName) {
381 382
            if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
                $permissions[$itemName] = $this->items[$itemName];
tof06 committed
383 384 385 386 387 388 389 390 391 392 393 394 395
            }
        }
        return $permissions;
    }

    /**
     * Recursively finds all children and grand children of the specified item.
     *
     * @param string $name the name of the item whose children are to be looked for.
     * @param array $result the children and grand children (in array keys)
     */
    protected function getChildrenRecursive($name, &$result)
    {
396 397
        if (isset($this->children[$name])) {
            foreach ($this->children[$name] as $child) {
tof06 committed
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
                $result[$child->name] = true;
                $this->getChildrenRecursive($child->name, $result);
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function getPermissionsByUser($userId)
    {
        $assignments = $this->getAssignments($userId);
        $result = [];
        foreach (array_keys($assignments) as $roleName) {
            $this->getChildrenRecursive($roleName, $result);
        }

        if (empty($result)) {
            return [];
        }

        $permissions = [];
        foreach (array_keys($result) as $itemName) {
421 422
            if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
                $permissions[$itemName] = $this->items[$itemName];
tof06 committed
423 424 425 426 427 428 429 430 431 432
            }
        }
        return $permissions;
    }

    /**
     * @inheritdoc
     */
    public function getChildren($name)
    {
433
        return isset($this->children[$name]) ? $this->children[$name] : [];
tof06 committed
434 435
    }

436 437 438 439 440
    /**
     * @inheritdoc
     */
    public function removeAll()
    {
441 442 443 444
        $this->children = [];
        $this->items = [];
        $this->assignments = [];
        $this->rules = [];
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
        $this->save();
    }

    /**
     * @inheritdoc
     */
    public function removeAllPermissions()
    {
        $this->removeAllItems(Item::TYPE_PERMISSION);
    }

    /**
     * @inheritdoc
     */
    public function removeAllRoles()
    {
        $this->removeAllItems(Item::TYPE_ROLE);
    }

    /**
     * Removes all auth items of the specified type.
     * @param integer $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE)
     */
    protected function removeAllItems($type)
    {
        $names = [];
471
        foreach ($this->items as $name => $item) {
472
            if ($item->type == $type) {
473
                unset($this->items[$name]);
474 475 476 477 478 479 480
                $names[$name] = true;
            }
        }
        if (empty($names)) {
            return;
        }

481
        foreach ($this->assignments as $i => $assignment) {
482
            if (isset($names[$assignment->roleName])) {
483
                unset($this->assignments[$i]);
484 485
            }
        }
486
        foreach ($this->children as $name => $children) {
487
            if (isset($names[$name])) {
488
                unset($this->children[$name]);
489 490 491 492 493 494
            } else {
                foreach ($children as $childName => $item) {
                    if (isset($names[$childName])) {
                        unset($children[$childName]);
                    }
                }
495
                $this->children[$name] = $children;
496 497 498
            }
        }

499
        $this->saveItems();
500 501 502 503 504 505 506
    }

    /**
     * @inheritdoc
     */
    public function removeAllRules()
    {
507
        foreach ($this->items as $item) {
508 509
            $item->ruleName = null;
        }
510 511
        $this->rules = [];
        $this->saveRules();
512 513 514 515 516 517 518
    }

    /**
     * @inheritdoc
     */
    public function removeAllAssignments()
    {
519 520
        $this->assignments = [];
        $this->saveAssignments();
521 522
    }

tof06 committed
523 524 525 526 527
    /**
     * @inheritdoc
     */
    protected function removeRule($rule)
    {
528 529 530
        if (isset($this->rules[$rule->name])) {
            unset($this->rules[$rule->name]);
            foreach ($this->items as $item) {
531 532 533 534
                if ($item->ruleName === $rule->name) {
                    $item->ruleName = null;
                }
            }
535
            $this->saveRules();
tof06 committed
536 537 538 539 540 541 542 543 544 545 546
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    protected function addRule($rule)
    {
547 548
        $this->rules[$rule->name] = $rule;
        $this->saveRules();
tof06 committed
549 550 551 552 553 554 555 556
        return true;
    }

    /**
     * @inheritdoc
     */
    protected function updateItem($name, $item)
    {
557
        $this->items[$item->name] = $item;
tof06 committed
558
        if ($name !== $item->name) {
559
            if (isset($this->items[$item->name])) {
560
                throw new InvalidParamException("Unable to change the item name. The name '{$item->name}' is already used by another item.");
tof06 committed
561
            }
562 563
            if (isset($this->items[$name])) {
                unset ($this->items[$name]);
tof06 committed
564

565 566 567
                if (isset($this->children[$name])) {
                    $this->children[$item->name] = $this->children[$name];
                    unset ($this->children[$name]);
tof06 committed
568
                }
569
                foreach ($this->children as &$children) {
tof06 committed
570 571 572 573 574
                    if (isset($children[$name])) {
                        $children[$item->name] = $children[$name];
                        unset ($children[$name]);
                    }
                }
575
                foreach ($this->assignments as &$assignments) {
tof06 committed
576 577 578 579 580 581 582
                    if (isset($assignments[$name])) {
                        $assignments[$item->name] = $assignments[$name];
                        unset($assignments[$name]);
                    }
                }
            }
        }
583
        $this->saveItems();
tof06 committed
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
        return true;
    }

    /**
     * @inheritdoc
     */
    protected function addItem($item)
    {
        $time = time();
        if ($item->createdAt === null) {
            $item->createdAt = $time;
        }
        if ($item->updatedAt === null) {
            $item->updatedAt = $time;
        }

600
        $this->items[$item->name] = $item;
tof06 committed
601

602
        $this->saveItems();
603

tof06 committed
604 605 606
        return true;

    }
607 608 609 610

    /**
     * Loads authorization data from persistent storage.
     */
611 612 613 614 615 616 617
    protected function load()
    {
        $this->children = [];
        $this->rules = [];
        $this->assignments = [];
        $this->items = [];

Alexander Makarov committed
618 619 620 621 622
        $items = $this->loadFromFile($this->itemFile);
        $itemsMtime = @filemtime($this->itemFile);
        $assignments = $this->loadFromFile($this->assignmentFile);
        $assignmentsMtime = @filemtime($this->assignmentFile);
        $rules = $this->loadFromFile($this->ruleFile);
623 624 625 626 627 628 629 630 631 632 633 634 635

        foreach ($items as $name => $item) {
            $class = $item['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className();

            $this->items[$name] = new $class([
                'name' => $name,
                'description' => isset($item['description']) ? $item['description'] : null,
                'ruleName' => isset($item['ruleName']) ? $item['ruleName'] : null,
                'data' => isset($item['data']) ? $item['data'] : null,
                'createdAt' => $itemsMtime,
                'updatedAt' => $itemsMtime,
            ]);
        }
636

637 638 639 640 641
        foreach ($items as $name => $item) {
            if (isset($item['children'])) {
                foreach ($item['children'] as $childName) {
                    if (isset($this->items[$childName])) {
                        $this->children[$name][$childName] = $this->items[$childName];
642 643 644 645 646
                    }
                }
            }
        }

647 648 649 650 651 652 653 654 655 656
        foreach ($assignments as $userId => $role) {
            $this->assignments[$userId][$role] = new Assignment([
                'userId' => $userId,
                'roleName' => $role,
                'createdAt' => $assignmentsMtime,
            ]);
        }

        foreach ($rules as $name => $ruleData) {
            $this->rules[$name] = unserialize($ruleData);
657 658 659 660 661 662
        }
    }

    /**
     * Saves authorization data into persistent storage.
     */
663
    protected function save()
664
    {
665 666 667
        $this->saveItems();
        $this->saveAssignments();
        $this->saveRules();
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
    }

    /**
     * Loads the authorization data from a PHP script file.
     *
     * @param string $file the file path.
     * @return array the authorization data
     * @see saveToFile()
     */
    protected function loadFromFile($file)
    {
        if (is_file($file)) {
            return require($file);
        } else {
            return [];
        }
    }

    /**
     * Saves the authorization data to a PHP script file.
     *
     * @param array $data the authorization data
     * @param string $file the file path.
     * @see loadFromFile()
     */
    protected function saveToFile($data, $file)
    {
695
        file_put_contents($file, "<?php\nreturn " . VarDumper::export($data) . ";\n", LOCK_EX);
696
    }
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720

    /**
     * Saves items data into persistent storage.
     */
    protected function saveItems()
    {
        $items = [];
        foreach ($this->items as $name => $item) {
            /* @var $item Item */
            $items[$name] = array_filter(
                [
                    'type' => $item->type,
                    'description' => $item->description,
                    'ruleName' => $item->ruleName,
                    'data' => $item->data,
                ]
            );
            if (isset($this->children[$name])) {
                foreach ($this->children[$name] as $child) {
                    /* @var $child Item */
                    $items[$name]['children'][] = $child->name;
                }
            }
        }
Alexander Makarov committed
721
        $this->saveToFile($items, $this->itemFile);
722 723 724 725 726 727 728 729 730 731 732 733 734 735
    }

    /**
     * Saves assignments data into persistent storage.
     */
    protected function saveAssignments()
    {
        $assignmentData = [];
        foreach ($this->assignments as $userId => $assignments) {
            foreach ($assignments as $name => $assignment) {
                /* @var $assignment Assignment */
                $assignmentData[$userId] = $assignment->roleName;
            }
        }
Alexander Makarov committed
736
        $this->saveToFile($assignmentData, $this->assignmentFile);
737 738 739 740 741 742 743 744 745 746 747
    }

    /**
     * Saves rules data into persistent storage.
     */
    protected function saveRules()
    {
        $rules = [];
        foreach ($this->rules as $name => $rule) {
            $rules[$name] = serialize($rule);
        }
Alexander Makarov committed
748
        $this->saveToFile($rules, $this->ruleFile);
749
    }
750
}