PhpManager.php 20.2 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 29 30 31 32 33 34 35 36 37 38 39 40

/**
 * 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>
 * @since 2.0
 */
class PhpManager extends BaseManager
{
    /**
     * @var string the path of the PHP script that contains the authorization data.
     * 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()
     */
    public $authFile = '@app/data/rbac.php';
41 42 43
    /**
     * @var Item[]
     */
tof06 committed
44
    private $_items = []; // itemName => item
45 46 47
    /**
     * @var array
     */
tof06 committed
48
    private $_children = []; // itemName, childName => child
49 50 51
    /**
     * @var Assignment[]
     */
tof06 committed
52
    private $_assignments = []; // userId, itemName => assignment
53 54 55
    /**
     * @var Rule[]
     */
tof06 committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    private $_rules = []; // ruleName => rule


    /**
     * Initializes the application component.
     * This method overrides parent implementation by loading the authorization data
     * from PHP script.
     */
    public function init()
    {
        parent::init();
        $this->authFile = Yii::getAlias($this->authFile);
        $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)
    {
        return isset($this->_assignments[$userId]) ? $this->_assignments[$userId] : [];
    }

    /**
     * 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.
     */
101
    protected function checkAccessRecursive($user, $itemName, $params, $assignments)
tof06 committed
102 103 104 105 106 107 108 109 110
    {
        if (!isset($this->_items[$itemName])) {
            return false;
        }

        /** @var Item $item */
        $item = $this->_items[$itemName];
        Yii::trace($item instanceof Role ? "Checking role: $itemName" : "Checking permission : $itemName", __METHOD__);

111
        if (!$this->executeRule($user, $item, $params)) {
tof06 committed
112 113 114
            return false;
        }

115
        if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
tof06 committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
            return true;
        }

