PhpManager.php 21.8 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

/**
 * PhpManager represents an authorization manager that stores authorization
 * information in terms of a PHP script file.
 *
19 20
 * The authorization data will be saved to and loaded from three files
 * specified by [[itemFile]], [[assignmentFile]] and [[ruleFile]].
tof06 committed
21 22 23 24 25
 *
 * 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.
 *
26 27 28
 * Note that PhpManager is not compatible with facebooks [HHVM](http://hhvm.com/) because
 * it relies on writing php files and including them afterwards which is not supported by HHVM.
 *
tof06 committed
29 30 31
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Alexander Kochetov <creocoder@gmail.com>
 * @author Christophe Boulain <christophe.boulain@gmail.com>
32
 * @author Alexander Makarov <sam@rmcreative.ru>
tof06 committed
33 34 35 36 37
 * @since 2.0
 */
class PhpManager extends BaseManager
{
    /**
38
     * @var string the path of the PHP script that contains the authorization items.
tof06 committed
39 40 41 42 43
     * 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
44
    public $itemFile = '@app/rbac/items.php';
45 46 47 48 49 50 51
    /**
     * @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
52
    public $assignmentFile = '@app/rbac/assignments.php';
53 54 55 56 57 58 59
    /**
     * @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
60
    public $ruleFile = '@app/rbac/rules.php';
61

62 63 64
    /**
     * @var Item[]
     */
65
    protected $items = []; // itemName => item
66 67 68
    /**
     * @var array
     */
69
    protected $children = []; // itemName, childName => child
70
    /**
Alexander Makarov committed
71
     * @var array
72
     */
73
    protected $assignments = []; // userId, itemName => assignment
74 75 76
    /**
     * @var Rule[]
     */
77
    protected $rules = []; // ruleName => rule
tof06 committed
78 79 80 81 82 83 84 85 86 87


    /**
     * 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
88 89 90
        $this->itemFile = Yii::getAlias($this->itemFile);
        $this->assignmentFile = Yii::getAlias($this->assignmentFile);
        $this->ruleFile = Yii::getAlias($this->ruleFile);
tof06 committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        $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)
    {
108
        return isset($this->assignments[$userId]) ? $this->assignments[$userId] : [];
tof06 committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    }

    /**
     * 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.
     */
124
    protected function checkAccessRecursive($user, $itemName, $params, $assignments)
tof06 committed
125
    {
126
        if (!isset($this->items[$itemName])) {
tof06 committed
127 128 129
            return false;
        }

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

134
        if (!$this->executeRule($user, $item, $params)) {
tof06 committed
135 136 137
            return false;
        }

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

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

        return false;
    }

    /**
     * @inheritdoc
     */
    public function addChild($parent, $child)
    {
156
        if (!isset($this->items[$parent->name], $this->items[$child->name])) {
tof06 committed
157 158 159 160 161 162 163 164 165 166 167 168 169
            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.");
        }
170
        if (isset($this->children[$parent->name][$child->name])) {
tof06 committed
171 172
            throw new InvalidCallException("The item '{$parent->name}' already has a child '{$child->name}'.");
        }
173 174
        $this->children[$parent->name][$child->name] = $this->items[$child->name];
        $this->saveItems();
tof06 committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

        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;
        }
191
        if (!isset($this->children[$child->name], $this->items[$parent->name])) {
tof06 committed
192 193
            return false;
        }
194
        foreach ($this->children[$child->name] as $grandchild) {
195
            /* @var $grandchild Item */
tof06 committed
196 197 198 199 200 201 202 203 204 205 206 207 208
            if ($this->detectLoop($parent, $grandchild)) {
                return true;
            }
        }

        return false;
    }

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

218 219 220 221 222 223 224 225 226 227 228 229 230 231
    /**
     * @inheritdoc
     */
    public function removeChildren($parent)
    {
        if (isset($this->children[$parent->name])) {
            unset($this->children[$parent->name]);
            $this->saveItems();
            return true;
        } else {
            return false;
        }
    }

tof06 committed
232
    /**
233
     * @inheritdoc
tof06 committed
234
     */
235
    public function hasChild($parent, $child)
tof06 committed
236
    {
237
        return isset($this->children[$parent->name][$child->name]);
tof06 committed
238 239 240 241 242
    }

    /**
     * @inheritdoc
     */
243
    public function assign($role, $userId)
