0 follower

CPhpAuthManager

Package system.web.auth
Inheritance class CPhpAuthManager » CAuthManager » CApplicationComponent » CComponent
Implements IAuthManager, IApplicationComponent
Since 1.0
Version $Id$
Source Code framework/web/auth/CPhpAuthManager.php
CPhpAuthManager 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/auth.php'.

CPhpAuthManager is mainly suitable for authorization data that is not too big (for example, the authorization data for a personal blog system). Use CDbAuthManager for more complex authorization data.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
authFile string the path of the PHP script that contains the authorization data. CPhpAuthManager
authItems array Returns the authorization items of the specific type and user. CPhpAuthManager
behaviors array the behaviors that should be attached to this component. CApplicationComponent
defaultRoles array list of role names that are assigned to all users implicitly. CAuthManager
isInitialized boolean whether this application component has been initialized (i.e., init() is invoked. CApplicationComponent
operations array Returns operations. CAuthManager
roles array Returns roles. CAuthManager
tasks array Returns tasks. CAuthManager

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. CComponent
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
addItemChild() Adds an item as a child of another item. CPhpAuthManager
asa() Returns the named behavior object. CComponent
assign() Assigns an authorization item to a user. CPhpAuthManager
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
checkAccess() Performs access check for the specified user. CPhpAuthManager
clearAll() Removes all authorization data. CPhpAuthManager
clearAuthAssignments() Removes all authorization assignments. CPhpAuthManager
createAuthItem() Creates an authorization item. CPhpAuthManager
createOperation() Creates an operation. CAuthManager
createRole() Creates a role. CAuthManager
createTask() Creates a task. CAuthManager
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
executeBizRule() Executes the specified business rule. CAuthManager
getAuthAssignment() Returns the item assignment information. CPhpAuthManager
getAuthAssignments() Returns the item assignments for the specified user. CPhpAuthManager
getAuthItem() Returns the authorization item with the specified name. CPhpAuthManager
getAuthItems() Returns the authorization items of the specific type and user. CPhpAuthManager
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getIsInitialized() Checks whether this application component has been initialized (i.e., init() is invoked.) CApplicationComponent
getItemChildren() Returns the children of the specified item. CPhpAuthManager
getOperations() Returns operations. CAuthManager
getRoles() Returns roles. CAuthManager
getTasks() Returns tasks. CAuthManager
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasItemChild() Returns a value indicating whether a child exists within a parent. CPhpAuthManager
hasProperty() Determines whether a property is defined. CComponent
init() Initializes the application component. CPhpAuthManager
isAssigned() Returns a value indicating whether the item has been assigned to the user. CPhpAuthManager
load() Loads authorization data. CPhpAuthManager
raiseEvent() Raises an event. CComponent
removeAuthItem() Removes the specified authorization item. CPhpAuthManager
removeItemChild() Removes a child from its parent. CPhpAuthManager
revoke() Revokes an authorization assignment from a user. CPhpAuthManager
save() Saves authorization data into persistent storage. CPhpAuthManager
saveAuthAssignment() Saves the changes to an authorization assignment. CPhpAuthManager
saveAuthItem() Saves an authorization item to persistent storage. CPhpAuthManager

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
checkDefaultRoles() Checks the access based on the default roles as declared in defaultRoles. CPhpAuthManager
checkItemChildType() Checks the item types to make sure a child can be added to a parent. CAuthManager
detectLoop() Checks whether there is a loop in the authorization item hierarchy. CPhpAuthManager
loadFromFile() Loads the authorization data from a PHP script file. CPhpAuthManager
saveToFile() Saves the authorization data to a PHP script file. CPhpAuthManager

Property Details

authFile property
public string $authFile;

the path of the PHP script that contains the authorization data. If not set, it will be using 'protected/data/auth.php' as the data file. Make sure this file is writable by the Web server process if the authorization needs to be changed.

authItems property read-only
public array getAuthItems(integer $type=NULL, mixed $userId=NULL)

Returns the authorization items of the specific type and user.

Method Details

addItemChild() method
public void addItemChild(string $itemName, string $childName)
$itemName string the parent item name
$childName string the child item name
Source Code: framework/web/auth/CPhpAuthManager.php#130 (show)
public function addItemChild($itemName,$childName)
{
    if(!isset(
$this->_items[$childName],$this->_items[$itemName]))
        throw new 
CException(Yii::t('yii','Either "{parent}" or "{child}" does not exist.',array('{child}'=>$childName,'{name}'=>$itemName)));
    
$child=$this->_items[$childName];
    
$item=$this->_items[$itemName];
    
$this->checkItemChildType($item->getType(),$child->getType());
    if(
$this->detectLoop($itemName,$childName))
        throw new 
CException(Yii::t('yii','Cannot add "{child}" as a child of "{parent}". A loop has been detected.',
            array(
'{child}'=>$childName,'{parent}'=>$itemName)));
    if(isset(
$this->_children[$itemName][$childName]))
        throw new 
CException(Yii::t('yii','The item "{parent}" already has a child "{child}".',
            array(
'{child}'=>$childName,'{parent}'=>$itemName)));
    
$this->_children[$itemName][$childName]=$this->_items[$childName];
}

Adds an item as a child of another item.

assign() method
public CAuthAssignment assign(string $itemName, mixed $userId, string $bizRule=NULL, mixed $data=NULL)
$itemName string the item name
$userId mixed the user ID (see IWebUser::getId)
$bizRule string the business rule to be executed when checkAccess is called for this particular authorization item.
$data mixed additional data associated with this assignment
{return} CAuthAssignment the authorization assignment information.
Source Code: framework/web/auth/CPhpAuthManager.php#205 (show)
public function assign($itemName,$userId,$bizRule=null,$data=null)
{
    if(!isset(
$this->_items[$itemName]))
        throw new 
CException(Yii::t('yii','Unknown authorization item "{name}".',array('{name}'=>$itemName)));
    else if(isset(
$this->_assignments[$userId][$itemName]))
        throw new 
CException(Yii::t('yii','Authorization item "{item}" has already been assigned to user "{user}".',
            array(
'{item}'=>$itemName,'{user}'=>$userId)));
    else
        return 
$this->_assignments[$userId][$itemName]=new CAuthAssignment($this,$itemName,$userId,$bizRule,$data);
}

Assigns an authorization item to a user.

checkAccess() method
public boolean checkAccess(string $itemName, mixed $userId, array $params=array ( ))
$itemName string the name of the operation that need access check
$userId mixed the user ID. This should can be either an integer and a string representing the unique identifier of a user. See IWebUser::getId.
$params array name-value pairs that would be passed to biz rules associated with the tasks and roles assigned to the user.
{return} boolean whether the operations can be performed by the user.
Source Code: framework/web/auth/CPhpAuthManager.php#64 (show)
public function checkAccess($itemName,$userId,$params=array())
{
    if(!empty(
$this->defaultRoles) && $this->checkDefaultRoles($itemName,$params))
        return 
true;

    
// check directly assigned items
    
$names=array();
    foreach(
$this->getAuthAssignments($userId) as $assignment)
    {
        
$item=$this->getAuthItem($assignment->getItemName());
        
Yii::trace('Checking permission "'.($item $item->getName() : 'unknown').'"','system.web.auth.CPhpAuthManager');
        if(
$item!==null && $this->executeBizRule($assignment->getBizRule(),$params,$assignment->getData())
            && 
$this->executeBizRule($item->getBizRule(),$params,$item->getData()))
        {
            if(
$item->getName()===$itemName)
                return 
true;
            
$names[]=$item->getName();
        }
    }

    
// check all descendant items
    
while($names!==array())
    {
        
$items=$this->getItemChildren($names);
        
$names=array();
        foreach(
$items as $item)
        {
            
Yii::trace('Checking permission "'.$item->getName().'"','system.web.auth.CPhpAuthManager');
            if(
$this->executeBizRule($item->getBizRule(),$params,$item->getData()))
            {
                if(
$item->getName()===$itemName)
                    return 
true;
                
$names[]=$item->getName();
            }
        }
    }

    return 
false;
}

Performs access check for the specified user.

checkDefaultRoles() method (available since v1.0.3)
protected boolean checkDefaultRoles(string $itemName, array $params)
$itemName string the name of the operation that need access check
$params array name-value pairs that would be passed to biz rules associated with the tasks and roles assigned to the user.
{return} boolean whether the operations can be performed by the user according to the default roles.
Source Code: framework/web/auth/CPhpAuthManager.php#112 (show)
protected function checkDefaultRoles($itemName,$params)
{
    foreach(
$this->defaultRoles as $role)
    {
        
Yii::trace('Checking default role "'.$role.'"','system.web.auth.CPhpAuthManager');            
        
$item=$this->getAuthItem($role);
        if(
$item!==null && $item->checkAccess($itemName,$params))
            return 
true;
    }
    return 
false;
}

Checks the access based on the default roles as declared in defaultRoles.

clearAll() method
public void clearAll()
Source Code: framework/web/auth/CPhpAuthManager.php#475 (show)
public function clearAll()
{
    
$this->clearAuthAssignments();
    
$this->_children=array();
    
$this->_items=array();
}

Removes all authorization data.

clearAuthAssignments() method
public void clearAuthAssignments()
Source Code: framework/web/auth/CPhpAuthManager.php#485 (show)
public function clearAuthAssignments()
{
    
$this->_assignments=array();
}

Removes all authorization assignments.

createAuthItem() method
public CAuthItem createAuthItem(string $name, integer $type, string $description='', string $bizRule=NULL, mixed $data=NULL)
$name string the item name. This must be a unique identifier.
$type integer the item type (0: operation, 1: task, 2: role).
$description string description of the item
$bizRule string business rule associated with the item. This is a piece of PHP code that will be executed when checkAccess is called for the item.
$data mixed additional data associated with the item.
{return} CAuthItem the authorization item
Source Code: framework/web/auth/CPhpAuthManager.php#315 (show)
public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null)
{
    if(isset(
$this->_items[$name]))
        throw new 
CException(Yii::t('yii','Unable to add an item whose name is the same as an existing item.'));
    return 
$this->_items[$name]=new CAuthItem($this,$name,$type,$description,$bizRule,$data);
}

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.

