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

/**
 * 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.
 *
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 218
            return true;
        } else {
            return false;
        }
    }

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

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

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

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

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

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

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

        return $items;
    }


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

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

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

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

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

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

        return $roles;
    }

    /**
     * @inheritdoc
     */
    public function getPermissionsByRole($roleName)
    {
        $result = [];
        $this->getChildrenRecursive($roleName, $result);
        if (empty($result)) {
            return [];
        }
        $permissions = [];
        foreach (array_keys($result) as $itemName) {
384 385
            if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
                $permissions[$itemName] = $this->items[$itemName];
tof06 committed
386 387 388 389 390 391 392 393 394 395 396 397 398
            }
        }
        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)
    {
399 400
        if (isset($this->children[$name])) {
            foreach ($this->children[$name] as $child) {
tof06 committed
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
                $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) {
424 425
            if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
                $permissions[$itemName] = $this->items[$itemName];
tof06 committed
426 427 428 429 430 431 432 433 434 435
            }
        }
        return $permissions;
    }

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

439 440 441 442 443
    /**
     * @inheritdoc
     */
    public function removeAll()
    {
444 445 446 447
        $this->children = [];
        $this->items = [];
        $this->assignments = [];
        $this->rules = [];
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
        $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 = [];
474
        foreach ($this->items as $name => $item) {
475
            if ($item->type == $type) {
476
                unset($this->items[$name]);
477 478 479 480 481 482 483
                $names[$name] = true;
            }
        }
        if (empty($names)) {
            return;
        }

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

502
        $this->saveItems();
503 504 505 506 507 508 509
    }

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

    /**
     * @inheritdoc
     */
    public function removeAllAssignments()
    {
522 523
        $this->assignments = [];
        $this->saveAssignments();
524 525
    }

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

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

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

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

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

603
        $this->items[$item->name] = $item;
tof06 committed
604

605
        $this->saveItems();
606

tof06 committed
607 608 609
        return true;

    }
610 611 612 613

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

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

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

640 641 642 643 644
        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];
645 646 647 648 649
                    }
                }
            }
        }

650 651 652 653 654 655 656 657
        foreach ($assignments as $userId => $roles) {
            foreach ($roles as $role) {
                $this->assignments[$userId][$role] = new Assignment([
                    'userId' => $userId,
                    'roleName' => $role,
                    'createdAt' => $assignmentsMtime,
                ]);
            }
658 659 660 661
        }

        foreach ($rules as $name => $ruleData) {
            $this->rules[$name] = unserialize($ruleData);
662 663 664 665 666 667
        }
    }

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

    /**
     * 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)
    {
700
        file_put_contents($file, "<?php\nreturn " . VarDumper::export($data) . ";\n", LOCK_EX);
701
    }
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725

    /**
     * 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
726
        $this->saveToFile($items, $this->itemFile);
727 728 729 730 731 732 733 734 735 736 737
    }

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

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