tof06 committed
244
    {
245
        if (!isset($this->items[$role->name])) {
tof06 committed
246
            throw new InvalidParamException("Unknown role '{$role->name}'.");
247
        } elseif (isset($this->assignments[$userId][$role->name])) {
tof06 committed
248 249
            throw new InvalidParamException("Authorization item '{$role->name}' has already been assigned to user '$userId'.");
        } else {
250
            $this->assignments[$userId][$role->name] = new Assignment([
tof06 committed
251 252 253 254
                'userId' => $userId,
                'roleName' => $role->name,
                'createdAt' => time(),
            ]);
255 256
            $this->saveAssignments();
            return $this->assignments[$userId][$role->name];
tof06 committed
257 258 259 260 261 262 263 264
        }
    }

    /**
     * @inheritdoc
     */
    public function revoke($role, $userId)
    {
265 266 267
        if (isset($this->assignments[$userId][$role->name])) {
            unset($this->assignments[$userId][$role->name]);
            $this->saveAssignments();
tof06 committed
268 269 270 271 272 273 274 275 276 277 278
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function revokeAll($userId)
    {
279 280 281
        if (isset($this->assignments[$userId]) && is_array($this->assignments[$userId])) {
            foreach ($this->assignments[$userId] as $itemName => $value) {
                unset($this->assignments[$userId][$itemName]);
tof06 committed
282
            }
283
            $this->saveAssignments();
tof06 committed
284 285 286 287 288 289 290 291 292 293 294
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function getAssignment($roleName, $userId)
    {
295
        return isset($this->assignments[$userId][$roleName]) ? $this->assignments[$userId][$roleName] : null;
tof06 committed
296 297 298 299 300 301 302 303 304
    }

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

305
        foreach ($this->items as $name => $item) {
306
            /* @var $item Item */
tof06 committed
307 308 309 310 311 312 313 314 315 316 317 318 319 320
            if ($item->type == $type) {
                $items[$name] = $item;
            }
        }

        return $items;
    }


    /**
     * @inheritdoc
     */
    public function removeItem($item)
    {
321 322
        if (isset($this->items[$item->name])) {
            foreach ($this->children as &$children) {
tof06 committed
323 324
                unset($children[$item->name]);
            }
325
            foreach ($this->assignments as &$assignments) {
tof06 committed
326 327
                unset($assignments[$item->name]);
            }
328 329
            unset($this->items[$item->name]);
            $this->saveItems();
tof06 committed
330 331 332 333 334 335 336 337 338 339 340
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function getItem($name)
    {
341
        return isset($this->items[$name]) ? $this->items[$name] : null;
tof06 committed
342 343 344 345 346 347 348 349
    }

    /**
     * @inheritdoc
     */
    public function updateRule($name, $rule)
    {
        if ($rule->name !== $name) {
350
            unset($this->rules[$name]);
tof06 committed
351
        }
352 353
        $this->rules[$rule->name] = $rule;
        $this->saveRules();
tof06 committed
354 355 356 357 358 359 360 361
        return true;
    }

    /**
     * @inheritdoc
     */
    public function getRule($name)
    {
362
        return isset($this->rules[$name]) ? $this->rules[$name] : null;
tof06 committed
363 364 365 366 367 368 369
    }

    /**
     * @inheritdoc
     */
    public function getRules()
    {
370
        return $this->rules;
tof06 committed
371 372 373 374 375 376 377 378 379
    }

    /**
     * @inheritdoc
     */
    public function getRolesByUser($userId)
    {
        $roles = [];
        foreach ($this->getAssignments($userId) as $name => $assignment) {
380
            $roles[$name] = $this->items[$assignment->roleName];
tof06 committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
        }

        return $roles;
    }

    /**
     * @inheritdoc
     */
    public function getPermissionsByRole($roleName)
    {
        $result = [];
        $this->getChildrenRecursive($roleName, $result);
        if (empty($result)) {
            return [];
        }
        $permissions = [];
        foreach (array_keys($result) as $itemName) {
398 399
            if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
                $permissions[$itemName] = $this->items[$itemName];
tof06 committed
400 401 402 403 404 405 406 407 408 409 410 411 412
            }
        }
        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)
    {
413 414
        if (isset($this->children[$name])) {
            foreach ($this->children[$name] as $child) {
tof06 committed
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
                $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) {
438 439
            if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
                $permissions[$itemName] = $this->items[$itemName];
tof06 committed
440 441 442 443 444 445 446 447 448 449
            }
        }
        return $permissions;
    }

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

453 454 455 456 457
    /**
     * @inheritdoc
     */
    public function removeAll()
    {
458 459 460 461
        $this->children = [];
        $this->items = [];
        $this->assignments = [];
        $this->rules = [];
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        $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 = [];
488
        foreach ($this->items as $name => $item) {
489
            if ($item->type == $type) {
490
                unset($this->items[$name]);
491 492 493 494 495 496 497
                $names[$name] = true;
            }
        }
        if (empty($names)) {
            return;
        }

498
        foreach ($this->assignments as $i => $assignment) {
499
            if (isset($names[$assignment->roleName])) {
500
                unset($this->assignments[$i]);
501 502
            }
        }
503
        foreach ($this->children as $name => $children) {
504
            if (isset($names[$name])) {
505
                unset($this->children[$name]);
506 507 508 509 510 511
            } else {
                foreach ($children as $childName => $item) {
                    if (isset($names[$childName])) {
                        unset($children[$childName]);
                    }
                }
512
                $this->children[$name] = $children;
513 514 515
            }
        }

516
        $this->saveItems();
517 518 519 520 521 522 523
    }

    /**
     * @inheritdoc
     */
    public function removeAllRules()
    {
524
        foreach ($this->items as $item) {
525 526
            $item->ruleName = null;
        }
527 528
        $this->rules = [];
        $this->saveRules();
529 530 531 532 533 534 535
    }

    /**
     * @inheritdoc
     */
    public function removeAllAssignments()
    {
536 537
        $this->assignments = [];
        $this->saveAssignments();
538 539
    }

tof06 committed
540 541 542 543 544
    /**
     * @inheritdoc
     */
    protected function removeRule($rule)
    {
545 546 547
        if (isset($this->rules[$rule->name])) {
            unset($this->rules[$rule->name]);
            foreach ($this->items as $item) {
548 549 550 551
                if ($item->ruleName === $rule->name) {
                    $item->ruleName = null;
                }
            }
552
            $this->saveRules();
tof06 committed
553 554 555 556 557 558 559 560 561 562 563
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    protected function addRule($rule)
    {
564 565
        $this->rules[$rule->name] = $rule;
        $this->saveRules();
tof06 committed
566 567 568 569 570 571 572 573
        return true;
    }

    /**
     * @inheritdoc
     */
    protected function updateItem($name, $item)
    {
574
        $this->items[$item->name] = $item;
tof06 committed
575
        if ($name !== $item->name) {
576
            if (isset($this->items[$item->name])) {
577
                throw new InvalidParamException("Unable to change the item name. The name '{$item->name}' is already used by another item.");
tof06 committed
578
            }
579 580
            if (isset($this->items[$name])) {
                unset ($this->items[$name]);
tof06 committed
581

582 583 584
                if (isset($this->children[$name])) {
                    $this->children[$item->name] = $this->children[$name];
                    unset ($this->children[$name]);
tof06 committed
585
                }
586
                foreach ($this->children as &$children) {
tof06 committed
587 588 589 590 591
                    if (isset($children[$name])) {
                        $children[$item->name] = $children[$name];
                        unset ($children[$name]);
                    }
                }
592
                foreach ($this->assignments as &$assignments) {
tof06 committed
593 594 595 596 597 598 599
                    if (isset($assignments[$name])) {
                        $assignments[$item->name] = $assignments[$name];
                        unset($assignments[$name]);
                    }
                }
            }
        }
600
        $this->saveItems();
tof06 committed
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
        return true;
    }

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

617
        $this->items[$item->name] = $item;
tof06 committed
618

619
        $this->saveItems();
620

tof06 committed
621 622 623
        return true;

    }
624 625 626 627

    /**
     * Loads authorization data from persistent storage.
     */
628 629 630 631 632 633 634
    protected function load()
    {
        $this->children = [];
        $this->rules = [];
        $this->assignments = [];
        $this->items = [];

Alexander Makarov committed
635 636 637 638 639
        $items = $this->loadFromFile($this->itemFile);
        $itemsMtime = @filemtime($this->itemFile);
        $assignments = $this->loadFromFile($this->assignmentFile);
        $assignmentsMtime = @filemtime($this->assignmentFile);
        $rules = $this->loadFromFile($this->ruleFile);
640 641 642 643 644 645 646 647 648 649 650 651 652

        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,
            ]);
        }
653

654 655 656 657 658
        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];
659 660 661 662 663
                    }
                }
            }
        }