detectLoop() method
protected boolean detectLoop(string $itemName, string $childName)
$itemName string parent item name
$childName string the name of the child item that is to be added to the hierarchy
{return} boolean whether a loop exists
Source Code: framework/web/auth/CPhpAuthManager.php#496 (show)
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)
    {
        if(
$this->detectLoop($itemName,$child->getName()))
            return 
true;
    }
    return 
false;
}

Checks whether there is a loop in the authorization item hierarchy.

getAuthAssignment() method
public CAuthAssignment getAuthAssignment(string $itemName, mixed $userId)
$itemName string the item name
$userId mixed the user ID (see IWebUser::getId)
{return} CAuthAssignment the item assignment information. Null is returned if the item is not assigned to the user.
Source Code: framework/web/auth/CPhpAuthManager.php#251 (show)
public function getAuthAssignment($itemName,$userId)
{
    return isset(
$this->_assignments[$userId][$itemName])?$this->_assignments[$userId][$itemName]:null;
}

Returns the item assignment information.

getAuthAssignments() method
public array getAuthAssignments(mixed $userId)
$userId mixed the user ID (see IWebUser::getId)
{return} array the item assignment information for the user. An empty array will be returned if there is no item assigned to the user.
Source Code: framework/web/auth/CPhpAuthManager.php#262 (show)
public function getAuthAssignments($userId)
{
    return isset(
$this->_assignments[$userId])?$this->_assignments[$userId]:array();
}

