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

namespace yii\rbac;

use Yii;
use yii\base\Exception;
12 13
use yii\base\InvalidCallException;
use yii\base\InvalidParamException;
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
 * @property Item[] $items The authorization items of the specific type. This property is read-only.
Carsten Brandt committed
27
 * @property Rule[] $rules This property is read-only.
28 29 30 31 32 33 34
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Alexander Kochetov <creocoder@gmail.com>
 * @since 2.0
 */
class PhpManager extends Manager
{
35 36 37 38 39 40 41 42 43 44 45 46
    /**
     * @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';

    private $_items = []; // itemName => item
    private $_children = []; // itemName, childName => child
    private $_assignments = []; // userId, itemName => assignment
47
    private $_rules = []; // ruleName => rule
48

49

50 51 52 53 54 55 56 57 58 59 60 61 62 63
    /**
     * 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();
    }

    /**
     * Performs access check for the specified user.
64 65 66
     * @param mixed $userId the user ID. This can be either an integer or a string representing
     * @param string $itemName the name of the operation that need access check
     * the unique identifier of a user. See [[\yii\web\User::id]].
67
     * @param array $params name-value pairs that would be passed to rules associated
68 69
     * with the tasks and roles assigned to the user. A param with name 'userId' is added to
     * this array, which holds the value of `$userId`.
70 71 72 73 74 75 76 77 78 79 80 81 82
     * @return boolean whether the operations can be performed by the user.
     */
    public function checkAccess($userId, $itemName, $params = [])
    {
        if (!isset($this->_items[$itemName])) {
            return false;
        }
        /** @var Item $item */
        $item = $this->_items[$itemName];
        Yii::trace('Checking permission: ' . $item->getName(), __METHOD__);
        if (!isset($params['userId'])) {
            $params['userId'] = $userId;
        }
83
        if ($this->executeRule($item->ruleName, $params, $item->data)) {
84 85 86 87 88 89
            if (in_array($itemName, $this->defaultRoles)) {
                return true;
            }
            if (isset($this->_assignments[$userId][$itemName])) {
                /** @var Assignment $assignment */
                $assignment = $this->_assignments[$userId][$itemName];
90
                if ($this->executeRule($assignment->ruleName, $params, $assignment->data)) {
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
                    return true;
                }
            }
            foreach ($this->_children as $parentName => $children) {
                if (isset($children[$itemName]) && $this->checkAccess($userId, $parentName, $params)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Adds an item as a child of another item.
106 107 108 109
     * @param string $itemName the parent item name
     * @param string $childName the child item name
     * @return boolean whether the item is added successfully
     * @throws Exception if either parent or child doesn't exist.
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
     * @throws InvalidCallException if item already has a child with $itemName or if a loop has been detected.
     */
    public function addItemChild($itemName, $childName)
    {
        if (!isset($this->_items[$childName], $this->_items[$itemName])) {
            throw new Exception("Either '$itemName' or '$childName' does not exist.");
        }
        /** @var Item $child */
        $child = $this->_items[$childName];
        /** @var Item $item */
        $item = $this->_items[$itemName];
        $this->checkItemChildType($item->type, $child->type);
        if ($this->detectLoop($itemName, $childName)) {
            throw new InvalidCallException("Cannot add '$childName' as a child of '$itemName'. A loop has been detected.");
        }
        if (isset($this->_children[$itemName][$childName])) {
            throw new InvalidCallException("The item '$itemName' already has a child '$childName'.");
        }
        $this->_children[$itemName][$childName] = $this->_items[$childName];

        return true;
    }

    /**
     * Removes a child from its parent.
     * Note, the child item is not deleted. Only the parent-child relationship is removed.
136 137
     * @param string $itemName the parent item name
     * @param string $childName the child item name
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
     * @return boolean whether the removal is successful
     */
    public function removeItemChild($itemName, $childName)
    {
        if (isset($this->_children[$itemName][$childName])) {
            unset($this->_children[$itemName][$childName]);

            return true;
        } else {
            return false;
        }
    }

    /**
     * Returns a value indicating whether a child exists within a parent.
153 154
     * @param string $itemName the parent item name
     * @param string $childName the child item name
155 156 157 158 159 160 161 162 163
     * @return boolean whether the child exists
     */
    public function hasItemChild($itemName, $childName)
    {
        return isset($this->_children[$itemName][$childName]);
    }

    /**
     * Returns the children of the specified item.
164
     * @param string|array $names the parent item name. This can be either a string or an array.
165
     * The latter represents a list of item names.
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
     * @return Item[] all child items of the parent
     */
    public function getItemChildren($names)
    {
        if (is_string($names)) {
            return isset($this->_children[$names]) ? $this->_children[$names] : [];
        }

        $children = [];
        foreach ($names as $name) {
            if (isset($this->_children[$name])) {
                $children = array_merge($children, $this->_children[$name]);
            }
        }

        return $children;
    }

    /**
     * Assigns an authorization item to a user.
186
     *
187
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
188
     * @param string $itemName the item name
189
     * @param string $ruleName the business rule to be executed when [[checkAccess()]] is called
190 191 192
     * for this particular authorization item.
     * @param mixed $data additional data associated with this assignment
     * @return Assignment the authorization assignment information.
193 194
     * @throws InvalidParamException if the item does not exist or if the item has already been assigned to the user
     */
195
    public function assign($userId, $itemName, $ruleName = null, $data = null)
196 197 198 199 200 201 202 203 204 205
    {
        if (!isset($this->_items[$itemName])) {
            throw new InvalidParamException("Unknown authorization item '$itemName'.");
        } elseif (isset($this->_assignments[$userId][$itemName])) {
            throw new InvalidParamException("Authorization item '$itemName' has already been assigned to user '$userId'.");
        } else {
            return $this->_assignments[$userId][$itemName] = new Assignment([
                'manager' => $this,
                'userId' => $userId,
                'itemName' => $itemName,
206
                'ruleName' => $ruleName,
207 208 209 210 211 212 213
                'data' => $data,
            ]);
        }
    }

    /**
     * Revokes an authorization assignment from a user.
214 215
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
     * @param string $itemName the item name
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
     * @return boolean whether removal is successful
     */
    public function revoke($userId, $itemName)
    {
        if (isset($this->_assignments[$userId][$itemName])) {
            unset($this->_assignments[$userId][$itemName]);

            return true;
        } else {
            return false;
        }
    }

    /**
     * Revokes all authorization assignments from a user.
231
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
     * @return boolean whether removal is successful
     */
    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]);

            return true;
        } else {
            return false;
        }
    }