664 665 666 667 668 669 670 671
        foreach ($assignments as $userId => $roles) {
            foreach ($roles as $role) {
                $this->assignments[$userId][$role] = new Assignment([
                    'userId' => $userId,
                    'roleName' => $role,
                    'createdAt' => $assignmentsMtime,
                ]);
            }
672 673 674 675
        }

        foreach ($rules as $name => $ruleData) {
            $this->rules[$name] = unserialize($ruleData);
676 677 678 679 680 681
        }
    }

    /**
     * Saves authorization data into persistent storage.
     */
682
    protected function save()
683
    {
684 685 686
        $this->saveItems();
        $this->saveAssignments();
        $this->saveRules();
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
    }

    /**
     * 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)
    {
714
        file_put_contents($file, "<?php\nreturn " . VarDumper::export($data) . ";\n", LOCK_EX);
715
    }
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739

    /**
     * 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
740
        $this->saveToFile($items, $this->itemFile);
741 742 743 744 745 746 747 748 749 750 751
    }

    /**
     * Saves assignments data into persistent storage.
     */
    protected function saveAssignments()
    {
        $assignmentData = [];
        foreach ($this->assignments as $userId => $assignments) {
            foreach ($assignments as $name => $assignment) {
                /* @var $assignment Assignment */
752
                $assignmentData[$userId][] = $assignment->roleName;
753 754
            }
        }
Alexander Makarov committed
755
        $this->saveToFile($assignmentData, $this->assignmentFile);
756 757 758 759 760 761 762 763 764 765 766
    }

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