Returns the item assignments for the specified user.

getAuthItem() method
public CAuthItem getAuthItem(string $name)
$name string the name of the item
{return} CAuthItem the authorization item. Null if the item cannot be found.
Source Code: framework/web/auth/CPhpAuthManager.php#347 (show)
public function getAuthItem($name)
{
    return isset(
$this->_items[$name])?$this->_items[$name]:null;
}

Returns the authorization item with the specified name.

getAuthItems() method
public array getAuthItems(integer $type=NULL, mixed $userId=NULL)
$type integer the item type (0: operation, 1: task, 2: role). Defaults to null, meaning returning all items regardless of their type.
$userId mixed the user ID. Defaults to null, meaning returning all items even if they are not assigned to a user.
{return} array the authorization items of the specific type.
Source Code: framework/web/auth/CPhpAuthManager.php#275 (show)
public function getAuthItems($type=null,$userId=null)
{
    if(
$type===null && $userId===null)
        return 
$this->_items;
    
$items=array();
    if(
$userId===null)
    {
        foreach(
$this->_items as $name=>$item)
        {
            if(
$item->getType()==$type)
                
$items[$name]=$item;
        }
    }
    else if(isset(
$this->_assignments[$userId]))
    {
        foreach(
$this->_assignments[$userId] as $assignment)
        {
            
$name=$assignment->getItemName();
            if(isset(
$this->_items[$name]) && ($type===null || $this->_items[$name]->getType()==$type))
                
$items[$name]=$this->_items[$name];
        }
    }
    return 
$items;
}