    /**
     * Returns a value indicating whether the item has been assigned to the user.
248 249
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
     * @param string $itemName the item name
250 251 252 253 254 255 256 257 258
     * @return boolean whether the item has been assigned to the user.
     */
    public function isAssigned($userId, $itemName)
    {
        return isset($this->_assignments[$userId][$itemName]);
    }

    /**
     * Returns the item assignment information.
259 260
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
     * @param string $itemName the item name
261
     * @return Assignment the item assignment information. Null is returned if
262
     * the item is not assigned to the user.
263 264 265 266 267 268 269 270
     */
    public function getAssignment($userId, $itemName)
    {
        return isset($this->_assignments[$userId][$itemName]) ? $this->_assignments[$userId][$itemName] : null;
    }

    /**
     * Returns the item assignments for the specified user.
271
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
272
     * @return Assignment[] the item assignment information for the user. An empty array will be
273
     * returned if there is no item assigned to the user.
274 275 276 277 278 279 280 281
     */
    public function getAssignments($userId)
    {
        return isset($this->_assignments[$userId]) ? $this->_assignments[$userId] : [];
    }

    /**
     * Returns the authorization items of the specific type and user.
282 283 284 285 286
     * @param mixed $userId the user ID. Defaults to null, meaning returning all items even if
     * they are not assigned to a user.
     * @param integer $type the item type (0: operation, 1: task, 2: role). Defaults to null,
     * meaning returning all items regardless of their type.
     * @return Item[] the authorization items of the specific type.
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
     */
    public function getItems($userId = null, $type = null)
    {
        if ($userId === null && $type === null) {
            return $this->_items;
        }
        $items = [];
        if ($userId === null) {
            foreach ($this->_items as $name => $item) {
                /** @var Item $item */
                if ($item->type == $type) {
                    $items[$name] = $item;
                }
            }
        } elseif (isset($this->_assignments[$userId])) {
            foreach ($this->_assignments[$userId] as $assignment) {
                /** @var Assignment $assignment */
                $name = $assignment->itemName;
                if (isset($this->_items[$name]) && ($type === null || $this->_items[$name]->type == $type)) {
                    $items[$name] = $this->_items[$name];
                }
            }
        }

        return $items;
    }