        foreach ($this->_children as $parentName => $children) {
            if (isset($children[$itemName]) && $this->checkAccessRecursive($user, $parentName, $params, $assignments)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @inheritdoc
     */
    public function addChild($parent, $child)
    {
        if (!isset($this->_items[$parent->name], $this->_items[$child->name])) {
            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.");
        }
        if (isset($this->_children[$parent->name][$child->name])) {
            throw new InvalidCallException("The item '{$parent->name}' already has a child '{$child->name}'.");
        }
        $this->_children[$parent->name][$child->name] = $this->_items[$child->name];
151
        $this->save();
tof06 committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 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;
        }
        if (!isset($this->_children[$child->name], $this->_items[$parent->name])) {
            return false;
        }
        foreach ($this->_children[$child->name] as $grandchild) {
            /** @var Item $grandchild */
            if ($this->detectLoop($parent, $grandchild)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @inheritdoc
     */
    public function removeChild($parent, $child)
    {
        if (isset($this->_children[$parent->name][$child->name])) {
            unset($this->_children[$parent->name][$child->name]);
188
            $this->save();
tof06 committed
189 190 191 192 193 194 195
            return true;
        } else {
            return false;
        }
    }

    /**
196
     * @inheritdoc
tof06 committed
197
     */
198
    public function hasChild($parent, $child)
tof06 committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212
    {
        return isset($this->_children[$parent->name][$child->name]);
    }

    /**
     * @inheritdoc
     */
    public function assign($role, $userId, $ruleName = null, $data = null)
    {
        if (!isset($this->_items[$role->name])) {
            throw new InvalidParamException("Unknown role '{$role->name}'.");
        } elseif (isset($this->_assignments[$userId][$role->name])) {
            throw new InvalidParamException("Authorization item '{$role->name}' has already been assigned to user '$userId'.");
        } else {
213
            $this->_assignments[$userId][$role->name] = new Assignment([
tof06 committed
214 215 216 217
                'userId' => $userId,
                'roleName' => $role->name,
                'createdAt' => time(),
            ]);
218 219
            $this->save();
            return $this->_assignments[$userId][$role->name];
tof06 committed
220 221 222 223 224 225 226 227 228 229
        }
    }

    /**
     * @inheritdoc
     */
    public function revoke($role, $userId)
    {
        if (isset($this->_assignments[$userId][$role->name])) {
            unset($this->_assignments[$userId][$role->name]);
230
            $this->save();
tof06 committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function revokeAll($userId)
    {
        if (isset($this->_assignments[$userId]) && is_array($this->_assignments[$userId])) {
            foreach ($this->_assignments[$userId] as $itemName => $value) {
                unset($this->_assignments[$userId][$itemName]);
            }
246
            $this->save();
tof06 committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function getAssignment($roleName, $userId)
    {
        return isset($this->_assignments[$userId][$roleName]) ? $this->_assignments[$userId][$roleName] : null;
    }

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

        foreach ($this->_items as $name => $item) {
            /** @var Item $item */
            if ($item->type == $type) {
                $items[$name] = $item;
            }
        }

        return $items;
    }


    /**
     * @inheritdoc
     */
    public function removeItem($item)
    {
        if (isset($this->_items[$item->name])) {
            foreach ($this->_children as &$children) {
                unset($children[$item->name]);
            }
            foreach ($this->_assignments as &$assignments) {
                unset($assignments[$item->name]);
            }
            unset($this->_items[$item->name]);
292
            $this->save();
tof06 committed
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function getItem($name)
    {
        return isset($this->_items[$name]) ? $this->_items[$name] : null;
    }

    /**
     * @inheritdoc
     */
    public function updateRule($name, $rule)
    {
        if ($rule->name !== $name) {
            unset($this->_rules[$name]);
        }
        $this->_rules[$rule->name] = $rule;
316
        $this->save();
tof06 committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
        return true;
    }

    /**
     * @inheritdoc
     */
    public function getRule($name)
    {
        return isset($this->_rules[$name]) ? $this->_rules[$name] : null;
    }

    /**
     * @inheritdoc
     */
    public function getRules()
    {
        return $this->_rules;
    }

    /**
     * @inheritdoc
     */
    public function getRolesByUser($userId)
    {
        $roles = [];
        foreach ($this->getAssignments($userId) as $name => $assignment) {
            $roles[$name] = $this->_items[$assignment->roleName];
        }

        return $roles;
    }

    /**
     * @inheritdoc
     */
    public function getPermissionsByRole($roleName)
    {
        $result = [];
        $this->getChildrenRecursive($roleName, $result);
        if (empty($result)) {
            return [];
        }
        $permissions = [];
        foreach (array_keys($result) as $itemName) {
            if (isset($this->_items[$itemName]) && $this->_items[$itemName] instanceof Permission) {
                $permissions[$itemName] = $this->_items[$itemName];
            }
        }
        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)
    {
        if (isset($this->_children[$name])) {
            foreach ($this->_children[$name] as $child) {
                $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) {
            if (isset($this->_items[$itemName]) && $this->_items[$itemName] instanceof Permission) {
                $permissions[$itemName] = $this->_items[$itemName];
            }
        }
        return $permissions;
    }

    /**
     * @inheritdoc
     */
    public function getChildren($name)
    {
        return (isset($this->_children[$name])) ? $this->_children[$name] : null;
    }

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 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 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    /**
     * @inheritdoc
     */
    public function removeAll()
    {
        $this->_children = [];
        $this->_items = [];
        $this->_assignments = [];
        $this->_rules = [];
        $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 = [];
        foreach ($this->_items as $name => $item) {
            if ($item->type == $type) {
                unset($this->_items[$name]);
                $names[$name] = true;
            }
        }
        if (empty($names)) {
            return;
        }

        foreach ($this->_assignments as $i => $assignment) {
            if (isset($names[$assignment->roleName])) {
                unset($this->_assignments[$i]);
            }
        }
        foreach ($this->_children as $name => $children) {
            if (isset($names[$name])) {
                unset($this->_children[$name]);
            } else {
                foreach ($children as $childName => $item) {
                    if (isset($names[$childName])) {
                        unset($children[$childName]);
                    }
                }
                $this->_children[$name] = $children;
            }
        }

        $this->save();
    }

    /**
     * @inheritdoc
     */
    public function removeAllRules()
    {
        foreach ($this->_items as $item) {
            $item->ruleName = null;
        }
        $this->_rules = [];
        $this->save();
    }

    /**
     * @inheritdoc
     */
    public function removeAllAssignments()
    {
        $this->_assignments = [];
        $this->save();
    }

tof06 committed
503 504 505 506 507 508 509
    /**
     * @inheritdoc
     */
    protected function removeRule($rule)
    {
        if (isset($this->_rules[$rule->name])) {
            unset($this->_rules[$rule->name]);
510 511 512 513 514 515
            foreach ($this->_items as $item) {
                if ($item->ruleName === $rule->name) {
                    $item->ruleName = null;
                }
            }
            $this->save();
tof06 committed
516 517 518 519 520 521 522 523 524 525 526 527
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    protected function addRule($rule)
    {
        $this->_rules[$rule->name] = $rule;
528
        $this->save();
tof06 committed
529 530 531 532 533 534 535 536 537 538 539
        return true;
    }

    /**
     * @inheritdoc
     */
    protected function updateItem($name, $item)
    {
        $this->_items[$item->name] = $item;
        if ($name !== $item->name) {
            if (isset($this->_items[$item->name])) {
540
                throw new InvalidParamException("Unable to change the item name. The name '{$item->name}' is already used by another item.");
tof06 committed
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
            }
            if (isset($this->_items[$name])) {
                unset ($this->_items[$name]);

                if (isset($this->_children[$name])) {
                    $this->_children[$item->name] = $this->_children[$name];
                    unset ($this->_children[$name]);
                }
                foreach ($this->_children as &$children) {
                    if (isset($children[$name])) {
                        $children[$item->name] = $children[$name];
                        unset ($children[$name]);
                    }
                }
                foreach ($this->_assignments as &$assignments) {
                    if (isset($assignments[$name])) {
                        $assignments[$item->name] = $assignments[$name];
                        unset($assignments[$name]);
                    }
                }
            }
        }
563
        $this->save();
tof06 committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
        return true;
    }

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

        $this->_items[$item->name] = $item;

582 583
        $this->save();

tof06 committed
584 585 586
        return true;

    }
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605

    /**
     * Loads authorization data from persistent storage.
     */
    public function load()
    {
        $this->_children = [];
        $this->_rules = [];
        $this->_assignments = [];
        $this->_items = [];

        $data = $this->loadFromFile($this->authFile);

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

                $this->_items[$name] = new $class([
                    'name' => $name,
606 607 608 609 610
                    'description' => isset($item['description']) ? $item['description'] : null,
                    'ruleName' => isset($item['ruleName']) ? $item['ruleName'] : null,
                    'data' => isset($item['data']) ? $item['data'] : null,
                    'createdAt' => isset($item['createdAt']) ? $item['createdAt'] : null,
                    'updatedAt' => isset($item['updatedAt']) ? $item['updatedAt'] : null,
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
                ]);
            }

            foreach ($data['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];
                        }
                    }
                }
                if (isset($item['assignments'])) {
                    foreach ($item['assignments'] as $userId => $assignment) {
                        $this->_assignments[$userId][$name] = new Assignment([
                            'userId' => $userId,
                            'roleName' => $assignment['roleName'],
627
                            'createdAt' => isset($assignment['createdAt']) ? $assignment['createdAt'] : null,
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
                        ]);
                    }
                }
            }
        }

        if (isset($data['rules'])) {
            foreach ($data['rules'] as $name => $ruleData) {
                $this->_rules[$name] = unserialize($ruleData);
            }
        }
    }

    /**
     * Saves authorization data into persistent storage.
     */
    public function save()
    {
        $items = [];
        foreach ($this->_items as $name => $item) {
            /** @var Item $item */
649
            $items[$name] = array_filter([
650 651 652 653
                'type' => $item->type,
                'description' => $item->description,
                'ruleName' => $item->ruleName,
                'data' => $item->data,
654
            ]);
655 656 657 658 659 660 661 662 663 664 665 666 667 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 695 696 697 698 699 700 701 702 703 704 705 706
            if (isset($this->_children[$name])) {
                foreach ($this->_children[$name] as $child) {
                    /** @var Item $child */
                    $items[$name]['children'][] = $child->name;
                }
            }
        }

        foreach ($this->_assignments as $userId => $assignments) {
            foreach ($assignments as $name => $assignment) {
                /** @var Assignment $assignment */
                if (isset($items[$name])) {
                    $items[$name]['assignments'][$userId] = [
                        'roleName' => $assignment->roleName,
                    ];
                }
            }
        }

        $rules = [];
        foreach ($this->_rules as $name => $rule) {
            $rules[$name] = serialize($rule);
        }

        $this->saveToFile(['items' => $items, 'rules' => $rules], $this->authFile);
    }

    /**
     * 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)
    {
707
        file_put_contents($file, "<?php\nreturn " . VarDumper::export($data) . ";\n", LOCK_EX);
708 709
    }
}