Returns the authorization items of the specific type and user.

getItemChildren() method
public array getItemChildren(mixed $names)
$names mixed the parent item name. This can be either a string or an array. The latter represents a list of item names (available since version 1.0.5).
{return} array all child items of the parent
Source Code: framework/web/auth/CPhpAuthManager.php#181 (show)
public function getItemChildren($names)
{
    if(
is_string($names))
        return isset(
$this->_children[$names]) ? $this->_children[$names] : array();

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

Returns the children of the specified item.

hasItemChild() method
public boolean hasItemChild(string $itemName, string $childName)
$itemName string the parent item name
$childName string the child item name
{return} boolean whether the child exists
Source Code: framework/web/auth/CPhpAuthManager.php#170 (show)
public function hasItemChild($itemName,$childName)
{
    return isset(
$this->_children[$itemName][$childName]);
}

Returns a value indicating whether a child exists within a parent.

init() method
public void init()
Source Code: framework/web/auth/CPhpAuthManager.php#47 (show)
public function init()
{
    
parent::init();
    if(
$this->authFile===null)
        
$this->authFile=Yii::getPathOfAlias('application.data.auth').'.php';
    
$this->load();
}

Initializes the application component. This method overrides parent implementation by loading the authorization data from PHP script.

isAssigned() method
public boolean isAssigned(string $itemName, mixed $userId)
$itemName string the item name
$userId mixed the user ID (see IWebUser::getId)
{return} boolean whether the item has been assigned to the user.
Source Code: framework/web/auth/CPhpAuthManager.php#239 (show)
public function isAssigned($itemName,$userId)
{
    return isset(
$this->_assignments[$userId][$itemName]);
}

Returns a value indicating whether the item has been assigned to the user.

load() method
public void load()
Source Code: framework/web/auth/CPhpAuthManager.php#443 (show)
public function load()
{
    
$this->clearAll();

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

    foreach(
$items as $name=>$item)
        
$this->_items[$name]=new CAuthItem($this,$name,$item['type'],$item['description'],$item['bizRule'],$item['data']);

    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];
            }
        }
        if(isset(
$item['assignments']))
        {
            foreach(
$item['assignments'] as $userId=>$assignment)
            {
                
$this->_assignments[$userId][$name]=new CAuthAssignment($this,$name,$userId,$assignment['bizRule'],$assignment['data']);
            }
        }
    }
}

Loads authorization data.