    /**
     * Creates an authorization item.
     * An authorization item represents an action permission (e.g. creating a post).
     * It has three types: operation, task and role.
     * Authorization items form a hierarchy. Higher level items inheirt permissions representing
     * by lower level items.
320
     *
321 322 323
     * @param string $name the item name. This must be a unique identifier.
     * @param integer $type the item type (0: operation, 1: task, 2: role).
     * @param string $description description of the item
324
     * @param string $rule business rule associated with the item. This is a piece of
325 326 327
     * PHP code that will be executed when [[checkAccess()]] is called for the item.
     * @param mixed $data additional data associated with the item.
     * @return Item the authorization item
328 329
     * @throws Exception if an item with the same name already exists
     */
330
    public function createItem($name, $type, $description = '', $rule = null, $data = null)
331 332 333 334 335 336 337 338 339 340
    {
        if (isset($this->_items[$name])) {
            throw new Exception('Unable to add an item whose name is the same as an existing item.');
        }

        return $this->_items[$name] = new Item([
            'manager' => $this,
            'name' => $name,
            'type' => $type,
            'description' => $description,
341
            'ruleName' => $rule,
342 343 344 345 346 347
            'data' => $data,
        ]);
    }

    /**
     * Removes the specified authorization item.
348
     * @param string $name the name of the item to be removed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
     * @return boolean whether the item exists in the storage and has been removed
     */
    public function removeItem($name)
    {
        if (isset($this->_items[$name])) {
            foreach ($this->_children as &$children) {
                unset($children[$name]);
            }
            foreach ($this->_assignments as &$assignments) {
                unset($assignments[$name]);
            }
            unset($this->_items[$name]);

            return true;
        } else {
            return false;
        }
    }

    /**
     * Returns the authorization item with the specified name.
370 371
     * @param string $name the name of the item
     * @return Item the authorization item. Null if the item cannot be found.
372 373 374 375 376 377 378 379
     */
    public function getItem($name)
    {
        return isset($this->_items[$name]) ? $this->_items[$name] : null;
    }

    /**
     * Saves an authorization item to persistent storage.
380 381
     * @param Item $item the item to be saved.
     * @param string $oldName the old item name. If null, it means the item name is not changed.
382 383
     * @throws InvalidParamException if an item with the same name already taken
     */
384
    public function saveItem(Item $item, $oldName = null)
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 416
    {
        if ($oldName !== null && ($newName = $item->getName()) !== $oldName) { // name changed
            if (isset($this->_items[$newName])) {
                throw new InvalidParamException("Unable to change the item name. The name '$newName' is already used by another item.");
            }
            if (isset($this->_items[$oldName]) && $this->_items[$oldName] === $item) {
                unset($this->_items[$oldName]);
                $this->_items[$newName] = $item;
                if (isset($this->_children[$oldName])) {
                    $this->_children[$newName] = $this->_children[$oldName];
                    unset($this->_children[$oldName]);
                }
                foreach ($this->_children as &$children) {
                    if (isset($children[$oldName])) {
                        $children[$newName] = $children[$oldName];
                        unset($children[$oldName]);
                    }
                }
                foreach ($this->_assignments as &$assignments) {
                    if (isset($assignments[$oldName])) {
                        $assignments[$newName] = $assignments[$oldName];
                        unset($assignments[$oldName]);
                    }
                }
            }
        }
    }

    /**
     * Saves the changes to an authorization assignment.
     * @param Assignment $assignment the assignment that has been changed.
     */
417
    public function saveAssignment(Assignment $assignment)
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    {
    }

    /**
     * Saves authorization data into persistent storage.
     * If any change is made to the authorization data, please make
     * sure you call this method to save the changed data into persistent storage.
     */
    public function save()
    {
        $items = [];
        foreach ($this->_items as $name => $item) {
            /** @var Item $item */
            $items[$name] = [
                'type' => $item->type,
                'description' => $item->description,
434
                'ruleName' => $item->ruleName,
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
                'data' => $item->data,
            ];
            if (isset($this->_children[$name])) {
                foreach ($this->_children[$name] as $child) {
                    /** @var Item $child */
                    $items[$name]['children'][] = $child->getName();
                }
            }
        }

        foreach ($this->_assignments as $userId => $assignments) {
            foreach ($assignments as $name => $assignment) {
                /** @var Assignment $assignment */
                if (isset($items[$name])) {
                    $items[$name]['assignments'][$userId] = [
450
                        'ruleName' => $assignment->ruleName,
451 452 453 454 455 456
                        'data' => $assignment->data,
                    ];
                }
            }
        }

457 458 459 460 461 462
        $rules = [];
        foreach ($this->_rules as $name => $rule) {
            $rules[$name] = serialize($rule);
        }

        $this->saveToFile(['items' => $items, 'rules' => $rules], $this->authFile);
463 464 465 466 467 468 469 470 471
    }