loadFromFile() method
protected array loadFromFile(string $file)
$file string the file path.
{return} array the authorization data
Source Code: framework/web/auth/CPhpAuthManager.php#517 (show)
protected function loadFromFile($file)
{
    if(
is_file($file))
        return require(
$file);
    else
        return array();
}

Loads the authorization data from a PHP script file.

See Also

removeAuthItem() method
public boolean removeAuthItem(string $name)
$name string the name of the item to be removed
{return} boolean whether the item exists in the storage and has been removed
Source Code: framework/web/auth/CPhpAuthManager.php#327 (show)
public function removeAuthItem($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;
}

Removes the specified authorization item.

removeItemChild() method
public boolean removeItemChild(string $itemName, string $childName)
$itemName string the parent item name
$childName string the child item name
{return} boolean whether the removal is successful
Source Code: framework/web/auth/CPhpAuthManager.php#153 (show)
public function removeItemChild($itemName,$childName)
{
    if(isset(
$this->_children[$itemName][$childName]))
    {
        unset(
$this->_children[$itemName][$childName]);
        return 
true;
    }
    else
        return 
false;
}

Removes a child from its parent. Note, the child item is not deleted. Only the parent-child relationship is removed.

revoke() method
public boolean revoke(string $itemName, mixed $userId)
$itemName string the item name
$userId mixed the user ID (see IWebUser::getId)
{return} boolean whether removal is successful
Source Code: framework/web/auth/CPhpAuthManager.php#222 (show)
public function revoke($itemName,$userId)
{
    if(isset(
$this->_assignments[$userId][$itemName]))
    {
        unset(
$this->_assignments[$userId][$itemName]);
        return 
true;
    }
    else
        return 
false;
}

Revokes an authorization assignment from a user.

save() method
public void save()
Source Code: framework/web/auth/CPhpAuthManager.php#405 (show)
public function save()
{
    
$items=array();
    foreach(
$this->_items as $name=>$item)
    {
        
$items[$name]=array(
            
'type'=>$item->getType(),
            
'description'=>$item->getDescription(),
            
'bizRule'=>$item->getBizRule(),
            
'data'=>$item->getData(),
        );
        if(isset(
$this->_children[$name]))
        {
            foreach(
$this->_children[$name] as $child)
                
$items[$name]['children'][]=$child->getName();
        }
    }

    foreach(
$this->_assignments as $userId=>$assignments)
    {
        foreach(
$assignments as $name=>$assignment)
        {
            if(isset(
$items[$name]))
            {
                
$items[$name]['assignments'][$userId]=array(
                    
'bizRule'=>$assignment->getBizRule(),
                    
'data'=>$assignment->getData(),
                );
            }
        }
    }

    
$this->saveToFile($items,$this->authFile);
}

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.

saveAuthAssignment() method
public void saveAuthAssignment(CAuthAssignment $assignment)
$assignment CAuthAssignment the assignment that has been changed.
Source Code: framework/web/auth/CPhpAuthManager.php#396 (show)
public function saveAuthAssignment($assignment)
{
}

Saves the changes to an authorization assignment.

saveAuthItem() method
public void saveAuthItem(CAuthItem $item, string $oldName=NULL)
$item CAuthItem the item to be saved.
$oldName string the old item name. If null, it means the item name is not changed.
Source Code: framework/web/auth/CPhpAuthManager.php#357 (show)
public function saveAuthItem($item,$oldName=null)
{
    if((
$newName=$item->getName())!==$oldName// name changed
    
{
        if(isset(
$this->_items[$newName]))
            throw new 
CException(Yii::t('yii','Unable to change the item name. The name "{name}" is already used by another item.',array('{name}'=>$newName)));
        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 an authorization item to persistent storage.

saveToFile() method
protected void saveToFile(array $data, string $file)
$data array the authorization data
$file string the file path.
Source Code: framework/web/auth/CPhpAuthManager.php#531 (show)
protected function saveToFile($data,$file)
{
    
file_put_contents($file,"<?php\nreturn ".var_export($data,true).";\n");
}

Saves the authorization data to a PHP script file.

See Also