    /**
     * Loads authorization data.
     */
    public function load()
    {
        $this->clearAll();

472 473 474 475 476 477 478 479 480 481 482 483 484
        $data = $this->loadFromFile($this->authFile);

        if (isset($data['items'])) {
            foreach ($data['items'] as $name => $item) {
                $this->_items[$name] = new Item([
                    'manager' => $this,
                    'name' => $name,
                    'type' => $item['type'],
                    'description' => $item['description'],
                    'ruleName' => $item['ruleName'],
                    'data' => $item['data'],
                ]);
            }
485

486 487 488 489 490 491
            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];
                        }
492 493
                    }
                }
494 495 496 497 498 499 500 501 502 503
                if (isset($item['assignments'])) {
                    foreach ($item['assignments'] as $userId => $assignment) {
                        $this->_assignments[$userId][$name] = new Assignment([
                            'manager' => $this,
                            'userId' => $userId,
                            'itemName' => $name,
                            'ruleName' => $assignment['ruleName'],
                            'data' => $assignment['data'],
                        ]);
                    }
504 505 506
                }
            }
        }
507 508 509 510 511 512

        if (isset($data['rules'])) {
            foreach ($data['rules'] as $name => $ruleData) {
                $this->_rules[$name] = unserialize($ruleData);
            }
        }
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    }

    /**
     * Removes all authorization data.
     */
    public function clearAll()
    {
        $this->clearAssignments();
        $this->_children = [];
        $this->_items = [];
    }

    /**
     * Removes all authorization assignments.
     */
    public function clearAssignments()
    {
        $this->_assignments = [];
    }

    /**
     * Checks whether there is a loop in the authorization item hierarchy.
535 536
     * @param string $itemName parent item name
     * @param string $childName the name of the child item that is to be added to the hierarchy
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
     * @return boolean whether a loop exists
     */
    protected function detectLoop($itemName, $childName)
    {
        if ($childName === $itemName) {
            return true;
        }
        if (!isset($this->_children[$childName], $this->_items[$itemName])) {
            return false;
        }
        foreach ($this->_children[$childName] as $child) {
            /** @var Item $child */
            if ($this->detectLoop($itemName, $child->getName())) {
                return true;
            }
        }

        return false;
    }

    /**
     * Loads the authorization data from a PHP script file.
559 560
     * @param string $file the file path.
     * @return array the authorization data
561 562 563 564 565 566 567 568 569 570 571 572 573
     * @see saveToFile()
     */
    protected function loadFromFile($file)
    {
        if (is_file($file)) {
            return require($file);
        } else {
            return [];
        }
    }

    /**
     * Saves the authorization data to a PHP script file.
574
     * @param array $data the authorization data
575 576 577 578 579 580 581
     * @param string $file the file path.
     * @see loadFromFile()
     */
    protected function saveToFile($data, $file)
    {
        file_put_contents($file, "<?php\nreturn " . var_export($data, true) . ";\n", LOCK_EX);
    }
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604

    /**
     * Removes the specified rule.
     *
     * @param string $name the name of the rule to be removed
     * @return boolean whether the rule exists in the storage and has been removed
     */
    public function removeRule($name)
    {
        if (isset($this->_rules[$name])) {
            unset($this->_rules[$name]);
            return true;
        } else {
            return false;
        }
    }


    /**
     * Saves the changes to the rule.
     *
     * @param Rule $rule the rule that has been changed.
     */
605
    public function insertRule(Rule $rule)
606 607 608 609
    {
        $this->_rules[$rule->name] = $rule;
    }

610 611 612 613 614 615 616 617 618 619 620 621 622 623
    /**
     * Updates existing rule.
     *
     * @param string $name the name of the rule to update
     * @param Rule $rule new rule
     */
    public function updateRule($name, Rule $rule)
    {
        if ($rule->name !== $name) {
            unset($this->_rules[$name]);
        }
        $this->_rules[$rule->name] = $rule;
    }

624 625 626 627 628 629 630 631
    /**
     * Returns rule given its name.
     *
     * @param string $name name of the rule.
     * @return Rule
     */
    public function getRule($name)
    {
632
        return isset($this->_rules[$name]) ? $this->_rules[$name] : null;
633 634 635 636 637 638 639 640 641 642 643
    }

    /**
     * Returns all rules.
     *
     * @return Rule[]
     */
    public function getRules()
    {
        return $this->_rules;
    }
644
}