Added new (clean) yii boilerplate
This commit is contained in:
990
framework/base/CApplication.php
Normal file
990
framework/base/CApplication.php
Normal file
@@ -0,0 +1,990 @@
|
||||
<?php
|
||||
/**
|
||||
* CApplication class file.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CApplication is the base class for all application classes.
|
||||
*
|
||||
* An application serves as the global context that the user request
|
||||
* is being processed. It manages a set of application components that
|
||||
* provide specific functionalities to the whole application.
|
||||
*
|
||||
* The core application components provided by CApplication are the following:
|
||||
* <ul>
|
||||
* <li>{@link getErrorHandler errorHandler}: handles PHP errors and
|
||||
* uncaught exceptions. This application component is dynamically loaded when needed.</li>
|
||||
* <li>{@link getSecurityManager securityManager}: provides security-related
|
||||
* services, such as hashing, encryption. This application component is dynamically
|
||||
* loaded when needed.</li>
|
||||
* <li>{@link getStatePersister statePersister}: provides global state
|
||||
* persistence method. This application component is dynamically loaded when needed.</li>
|
||||
* <li>{@link getCache cache}: provides caching feature. This application component is
|
||||
* disabled by default.</li>
|
||||
* <li>{@link getMessages messages}: provides the message source for translating
|
||||
* application messages. This application component is dynamically loaded when needed.</li>
|
||||
* <li>{@link getCoreMessages coreMessages}: provides the message source for translating
|
||||
* Yii framework messages. This application component is dynamically loaded when needed.</li>
|
||||
* <li>{@link getUrlManager urlManager}: provides URL construction as well as parsing functionality.
|
||||
* This application component is dynamically loaded when needed.</li>
|
||||
* <li>{@link getRequest request}: represents the current HTTP request by encapsulating
|
||||
* the $_SERVER variable and managing cookies sent from and sent to the user.
|
||||
* This application component is dynamically loaded when needed.</li>
|
||||
* <li>{@link getFormat format}: provides a set of commonly used data formatting methods.
|
||||
* This application component is dynamically loaded when needed.</li>
|
||||
* </ul>
|
||||
*
|
||||
* CApplication will undergo the following lifecycles when processing a user request:
|
||||
* <ol>
|
||||
* <li>load application configuration;</li>
|
||||
* <li>set up class autoloader and error handling;</li>
|
||||
* <li>load static application components;</li>
|
||||
* <li>{@link onBeginRequest}: preprocess the user request;</li>
|
||||
* <li>{@link processRequest}: process the user request;</li>
|
||||
* <li>{@link onEndRequest}: postprocess the user request;</li>
|
||||
* </ol>
|
||||
*
|
||||
* Starting from lifecycle 3, if a PHP error or an uncaught exception occurs,
|
||||
* the application will switch to its error handling logic and jump to step 6 afterwards.
|
||||
*
|
||||
* @property string $id The unique identifier for the application.
|
||||
* @property string $basePath The root directory of the application. Defaults to 'protected'.
|
||||
* @property string $runtimePath The directory that stores runtime files. Defaults to 'protected/runtime'.
|
||||
* @property string $extensionPath The directory that contains all extensions. Defaults to the 'extensions' directory under 'protected'.
|
||||
* @property string $language The language that the user is using and the application should be targeted to.
|
||||
* Defaults to the {@link sourceLanguage source language}.
|
||||
* @property string $timeZone The time zone used by this application.
|
||||
* @property CLocale $locale The locale instance.
|
||||
* @property string $localeDataPath The directory that contains the locale data. It defaults to 'framework/i18n/data'.
|
||||
* @property CNumberFormatter $numberFormatter The locale-dependent number formatter.
|
||||
* The current {@link getLocale application locale} will be used.
|
||||
* @property CDateFormatter $dateFormatter The locale-dependent date formatter.
|
||||
* The current {@link getLocale application locale} will be used.
|
||||
* @property CDbConnection $db The database connection.
|
||||
* @property CErrorHandler $errorHandler The error handler application component.
|
||||
* @property CSecurityManager $securityManager The security manager application component.
|
||||
* @property CStatePersister $statePersister The state persister application component.
|
||||
* @property CCache $cache The cache application component. Null if the component is not enabled.
|
||||
* @property CPhpMessageSource $coreMessages The core message translations.
|
||||
* @property CMessageSource $messages The application message translations.
|
||||
* @property CHttpRequest $request The request component.
|
||||
* @property CUrlManager $urlManager The URL manager component.
|
||||
* @property CController $controller The currently active controller. Null is returned in this base class.
|
||||
* @property string $baseUrl The relative URL for the application.
|
||||
* @property string $homeUrl The homepage URL.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
abstract class CApplication extends CModule
|
||||
{
|
||||
/**
|
||||
* @var string the application name. Defaults to 'My Application'.
|
||||
*/
|
||||
public $name='My Application';
|
||||
/**
|
||||
* @var string the charset currently used for the application. Defaults to 'UTF-8'.
|
||||
*/
|
||||
public $charset='UTF-8';
|
||||
/**
|
||||
* @var string the language that the application is written in. This mainly refers to
|
||||
* the language that the messages and view files are in. Defaults to 'en_us' (US English).
|
||||
*/
|
||||
public $sourceLanguage='en_us';
|
||||
|
||||
private $_id;
|
||||
private $_basePath;
|
||||
private $_runtimePath;
|
||||
private $_extensionPath;
|
||||
private $_globalState;
|
||||
private $_stateChanged;
|
||||
private $_ended=false;
|
||||
private $_language;
|
||||
private $_homeUrl;
|
||||
|
||||
/**
|
||||
* Processes the request.
|
||||
* This is the place where the actual request processing work is done.
|
||||
* Derived classes should override this method.
|
||||
*/
|
||||
abstract public function processRequest();
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
* @param mixed $config application configuration.
|
||||
* If a string, it is treated as the path of the file that contains the configuration;
|
||||
* If an array, it is the actual configuration information.
|
||||
* Please make sure you specify the {@link getBasePath basePath} property in the configuration,
|
||||
* which should point to the directory containing all application logic, template and data.
|
||||
* If not, the directory will be defaulted to 'protected'.
|
||||
*/
|
||||
public function __construct($config=null)
|
||||
{
|
||||
Yii::setApplication($this);
|
||||
|
||||
// set basePath at early as possible to avoid trouble
|
||||
if(is_string($config))
|
||||
$config=require($config);
|
||||
if(isset($config['basePath']))
|
||||
{
|
||||
$this->setBasePath($config['basePath']);
|
||||
unset($config['basePath']);
|
||||
}
|
||||
else
|
||||
$this->setBasePath('protected');
|
||||
Yii::setPathOfAlias('application',$this->getBasePath());
|
||||
Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
|
||||
if(isset($config['extensionPath']))
|
||||
{
|
||||
$this->setExtensionPath($config['extensionPath']);
|
||||
unset($config['extensionPath']);
|
||||
}
|
||||
else
|
||||
Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
|
||||
if(isset($config['aliases']))
|
||||
{
|
||||
$this->setAliases($config['aliases']);
|
||||
unset($config['aliases']);
|
||||
}
|
||||
|
||||
$this->preinit();
|
||||
|
||||
$this->initSystemHandlers();
|
||||
$this->registerCoreComponents();
|
||||
|
||||
$this->configure($config);
|
||||
$this->attachBehaviors($this->behaviors);
|
||||
$this->preloadComponents();
|
||||
|
||||
$this->init();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Runs the application.
|
||||
* This method loads static application components. Derived classes usually overrides this
|
||||
* method to do more application-specific tasks.
|
||||
* Remember to call the parent implementation so that static application components are loaded.
|
||||
*/
|
||||
public function run()
|
||||
{
|
||||
if($this->hasEventHandler('onBeginRequest'))
|
||||
$this->onBeginRequest(new CEvent($this));
|
||||
register_shutdown_function(array($this,'end'),0,false);
|
||||
$this->processRequest();
|
||||
if($this->hasEventHandler('onEndRequest'))
|
||||
$this->onEndRequest(new CEvent($this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminates the application.
|
||||
* This method replaces PHP's exit() function by calling
|
||||
* {@link onEndRequest} before exiting.
|
||||
* @param integer $status exit status (value 0 means normal exit while other values mean abnormal exit).
|
||||
* @param boolean $exit whether to exit the current request. This parameter has been available since version 1.1.5.
|
||||
* It defaults to true, meaning the PHP's exit() function will be called at the end of this method.
|
||||
*/
|
||||
public function end($status=0,$exit=true)
|
||||
{
|
||||
if($this->hasEventHandler('onEndRequest'))
|
||||
$this->onEndRequest(new CEvent($this));
|
||||
if($exit)
|
||||
exit($status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Raised right BEFORE the application processes the request.
|
||||
* @param CEvent $event the event parameter
|
||||
*/
|
||||
public function onBeginRequest($event)
|
||||
{
|
||||
$this->raiseEvent('onBeginRequest',$event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Raised right AFTER the application processes the request.
|
||||
* @param CEvent $event the event parameter
|
||||
*/
|
||||
public function onEndRequest($event)
|
||||
{
|
||||
if(!$this->_ended)
|
||||
{
|
||||
$this->_ended=true;
|
||||
$this->raiseEvent('onEndRequest',$event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the unique identifier for the application.
|
||||
* @return string the unique identifier for the application.
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
if($this->_id!==null)
|
||||
return $this->_id;
|
||||
else
|
||||
return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the unique identifier for the application.
|
||||
* @param string $id the unique identifier for the application.
|
||||
*/
|
||||
public function setId($id)
|
||||
{
|
||||
$this->_id=$id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the root path of the application.
|
||||
* @return string the root directory of the application. Defaults to 'protected'.
|
||||
*/
|
||||
public function getBasePath()
|
||||
{
|
||||
return $this->_basePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the root directory of the application.
|
||||
* This method can only be invoked at the begin of the constructor.
|
||||
* @param string $path the root directory of the application.
|
||||
* @throws CException if the directory does not exist.
|
||||
*/
|
||||
public function setBasePath($path)
|
||||
{
|
||||
if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
|
||||
throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
|
||||
array('{path}'=>$path)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the directory that stores runtime files.
|
||||
* @return string the directory that stores runtime files. Defaults to 'protected/runtime'.
|
||||
*/
|
||||
public function getRuntimePath()
|
||||
{
|
||||
if($this->_runtimePath!==null)
|
||||
return $this->_runtimePath;
|
||||
else
|
||||
{
|
||||
$this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
|
||||
return $this->_runtimePath;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the directory that stores runtime files.
|
||||
* @param string $path the directory that stores runtime files.
|
||||
* @throws CException if the directory does not exist or is not writable
|
||||
*/
|
||||
public function setRuntimePath($path)
|
||||
{
|
||||
if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
|
||||
throw new CException(Yii::t('yii','Application runtime path "{path}" is not valid. Please make sure it is a directory writable by the Web server process.',
|
||||
array('{path}'=>$path)));
|
||||
$this->_runtimePath=$runtimePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the root directory that holds all third-party extensions.
|
||||
* @return string the directory that contains all extensions. Defaults to the 'extensions' directory under 'protected'.
|
||||
*/
|
||||
public function getExtensionPath()
|
||||
{
|
||||
return Yii::getPathOfAlias('ext');
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the root directory that holds all third-party extensions.
|
||||
* @param string $path the directory that contains all third-party extensions.
|
||||
* @throws CException if the directory does not exist
|
||||
*/
|
||||
public function setExtensionPath($path)
|
||||
{
|
||||
if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
|
||||
throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
|
||||
array('{path}'=>$path)));
|
||||
Yii::setPathOfAlias('ext',$extensionPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the language that the user is using and the application should be targeted to.
|
||||
* @return string the language that the user is using and the application should be targeted to.
|
||||
* Defaults to the {@link sourceLanguage source language}.
|
||||
*/
|
||||
public function getLanguage()
|
||||
{
|
||||
return $this->_language===null ? $this->sourceLanguage : $this->_language;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies which language the application is targeted to.
|
||||
*
|
||||
* This is the language that the application displays to end users.
|
||||
* If set null, it uses the {@link sourceLanguage source language}.
|
||||
*
|
||||
* Unless your application needs to support multiple languages, you should always
|
||||
* set this language to null to maximize the application's performance.
|
||||
* @param string $language the user language (e.g. 'en_US', 'zh_CN').
|
||||
* If it is null, the {@link sourceLanguage} will be used.
|
||||
*/
|
||||
public function setLanguage($language)
|
||||
{
|
||||
$this->_language=$language;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the time zone used by this application.
|
||||
* This is a simple wrapper of PHP function date_default_timezone_get().
|
||||
* @return string the time zone used by this application.
|
||||
* @see http://php.net/manual/en/function.date-default-timezone-get.php
|
||||
*/
|
||||
public function getTimeZone()
|
||||
{
|
||||
return date_default_timezone_get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the time zone used by this application.
|
||||
* This is a simple wrapper of PHP function date_default_timezone_set().
|
||||
* @param string $value the time zone used by this application.
|
||||
* @see http://php.net/manual/en/function.date-default-timezone-set.php
|
||||
*/
|
||||
public function setTimeZone($value)
|
||||
{
|
||||
date_default_timezone_set($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the localized version of a specified file.
|
||||
*
|
||||
* The searching is based on the specified language code. In particular,
|
||||
* a file with the same name will be looked for under the subdirectory
|
||||
* named as the locale ID. For example, given the file "path/to/view.php"
|
||||
* and locale ID "zh_cn", the localized file will be looked for as
|
||||
* "path/to/zh_cn/view.php". If the file is not found, the original file
|
||||
* will be returned.
|
||||
*
|
||||
* For consistency, it is recommended that the locale ID is given
|
||||
* in lower case and in the format of LanguageID_RegionID (e.g. "en_us").
|
||||
*
|
||||
* @param string $srcFile the original file
|
||||
* @param string $srcLanguage the language that the original file is in. If null, the application {@link sourceLanguage source language} is used.
|
||||
* @param string $language the desired language that the file should be localized to. If null, the {@link getLanguage application language} will be used.
|
||||
* @return string the matching localized file. The original file is returned if no localized version is found
|
||||
* or if source language is the same as the desired language.
|
||||
*/
|
||||
public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
|
||||
{
|
||||
if($srcLanguage===null)
|
||||
$srcLanguage=$this->sourceLanguage;
|
||||
if($language===null)
|
||||
$language=$this->getLanguage();
|
||||
if($language===$srcLanguage)
|
||||
return $srcFile;
|
||||
$desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
|
||||
return is_file($desiredFile) ? $desiredFile : $srcFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the locale instance.
|
||||
* @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used.
|
||||
* @return CLocale the locale instance
|
||||
*/
|
||||
public function getLocale($localeID=null)
|
||||
{
|
||||
return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the directory that contains the locale data.
|
||||
* @return string the directory that contains the locale data. It defaults to 'framework/i18n/data'.
|
||||
* @since 1.1.0
|
||||
*/
|
||||
public function getLocaleDataPath()
|
||||
{
|
||||
return CLocale::$dataPath===null ? Yii::getPathOfAlias('system.i18n.data') : CLocale::$dataPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the directory that contains the locale data.
|
||||
* @param string $value the directory that contains the locale data.
|
||||
* @since 1.1.0
|
||||
*/
|
||||
public function setLocaleDataPath($value)
|
||||
{
|
||||
CLocale::$dataPath=$value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return CNumberFormatter the locale-dependent number formatter.
|
||||
* The current {@link getLocale application locale} will be used.
|
||||
*/
|
||||
public function getNumberFormatter()
|
||||
{
|
||||
return $this->getLocale()->getNumberFormatter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the locale-dependent date formatter.
|
||||
* @return CDateFormatter the locale-dependent date formatter.
|
||||
* The current {@link getLocale application locale} will be used.
|
||||
*/
|
||||
public function getDateFormatter()
|
||||
{
|
||||
return $this->getLocale()->getDateFormatter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the database connection component.
|
||||
* @return CDbConnection the database connection
|
||||
*/
|
||||
public function getDb()
|
||||
{
|
||||
return $this->getComponent('db');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the error handler component.
|
||||
* @return CErrorHandler the error handler application component.
|
||||
*/
|
||||
public function getErrorHandler()
|
||||
{
|
||||
return $this->getComponent('errorHandler');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the security manager component.
|
||||
* @return CSecurityManager the security manager application component.
|
||||
*/
|
||||
public function getSecurityManager()
|
||||
{
|
||||
return $this->getComponent('securityManager');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the state persister component.
|
||||
* @return CStatePersister the state persister application component.
|
||||
*/
|
||||
public function getStatePersister()
|
||||
{
|
||||
return $this->getComponent('statePersister');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the cache component.
|
||||
* @return CCache the cache application component. Null if the component is not enabled.
|
||||
*/
|
||||
public function getCache()
|
||||
{
|
||||
return $this->getComponent('cache');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the core message translations component.
|
||||
* @return CPhpMessageSource the core message translations
|
||||
*/
|
||||
public function getCoreMessages()
|
||||
{
|
||||
return $this->getComponent('coreMessages');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the application message translations component.
|
||||
* @return CMessageSource the application message translations
|
||||
*/
|
||||
public function getMessages()
|
||||
{
|
||||
return $this->getComponent('messages');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the request component.
|
||||
* @return CHttpRequest the request component
|
||||
*/
|
||||
public function getRequest()
|
||||
{
|
||||
return $this->getComponent('request');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the URL manager component.
|
||||
* @return CUrlManager the URL manager component
|
||||
*/
|
||||
public function getUrlManager()
|
||||
{
|
||||
return $this->getComponent('urlManager');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return CController the currently active controller. Null is returned in this base class.
|
||||
* @since 1.1.8
|
||||
*/
|
||||
public function getController()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a relative URL based on the given controller and action information.
|
||||
* @param string $route the URL route. This should be in the format of 'ControllerID/ActionID'.
|
||||
* @param array $params additional GET parameters (name=>value). Both the name and value will be URL-encoded.
|
||||
* @param string $ampersand the token separating name-value pairs in the URL.
|
||||
* @return string the constructed URL
|
||||
*/
|
||||
public function createUrl($route,$params=array(),$ampersand='&')
|
||||
{
|
||||
return $this->getUrlManager()->createUrl($route,$params,$ampersand);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an absolute URL based on the given controller and action information.
|
||||
* @param string $route the URL route. This should be in the format of 'ControllerID/ActionID'.
|
||||
* @param array $params additional GET parameters (name=>value). Both the name and value will be URL-encoded.
|
||||
* @param string $schema schema to use (e.g. http, https). If empty, the schema used for the current request will be used.
|
||||
* @param string $ampersand the token separating name-value pairs in the URL.
|
||||
* @return string the constructed URL
|
||||
*/
|
||||
public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
|
||||
{
|
||||
$url=$this->createUrl($route,$params,$ampersand);
|
||||
if(strpos($url,'http')===0)
|
||||
return $url;
|
||||
else
|
||||
return $this->getRequest()->getHostInfo($schema).$url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the relative URL for the application.
|
||||
* This is a shortcut method to {@link CHttpRequest::getBaseUrl()}.
|
||||
* @param boolean $absolute whether to return an absolute URL. Defaults to false, meaning returning a relative one.
|
||||
* @return string the relative URL for the application
|
||||
* @see CHttpRequest::getBaseUrl()
|
||||
*/
|
||||
public function getBaseUrl($absolute=false)
|
||||
{
|
||||
return $this->getRequest()->getBaseUrl($absolute);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string the homepage URL
|
||||
*/
|
||||
public function getHomeUrl()
|
||||
{
|
||||
if($this->_homeUrl===null)
|
||||
{
|
||||
if($this->getUrlManager()->showScriptName)
|
||||
return $this->getRequest()->getScriptUrl();
|
||||
else
|
||||
return $this->getRequest()->getBaseUrl().'/';
|
||||
}
|
||||
else
|
||||
return $this->_homeUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $value the homepage URL
|
||||
*/
|
||||
public function setHomeUrl($value)
|
||||
{
|
||||
$this->_homeUrl=$value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a global value.
|
||||
*
|
||||
* A global value is one that is persistent across users sessions and requests.
|
||||
* @param string $key the name of the value to be returned
|
||||
* @param mixed $defaultValue the default value. If the named global value is not found, this will be returned instead.
|
||||
* @return mixed the named global value
|
||||
* @see setGlobalState
|
||||
*/
|
||||
public function getGlobalState($key,$defaultValue=null)
|
||||
{
|
||||
if($this->_globalState===null)
|
||||
$this->loadGlobalState();
|
||||
if(isset($this->_globalState[$key]))
|
||||
return $this->_globalState[$key];
|
||||
else
|
||||
return $defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a global value.
|
||||
*
|
||||
* A global value is one that is persistent across users sessions and requests.
|
||||
* Make sure that the value is serializable and unserializable.
|
||||
* @param string $key the name of the value to be saved
|
||||
* @param mixed $value the global value to be saved. It must be serializable.
|
||||
* @param mixed $defaultValue the default value. If the named global value is the same as this value, it will be cleared from the current storage.
|
||||
* @see getGlobalState
|
||||
*/
|
||||
public function setGlobalState($key,$value,$defaultValue=null)
|
||||
{
|
||||
if($this->_globalState===null)
|
||||
$this->loadGlobalState();
|
||||
|
||||
$changed=$this->_stateChanged;
|
||||
if($value===$defaultValue)
|
||||
{
|
||||
if(isset($this->_globalState[$key]))
|
||||
{
|
||||
unset($this->_globalState[$key]);
|
||||
$this->_stateChanged=true;
|
||||
}
|
||||
}
|
||||
elseif(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
|
||||
{
|
||||
$this->_globalState[$key]=$value;
|
||||
$this->_stateChanged=true;
|
||||
}
|
||||
|
||||
if($this->_stateChanged!==$changed)
|
||||
$this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears a global value.
|
||||
*
|
||||
* The value cleared will no longer be available in this request and the following requests.
|
||||
* @param string $key the name of the value to be cleared
|
||||
*/
|
||||
public function clearGlobalState($key)
|
||||
{
|
||||
$this->setGlobalState($key,true,true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the global state data from persistent storage.
|
||||
* @see getStatePersister
|
||||
* @throws CException if the state persister is not available
|
||||
*/
|
||||
public function loadGlobalState()
|
||||
{
|
||||
$persister=$this->getStatePersister();
|
||||
if(($this->_globalState=$persister->load())===null)
|
||||
$this->_globalState=array();
|
||||
$this->_stateChanged=false;
|
||||
$this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the global state data into persistent storage.
|
||||
* @see getStatePersister
|
||||
* @throws CException if the state persister is not available
|
||||
*/
|
||||
public function saveGlobalState()
|
||||
{
|
||||
if($this->_stateChanged)
|
||||
{
|
||||
$this->_stateChanged=false;
|
||||
$this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
|
||||
$this->getStatePersister()->save($this->_globalState);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles uncaught PHP exceptions.
|
||||
*
|
||||
* This method is implemented as a PHP exception handler. It requires
|
||||
* that constant YII_ENABLE_EXCEPTION_HANDLER be defined true.
|
||||
*
|
||||
* This method will first raise an {@link onException} event.
|
||||
* If the exception is not handled by any event handler, it will call
|
||||
* {@link getErrorHandler errorHandler} to process the exception.
|
||||
*
|
||||
* The application will be terminated by this method.
|
||||
*
|
||||
* @param Exception $exception exception that is not caught
|
||||
*/
|
||||
public function handleException($exception)
|
||||
{
|
||||
// disable error capturing to avoid recursive errors
|
||||
restore_error_handler();
|
||||
restore_exception_handler();
|
||||
|
||||
$category='exception.'.get_class($exception);
|
||||
if($exception instanceof CHttpException)
|
||||
$category.='.'.$exception->statusCode;
|
||||
// php <5.2 doesn't support string conversion auto-magically
|
||||
$message=$exception->__toString();
|
||||
if(isset($_SERVER['REQUEST_URI']))
|
||||
$message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
|
||||
if(isset($_SERVER['HTTP_REFERER']))
|
||||
$message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
|
||||
$message.="\n---";
|
||||
Yii::log($message,CLogger::LEVEL_ERROR,$category);
|
||||
|
||||
try
|
||||
{
|
||||
$event=new CExceptionEvent($this,$exception);
|
||||
$this->onException($event);
|
||||
if(!$event->handled)
|
||||
{
|
||||
// try an error handler
|
||||
if(($handler=$this->getErrorHandler())!==null)
|
||||
$handler->handle($event);
|
||||
else
|
||||
$this->displayException($exception);
|
||||
}
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
$this->displayException($e);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
$this->end(1);
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
// use the most primitive way to log error
|
||||
$msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
|
||||
$msg .= $e->getTraceAsString()."\n";
|
||||
$msg .= "Previous exception:\n";
|
||||
$msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
|
||||
$msg .= $exception->getTraceAsString()."\n";
|
||||
$msg .= '$_SERVER='.var_export($_SERVER,true);
|
||||
error_log($msg);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles PHP execution errors such as warnings, notices.
|
||||
*
|
||||
* This method is implemented as a PHP error handler. It requires
|
||||
* that constant YII_ENABLE_ERROR_HANDLER be defined true.
|
||||
*
|
||||
* This method will first raise an {@link onError} event.
|
||||
* If the error is not handled by any event handler, it will call
|
||||
* {@link getErrorHandler errorHandler} to process the error.
|
||||
*
|
||||
* The application will be terminated by this method.
|
||||
*
|
||||
* @param integer $code the level of the error raised
|
||||
* @param string $message the error message
|
||||
* @param string $file the filename that the error was raised in
|
||||
* @param integer $line the line number the error was raised at
|
||||
*/
|
||||
public function handleError($code,$message,$file,$line)
|
||||
{
|
||||
if($code & error_reporting())
|
||||
{
|
||||
// disable error capturing to avoid recursive errors
|
||||
restore_error_handler();
|
||||
restore_exception_handler();
|
||||
|
||||
$log="$message ($file:$line)\nStack trace:\n";
|
||||
$trace=debug_backtrace();
|
||||
// skip the first 3 stacks as they do not tell the error position
|
||||
if(count($trace)>3)
|
||||
$trace=array_slice($trace,3);
|
||||
foreach($trace as $i=>$t)
|
||||
{
|
||||
if(!isset($t['file']))
|
||||
$t['file']='unknown';
|
||||
if(!isset($t['line']))
|
||||
$t['line']=0;
|
||||
if(!isset($t['function']))
|
||||
$t['function']='unknown';
|
||||
$log.="#$i {$t['file']}({$t['line']}): ";
|
||||
if(isset($t['object']) && is_object($t['object']))
|
||||
$log.=get_class($t['object']).'->';
|
||||
$log.="{$t['function']}()\n";
|
||||
}
|
||||
if(isset($_SERVER['REQUEST_URI']))
|
||||
$log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
|
||||
Yii::log($log,CLogger::LEVEL_ERROR,'php');
|
||||
|
||||
try
|
||||
{
|
||||
Yii::import('CErrorEvent',true);
|
||||
$event=new CErrorEvent($this,$code,$message,$file,$line);
|
||||
$this->onError($event);
|
||||
if(!$event->handled)
|
||||
{
|
||||
// try an error handler
|
||||
if(($handler=$this->getErrorHandler())!==null)
|
||||
$handler->handle($event);
|
||||
else
|
||||
$this->displayError($code,$message,$file,$line);
|
||||
}
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
$this->displayException($e);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
$this->end(1);
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
// use the most primitive way to log error
|
||||
$msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
|
||||
$msg .= $e->getTraceAsString()."\n";
|
||||
$msg .= "Previous error:\n";
|
||||
$msg .= $log."\n";
|
||||
$msg .= '$_SERVER='.var_export($_SERVER,true);
|
||||
error_log($msg);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Raised when an uncaught PHP exception occurs.
|
||||
*
|
||||
* An event handler can set the {@link CExceptionEvent::handled handled}
|
||||
* property of the event parameter to be true to indicate no further error
|
||||
* handling is needed. Otherwise, the {@link getErrorHandler errorHandler}
|
||||
* application component will continue processing the error.
|
||||
*
|
||||
* @param CExceptionEvent $event event parameter
|
||||
*/
|
||||
public function onException($event)
|
||||
{
|
||||
$this->raiseEvent('onException',$event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Raised when a PHP execution error occurs.
|
||||
*
|
||||
* An event handler can set the {@link CErrorEvent::handled handled}
|
||||
* property of the event parameter to be true to indicate no further error
|
||||
* handling is needed. Otherwise, the {@link getErrorHandler errorHandler}
|
||||
* application component will continue processing the error.
|
||||
*
|
||||
* @param CErrorEvent $event event parameter
|
||||
*/
|
||||
public function onError($event)
|
||||
{
|
||||
$this->raiseEvent('onError',$event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the captured PHP error.
|
||||
* This method displays the error in HTML when there is
|
||||
* no active error handler.
|
||||
* @param integer $code error code
|
||||
* @param string $message error message
|
||||
* @param string $file error file
|
||||
* @param string $line error line
|
||||
*/
|
||||
public function displayError($code,$message,$file,$line)
|
||||
{
|
||||
if(YII_DEBUG)
|
||||
{
|
||||
echo "<h1>PHP Error [$code]</h1>\n";
|
||||
echo "<p>$message ($file:$line)</p>\n";
|
||||
echo '<pre>';
|
||||
|
||||
$trace=debug_backtrace();
|
||||
// skip the first 3 stacks as they do not tell the error position
|
||||
if(count($trace)>3)
|
||||
$trace=array_slice($trace,3);
|
||||
foreach($trace as $i=>$t)
|
||||
{
|
||||
if(!isset($t['file']))
|
||||
$t['file']='unknown';
|
||||
if(!isset($t['line']))
|
||||
$t['line']=0;
|
||||
if(!isset($t['function']))
|
||||
$t['function']='unknown';
|
||||
echo "#$i {$t['file']}({$t['line']}): ";
|
||||
if(isset($t['object']) && is_object($t['object']))
|
||||
echo get_class($t['object']).'->';
|
||||
echo "{$t['function']}()\n";
|
||||
}
|
||||
|
||||
echo '</pre>';
|
||||
}
|
||||
else
|
||||
{
|
||||
echo "<h1>PHP Error [$code]</h1>\n";
|
||||
echo "<p>$message</p>\n";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the uncaught PHP exception.
|
||||
* This method displays the exception in HTML when there is
|
||||
* no active error handler.
|
||||
* @param Exception $exception the uncaught exception
|
||||
*/
|
||||
public function displayException($exception)
|
||||
{
|
||||
if(YII_DEBUG)
|
||||
{
|
||||
echo '<h1>'.get_class($exception)."</h1>\n";
|
||||
echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
|
||||
echo '<pre>'.$exception->getTraceAsString().'</pre>';
|
||||
}
|
||||
else
|
||||
{
|
||||
echo '<h1>'.get_class($exception)."</h1>\n";
|
||||
echo '<p>'.$exception->getMessage().'</p>';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the class autoloader and error handlers.
|
||||
*/
|
||||
protected function initSystemHandlers()
|
||||
{
|
||||
if(YII_ENABLE_EXCEPTION_HANDLER)
|
||||
set_exception_handler(array($this,'handleException'));
|
||||
if(YII_ENABLE_ERROR_HANDLER)
|
||||
set_error_handler(array($this,'handleError'),error_reporting());
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the core application components.
|
||||
* @see setComponents
|
||||
*/
|
||||
protected function registerCoreComponents()
|
||||
{
|
||||
$components=array(
|
||||
'coreMessages'=>array(
|
||||
'class'=>'CPhpMessageSource',
|
||||
'language'=>'en_us',
|
||||
'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
|
||||
),
|
||||
'db'=>array(
|
||||
'class'=>'CDbConnection',
|
||||
),
|
||||
'messages'=>array(
|
||||
'class'=>'CPhpMessageSource',
|
||||
),
|
||||
'errorHandler'=>array(
|
||||
'class'=>'CErrorHandler',
|
||||
),
|
||||
'securityManager'=>array(
|
||||
'class'=>'CSecurityManager',
|
||||
),
|
||||
'statePersister'=>array(
|
||||
'class'=>'CStatePersister',
|
||||
),
|
||||
'urlManager'=>array(
|
||||
'class'=>'CUrlManager',
|
||||
),
|
||||
'request'=>array(
|
||||
'class'=>'CHttpRequest',
|
||||
),
|
||||
'format'=>array(
|
||||
'class'=>'CFormatter',
|
||||
),
|
||||
);
|
||||
|
||||
$this->setComponents($components);
|
||||
}
|
||||
}
|
||||
57
framework/base/CApplicationComponent.php
Normal file
57
framework/base/CApplicationComponent.php
Normal file
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
/**
|
||||
* This file contains the base application component class.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CApplicationComponent is the base class for application component classes.
|
||||
*
|
||||
* CApplicationComponent implements the basic methods required by {@link IApplicationComponent}.
|
||||
*
|
||||
* When developing an application component, try to put application component initialization code in
|
||||
* the {@link init()} method instead of the constructor. This has the advantage that
|
||||
* the application component can be customized through application configuration.
|
||||
*
|
||||
* @property boolean $isInitialized Whether this application component has been initialized (ie, {@link init()} is invoked).
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
abstract class CApplicationComponent extends CComponent implements IApplicationComponent
|
||||
{
|
||||
/**
|
||||
* @var array the behaviors that should be attached to this component.
|
||||
* The behaviors will be attached to the component when {@link init} is called.
|
||||
* Please refer to {@link CModel::behaviors} on how to specify the value of this property.
|
||||
*/
|
||||
public $behaviors=array();
|
||||
|
||||
private $_initialized=false;
|
||||
|
||||
/**
|
||||
* Initializes the application component.
|
||||
* This method is required by {@link IApplicationComponent} and is invoked by application.
|
||||
* If you override this method, make sure to call the parent implementation
|
||||
* so that the application component can be marked as initialized.
|
||||
*/
|
||||
public function init()
|
||||
{
|
||||
$this->attachBehaviors($this->behaviors);
|
||||
$this->_initialized=true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if this application component has been initialized.
|
||||
* @return boolean whether this application component has been initialized (ie, {@link init()} is invoked).
|
||||
*/
|
||||
public function getIsInitialized()
|
||||
{
|
||||
return $this->_initialized;
|
||||
}
|
||||
}
|
||||
114
framework/base/CBehavior.php
Normal file
114
framework/base/CBehavior.php
Normal file
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
/**
|
||||
* CBehavior class file.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CBehavior is a convenient base class for behavior classes.
|
||||
*
|
||||
* @property CComponent $owner The owner component that this behavior is attached to.
|
||||
* @property boolean $enabled Whether this behavior is enabled.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
*/
|
||||
class CBehavior extends CComponent implements IBehavior
|
||||
{
|
||||
private $_enabled=false;
|
||||
private $_owner;
|
||||
|
||||
/**
|
||||
* Declares events and the corresponding event handler methods.
|
||||
* The events are defined by the {@link owner} component, while the handler
|
||||
* methods by the behavior class. The handlers will be attached to the corresponding
|
||||
* events when the behavior is attached to the {@link owner} component; and they
|
||||
* will be detached from the events when the behavior is detached from the component.
|
||||
* Make sure you've declared handler method as public.
|
||||
* @return array events (array keys) and the corresponding event handler methods (array values).
|
||||
*/
|
||||
public function events()
|
||||
{
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches the behavior object to the component.
|
||||
* The default implementation will set the {@link owner} property
|
||||
* and attach event handlers as declared in {@link events}.
|
||||
* This method will also set {@link enabled} to true.
|
||||
* Make sure you've declared handler as public and call the parent implementation if you override this method.
|
||||
* @param CComponent $owner the component that this behavior is to be attached to.
|
||||
*/
|
||||
public function attach($owner)
|
||||
{
|
||||
$this->_enabled=true;
|
||||
$this->_owner=$owner;
|
||||
$this->_attachEventHandlers();
|
||||
}
|
||||
|
||||
/**
|
||||
* Detaches the behavior object from the component.
|
||||
* The default implementation will unset the {@link owner} property
|
||||
* and detach event handlers declared in {@link events}.
|
||||
* This method will also set {@link enabled} to false.
|
||||
* Make sure you call the parent implementation if you override this method.
|
||||
* @param CComponent $owner the component that this behavior is to be detached from.
|
||||
*/
|
||||
public function detach($owner)
|
||||
{
|
||||
foreach($this->events() as $event=>$handler)
|
||||
$owner->detachEventHandler($event,array($this,$handler));
|
||||
$this->_owner=null;
|
||||
$this->_enabled=false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return CComponent the owner component that this behavior is attached to.
|
||||
*/
|
||||
public function getOwner()
|
||||
{
|
||||
return $this->_owner;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean whether this behavior is enabled
|
||||
*/
|
||||
public function getEnabled()
|
||||
{
|
||||
return $this->_enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param boolean $value whether this behavior is enabled
|
||||
*/
|
||||
public function setEnabled($value)
|
||||
{
|
||||
$value=(bool)$value;
|
||||
if($this->_enabled!=$value && $this->_owner)
|
||||
{
|
||||
if($value)
|
||||
$this->_attachEventHandlers();
|
||||
else
|
||||
{
|
||||
foreach($this->events() as $event=>$handler)
|
||||
$this->_owner->detachEventHandler($event,array($this,$handler));
|
||||
}
|
||||
}
|
||||
$this->_enabled=$value;
|
||||
}
|
||||
|
||||
private function _attachEventHandlers()
|
||||
{
|
||||
$class=new ReflectionClass($this);
|
||||
foreach($this->events() as $event=>$handler)
|
||||
{
|
||||
if($class->getMethod($handler)->isPublic())
|
||||
$this->_owner->attachEventHandler($event,array($this,$handler));
|
||||
}
|
||||
}
|
||||
}
|
||||
689
framework/base/CComponent.php
Normal file
689
framework/base/CComponent.php
Normal file
@@ -0,0 +1,689 @@
|
||||
<?php
|
||||
/**
|
||||
* This file contains the foundation classes for component-based and event-driven programming.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CComponent is the base class for all components.
|
||||
*
|
||||
* CComponent implements the protocol of defining, using properties and events.
|
||||
*
|
||||
* A property is defined by a getter method, and/or a setter method.
|
||||
* Properties can be accessed in the way like accessing normal object members.
|
||||
* Reading or writing a property will cause the invocation of the corresponding
|
||||
* getter or setter method, e.g
|
||||
* <pre>
|
||||
* $a=$component->text; // equivalent to $a=$component->getText();
|
||||
* $component->text='abc'; // equivalent to $component->setText('abc');
|
||||
* </pre>
|
||||
* The signatures of getter and setter methods are as follows,
|
||||
* <pre>
|
||||
* // getter, defines a readable property 'text'
|
||||
* public function getText() { ... }
|
||||
* // setter, defines a writable property 'text' with $value to be set to the property
|
||||
* public function setText($value) { ... }
|
||||
* </pre>
|
||||
*
|
||||
* An event is defined by the presence of a method whose name starts with 'on'.
|
||||
* The event name is the method name. When an event is raised, functions
|
||||
* (called event handlers) attached to the event will be invoked automatically.
|
||||
*
|
||||
* An event can be raised by calling {@link raiseEvent} method, upon which
|
||||
* the attached event handlers will be invoked automatically in the order they
|
||||
* are attached to the event. Event handlers must have the following signature,
|
||||
* <pre>
|
||||
* function eventHandler($event) { ... }
|
||||
* </pre>
|
||||
* where $event includes parameters associated with the event.
|
||||
*
|
||||
* To attach an event handler to an event, see {@link attachEventHandler}.
|
||||
* You can also use the following syntax:
|
||||
* <pre>
|
||||
* $component->onClick=$callback; // or $component->onClick->add($callback);
|
||||
* </pre>
|
||||
* where $callback refers to a valid PHP callback. Below we show some callback examples:
|
||||
* <pre>
|
||||
* 'handleOnClick' // handleOnClick() is a global function
|
||||
* array($object,'handleOnClick') // using $object->handleOnClick()
|
||||
* array('Page','handleOnClick') // using Page::handleOnClick()
|
||||
* </pre>
|
||||
*
|
||||
* To raise an event, use {@link raiseEvent}. The on-method defining an event is
|
||||
* commonly written like the following:
|
||||
* <pre>
|
||||
* public function onClick($event)
|
||||
* {
|
||||
* $this->raiseEvent('onClick',$event);
|
||||
* }
|
||||
* </pre>
|
||||
* where <code>$event</code> is an instance of {@link CEvent} or its child class.
|
||||
* One can then raise the event by calling the on-method instead of {@link raiseEvent} directly.
|
||||
*
|
||||
* Both property names and event names are case-insensitive.
|
||||
*
|
||||
* CComponent supports behaviors. A behavior is an
|
||||
* instance of {@link IBehavior} which is attached to a component. The methods of
|
||||
* the behavior can be invoked as if they belong to the component. Multiple behaviors
|
||||
* can be attached to the same component.
|
||||
*
|
||||
* To attach a behavior to a component, call {@link attachBehavior}; and to detach the behavior
|
||||
* from the component, call {@link detachBehavior}.
|
||||
*
|
||||
* A behavior can be temporarily enabled or disabled by calling {@link enableBehavior}
|
||||
* or {@link disableBehavior}, respectively. When disabled, the behavior methods cannot
|
||||
* be invoked via the component.
|
||||
*
|
||||
* Starting from version 1.1.0, a behavior's properties (either its public member variables or
|
||||
* its properties defined via getters and/or setters) can be accessed through the component it
|
||||
* is attached to.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
class CComponent
|
||||
{
|
||||
private $_e;
|
||||
private $_m;
|
||||
|
||||
/**
|
||||
* Returns a property value, an event handler list or a behavior based on its name.
|
||||
* Do not call this method. This is a PHP magic method that we override
|
||||
* to allow using the following syntax to read a property or obtain event handlers:
|
||||
* <pre>
|
||||
* $value=$component->propertyName;
|
||||
* $handlers=$component->eventName;
|
||||
* </pre>
|
||||
* @param string $name the property name or event name
|
||||
* @return mixed the property value, event handlers attached to the event, or the named behavior
|
||||
* @throws CException if the property or event is not defined
|
||||
* @see __set
|
||||
*/
|
||||
public function __get($name)
|
||||
{
|
||||
$getter='get'.$name;
|
||||
if(method_exists($this,$getter))
|
||||
return $this->$getter();
|
||||
elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
|
||||
{
|
||||
// duplicating getEventHandlers() here for performance
|
||||
$name=strtolower($name);
|
||||
if(!isset($this->_e[$name]))
|
||||
$this->_e[$name]=new CList;
|
||||
return $this->_e[$name];
|
||||
}
|
||||
elseif(isset($this->_m[$name]))
|
||||
return $this->_m[$name];
|
||||
elseif(is_array($this->_m))
|
||||
{
|
||||
foreach($this->_m as $object)
|
||||
{
|
||||
if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
|
||||
return $object->$name;
|
||||
}
|
||||
}
|
||||
throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
|
||||
array('{class}'=>get_class($this), '{property}'=>$name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets value of a component property.
|
||||
* Do not call this method. This is a PHP magic method that we override
|
||||
* to allow using the following syntax to set a property or attach an event handler
|
||||
* <pre>
|
||||
* $this->propertyName=$value;
|
||||
* $this->eventName=$callback;
|
||||
* </pre>
|
||||
* @param string $name the property name or the event name
|
||||
* @param mixed $value the property value or callback
|
||||
* @return mixed
|
||||
* @throws CException if the property/event is not defined or the property is read only.
|
||||
* @see __get
|
||||
*/
|
||||
public function __set($name,$value)
|
||||
{
|
||||
$setter='set'.$name;
|
||||
if(method_exists($this,$setter))
|
||||
return $this->$setter($value);
|
||||
elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
|
||||
{
|
||||
// duplicating getEventHandlers() here for performance
|
||||
$name=strtolower($name);
|
||||
if(!isset($this->_e[$name]))
|
||||
$this->_e[$name]=new CList;
|
||||
return $this->_e[$name]->add($value);
|
||||
}
|
||||
elseif(is_array($this->_m))
|
||||
{
|
||||
foreach($this->_m as $object)
|
||||
{
|
||||
if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
|
||||
return $object->$name=$value;
|
||||
}
|
||||
}
|
||||
if(method_exists($this,'get'.$name))
|
||||
throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
|
||||
array('{class}'=>get_class($this), '{property}'=>$name)));
|
||||
else
|
||||
throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
|
||||
array('{class}'=>get_class($this), '{property}'=>$name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a property value is null.
|
||||
* Do not call this method. This is a PHP magic method that we override
|
||||
* to allow using isset() to detect if a component property is set or not.
|
||||
* @param string $name the property name or the event name
|
||||
* @return boolean
|
||||
*/
|
||||
public function __isset($name)
|
||||
{
|
||||
$getter='get'.$name;
|
||||
if(method_exists($this,$getter))
|
||||
return $this->$getter()!==null;
|
||||
elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
|
||||
{
|
||||
$name=strtolower($name);
|
||||
return isset($this->_e[$name]) && $this->_e[$name]->getCount();
|
||||
}
|
||||
elseif(is_array($this->_m))
|
||||
{
|
||||
if(isset($this->_m[$name]))
|
||||
return true;
|
||||
foreach($this->_m as $object)
|
||||
{
|
||||
if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
|
||||
return $object->$name!==null;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a component property to be null.
|
||||
* Do not call this method. This is a PHP magic method that we override
|
||||
* to allow using unset() to set a component property to be null.
|
||||
* @param string $name the property name or the event name
|
||||
* @throws CException if the property is read only.
|
||||
* @return mixed
|
||||
*/
|
||||
public function __unset($name)
|
||||
{
|
||||
$setter='set'.$name;
|
||||
if(method_exists($this,$setter))
|
||||
$this->$setter(null);
|
||||
elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
|
||||
unset($this->_e[strtolower($name)]);
|
||||
elseif(is_array($this->_m))
|
||||
{
|
||||
if(isset($this->_m[$name]))
|
||||
$this->detachBehavior($name);
|
||||
else
|
||||
{
|
||||
foreach($this->_m as $object)
|
||||
{
|
||||
if($object->getEnabled())
|
||||
{
|
||||
if(property_exists($object,$name))
|
||||
return $object->$name=null;
|
||||
elseif($object->canSetProperty($name))
|
||||
return $object->$setter(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
elseif(method_exists($this,'get'.$name))
|
||||
throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
|
||||
array('{class}'=>get_class($this), '{property}'=>$name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls the named method which is not a class method.
|
||||
* Do not call this method. This is a PHP magic method that we override
|
||||
* to implement the behavior feature.
|
||||
* @param string $name the method name
|
||||
* @param array $parameters method parameters
|
||||
* @throws CException if current class and its behaviors do not have a method or closure with the given name
|
||||
* @return mixed the method return value
|
||||
*/
|
||||
public function __call($name,$parameters)
|
||||
{
|
||||
if($this->_m!==null)
|
||||
{
|
||||
foreach($this->_m as $object)
|
||||
{
|
||||
if($object->getEnabled() && method_exists($object,$name))
|
||||
return call_user_func_array(array($object,$name),$parameters);
|
||||
}
|
||||
}
|
||||
if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)
|
||||
return call_user_func_array($this->$name, $parameters);
|
||||
throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
|
||||
array('{class}'=>get_class($this), '{name}'=>$name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the named behavior object.
|
||||
* The name 'asa' stands for 'as a'.
|
||||
* @param string $behavior the behavior name
|
||||
* @return IBehavior the behavior object, or null if the behavior does not exist
|
||||
*/
|
||||
public function asa($behavior)
|
||||
{
|
||||
return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches a list of behaviors to the component.
|
||||
* Each behavior is indexed by its name and should be an instance of
|
||||
* {@link IBehavior}, a string specifying the behavior class, or an
|
||||
* array of the following structure:
|
||||
* <pre>
|
||||
* array(
|
||||
* 'class'=>'path.to.BehaviorClass',
|
||||
* 'property1'=>'value1',
|
||||
* 'property2'=>'value2',
|
||||
* )
|
||||
* </pre>
|
||||
* @param array $behaviors list of behaviors to be attached to the component
|
||||
*/
|
||||
public function attachBehaviors($behaviors)
|
||||
{
|
||||
foreach($behaviors as $name=>$behavior)
|
||||
$this->attachBehavior($name,$behavior);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detaches all behaviors from the component.
|
||||
*/
|
||||
public function detachBehaviors()
|
||||
{
|
||||
if($this->_m!==null)
|
||||
{
|
||||
foreach($this->_m as $name=>$behavior)
|
||||
$this->detachBehavior($name);
|
||||
$this->_m=null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches a behavior to this component.
|
||||
* This method will create the behavior object based on the given
|
||||
* configuration. After that, the behavior object will be initialized
|
||||
* by calling its {@link IBehavior::attach} method.
|
||||
* @param string $name the behavior's name. It should uniquely identify this behavior.
|
||||
* @param mixed $behavior the behavior configuration. This is passed as the first
|
||||
* parameter to {@link YiiBase::createComponent} to create the behavior object.
|
||||
* You can also pass an already created behavior instance (the new behavior will replace an already created
|
||||
* behavior with the same name, if it exists).
|
||||
* @return IBehavior the behavior object
|
||||
*/
|
||||
public function attachBehavior($name,$behavior)
|
||||
{
|
||||
if(!($behavior instanceof IBehavior))
|
||||
$behavior=Yii::createComponent($behavior);
|
||||
$behavior->setEnabled(true);
|
||||
$behavior->attach($this);
|
||||
return $this->_m[$name]=$behavior;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detaches a behavior from the component.
|
||||
* The behavior's {@link IBehavior::detach} method will be invoked.
|
||||
* @param string $name the behavior's name. It uniquely identifies the behavior.
|
||||
* @return IBehavior the detached behavior. Null if the behavior does not exist.
|
||||
*/
|
||||
public function detachBehavior($name)
|
||||
{
|
||||
if(isset($this->_m[$name]))
|
||||
{
|
||||
$this->_m[$name]->detach($this);
|
||||
$behavior=$this->_m[$name];
|
||||
unset($this->_m[$name]);
|
||||
return $behavior;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables all behaviors attached to this component.
|
||||
*/
|
||||
public function enableBehaviors()
|
||||
{
|
||||
if($this->_m!==null)
|
||||
{
|
||||
foreach($this->_m as $behavior)
|
||||
$behavior->setEnabled(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables all behaviors attached to this component.
|
||||
*/
|
||||
public function disableBehaviors()
|
||||
{
|
||||
if($this->_m!==null)
|
||||
{
|
||||
foreach($this->_m as $behavior)
|
||||
$behavior->setEnabled(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables an attached behavior.
|
||||
* A behavior is only effective when it is enabled.
|
||||
* A behavior is enabled when first attached.
|
||||
* @param string $name the behavior's name. It uniquely identifies the behavior.
|
||||
*/
|
||||
public function enableBehavior($name)
|
||||
{
|
||||
if(isset($this->_m[$name]))
|
||||
$this->_m[$name]->setEnabled(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables an attached behavior.
|
||||
* A behavior is only effective when it is enabled.
|
||||
* @param string $name the behavior's name. It uniquely identifies the behavior.
|
||||
*/
|
||||
public function disableBehavior($name)
|
||||
{
|
||||
if(isset($this->_m[$name]))
|
||||
$this->_m[$name]->setEnabled(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a property is defined.
|
||||
* A property is defined if there is a getter or setter method
|
||||
* defined in the class. Note, property names are case-insensitive.
|
||||
* @param string $name the property name
|
||||
* @return boolean whether the property is defined
|
||||
* @see canGetProperty
|
||||
* @see canSetProperty
|
||||
*/
|
||||
public function hasProperty($name)
|
||||
{
|
||||
return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a property can be read.
|
||||
* A property can be read if the class has a getter method
|
||||
* for the property name. Note, property name is case-insensitive.
|
||||
* @param string $name the property name
|
||||
* @return boolean whether the property can be read
|
||||
* @see canSetProperty
|
||||
*/
|
||||
public function canGetProperty($name)
|
||||
{
|
||||
return method_exists($this,'get'.$name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a property can be set.
|
||||
* A property can be written if the class has a setter method
|
||||
* for the property name. Note, property name is case-insensitive.
|
||||
* @param string $name the property name
|
||||
* @return boolean whether the property can be written
|
||||
* @see canGetProperty
|
||||
*/
|
||||
public function canSetProperty($name)
|
||||
{
|
||||
return method_exists($this,'set'.$name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether an event is defined.
|
||||
* An event is defined if the class has a method named like 'onXXX'.
|
||||
* Note, event name is case-insensitive.
|
||||
* @param string $name the event name
|
||||
* @return boolean whether an event is defined
|
||||
*/
|
||||
public function hasEvent($name)
|
||||
{
|
||||
return !strncasecmp($name,'on',2) && method_exists($this,$name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the named event has attached handlers.
|
||||
* @param string $name the event name
|
||||
* @return boolean whether an event has been attached one or several handlers
|
||||
*/
|
||||
public function hasEventHandler($name)
|
||||
{
|
||||
$name=strtolower($name);
|
||||
return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of attached event handlers for an event.
|
||||
* @param string $name the event name
|
||||
* @return CList list of attached event handlers for the event
|
||||
* @throws CException if the event is not defined
|
||||
*/
|
||||
public function getEventHandlers($name)
|
||||
{
|
||||
if($this->hasEvent($name))
|
||||
{
|
||||
$name=strtolower($name);
|
||||
if(!isset($this->_e[$name]))
|
||||
$this->_e[$name]=new CList;
|
||||
return $this->_e[$name];
|
||||
}
|
||||
else
|
||||
throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
|
||||
array('{class}'=>get_class($this), '{event}'=>$name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches an event handler to an event.
|
||||
*
|
||||
* An event handler must be a valid PHP callback, i.e., a string referring to
|
||||
* a global function name, or an array containing two elements with
|
||||
* the first element being an object and the second element a method name
|
||||
* of the object.
|
||||
*
|
||||
* An event handler must be defined with the following signature,
|
||||
* <pre>
|
||||
* function handlerName($event) {}
|
||||
* </pre>
|
||||
* where $event includes parameters associated with the event.
|
||||
*
|
||||
* This is a convenient method of attaching a handler to an event.
|
||||
* It is equivalent to the following code:
|
||||
* <pre>
|
||||
* $component->getEventHandlers($eventName)->add($eventHandler);
|
||||
* </pre>
|
||||
*
|
||||
* Using {@link getEventHandlers}, one can also specify the excution order
|
||||
* of multiple handlers attaching to the same event. For example:
|
||||
* <pre>
|
||||
* $component->getEventHandlers($eventName)->insertAt(0,$eventHandler);
|
||||
* </pre>
|
||||
* makes the handler to be invoked first.
|
||||
*
|
||||
* @param string $name the event name
|
||||
* @param callback $handler the event handler
|
||||
* @throws CException if the event is not defined
|
||||
* @see detachEventHandler
|
||||
*/
|
||||
public function attachEventHandler($name,$handler)
|
||||
{
|
||||
$this->getEventHandlers($name)->add($handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detaches an existing event handler.
|
||||
* This method is the opposite of {@link attachEventHandler}.
|
||||
* @param string $name event name
|
||||
* @param callback $handler the event handler to be removed
|
||||
* @return boolean if the detachment process is successful
|
||||
* @see attachEventHandler
|
||||
*/
|
||||
public function detachEventHandler($name,$handler)
|
||||
{
|
||||
if($this->hasEventHandler($name))
|
||||
return $this->getEventHandlers($name)->remove($handler)!==false;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Raises an event.
|
||||
* This method represents the happening of an event. It invokes
|
||||
* all attached handlers for the event.
|
||||
* @param string $name the event name
|
||||
* @param CEvent $event the event parameter
|
||||
* @throws CException if the event is undefined or an event handler is invalid.
|
||||
*/
|
||||
public function raiseEvent($name,$event)
|
||||
{
|
||||
$name=strtolower($name);
|
||||
if(isset($this->_e[$name]))
|
||||
{
|
||||
foreach($this->_e[$name] as $handler)
|
||||
{
|
||||
if(is_string($handler))
|
||||
call_user_func($handler,$event);
|
||||
elseif(is_callable($handler,true))
|
||||
{
|
||||
if(is_array($handler))
|
||||
{
|
||||
// an array: 0 - object, 1 - method name
|
||||
list($object,$method)=$handler;
|
||||
if(is_string($object)) // static method call
|
||||
call_user_func($handler,$event);
|
||||
elseif(method_exists($object,$method))
|
||||
$object->$method($event);
|
||||
else
|
||||
throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
|
||||
array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
|
||||
}
|
||||
else // PHP 5.3: anonymous function
|
||||
call_user_func($handler,$event);
|
||||
}
|
||||
else
|
||||
throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
|
||||
array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
|
||||
// stop further handling if param.handled is set true
|
||||
if(($event instanceof CEvent) && $event->handled)
|
||||
return;
|
||||
}
|
||||
}
|
||||
elseif(YII_DEBUG && !$this->hasEvent($name))
|
||||
throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
|
||||
array('{class}'=>get_class($this), '{event}'=>$name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates a PHP expression or callback under the context of this component.
|
||||
*
|
||||
* Valid PHP callback can be class method name in the form of
|
||||
* array(ClassName/Object, MethodName), or anonymous function (only available in PHP 5.3.0 or above).
|
||||
*
|
||||
* If a PHP callback is used, the corresponding function/method signature should be
|
||||
* <pre>
|
||||
* function foo($param1, $param2, ..., $component) { ... }
|
||||
* </pre>
|
||||
* where the array elements in the second parameter to this method will be passed
|
||||
* to the callback as $param1, $param2, ...; and the last parameter will be the component itself.
|
||||
*
|
||||
* If a PHP expression is used, the second parameter will be "extracted" into PHP variables
|
||||
* that can be directly accessed in the expression. See {@link http://us.php.net/manual/en/function.extract.php PHP extract}
|
||||
* for more details. In the expression, the component object can be accessed using $this.
|
||||
*
|
||||
* A PHP expression can be any PHP code that has a value. To learn more about what an expression is,
|
||||
* please refer to the {@link http://www.php.net/manual/en/language.expressions.php php manual}.
|
||||
*
|
||||
* @param mixed $_expression_ a PHP expression or PHP callback to be evaluated.
|
||||
* @param array $_data_ additional parameters to be passed to the above expression/callback.
|
||||
* @return mixed the expression result
|
||||
* @since 1.1.0
|
||||
*/
|
||||
public function evaluateExpression($_expression_,$_data_=array())
|
||||
{
|
||||
if(is_string($_expression_))
|
||||
{
|
||||
extract($_data_);
|
||||
return eval('return '.$_expression_.';');
|
||||
}
|
||||
else
|
||||
{
|
||||
$_data_[]=$this;
|
||||
return call_user_func_array($_expression_, $_data_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* CEvent is the base class for all event classes.
|
||||
*
|
||||
* It encapsulates the parameters associated with an event.
|
||||
* The {@link sender} property describes who raises the event.
|
||||
* And the {@link handled} property indicates if the event is handled.
|
||||
* If an event handler sets {@link handled} to true, those handlers
|
||||
* that are not invoked yet will not be invoked anymore.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
class CEvent extends CComponent
|
||||
{
|
||||
/**
|
||||
* @var object the sender of this event
|
||||
*/
|
||||
public $sender;
|
||||
/**
|
||||
* @var boolean whether the event is handled. Defaults to false.
|
||||
* When a handler sets this true, the rest of the uninvoked event handlers will not be invoked anymore.
|
||||
*/
|
||||
public $handled=false;
|
||||
/**
|
||||
* @var mixed additional event parameters.
|
||||
* @since 1.1.7
|
||||
*/
|
||||
public $params;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
* @param mixed $sender sender of the event
|
||||
* @param mixed $params additional parameters for the event
|
||||
*/
|
||||
public function __construct($sender=null,$params=null)
|
||||
{
|
||||
$this->sender=$sender;
|
||||
$this->params=$params;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* CEnumerable is the base class for all enumerable types.
|
||||
*
|
||||
* To define an enumerable type, extend CEnumberable and define string constants.
|
||||
* Each constant represents an enumerable value.
|
||||
* The constant name must be the same as the constant value.
|
||||
* For example,
|
||||
* <pre>
|
||||
* class TextAlign extends CEnumerable
|
||||
* {
|
||||
* const Left='Left';
|
||||
* const Right='Right';
|
||||
* }
|
||||
* </pre>
|
||||
* Then, one can use the enumerable values such as TextAlign::Left and
|
||||
* TextAlign::Right.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
class CEnumerable
|
||||
{
|
||||
}
|
||||
53
framework/base/CErrorEvent.php
Normal file
53
framework/base/CErrorEvent.php
Normal file
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
/**
|
||||
* CErrorEvent class file.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CErrorEvent represents the parameter for the {@link CApplication::onError onError} event.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
class CErrorEvent extends CEvent
|
||||
{
|
||||
/**
|
||||
* @var string error code
|
||||
*/
|
||||
public $code;
|
||||
/**
|
||||
* @var string error message
|
||||
*/
|
||||
public $message;
|
||||
/**
|
||||
* @var string error message
|
||||
*/
|
||||
public $file;
|
||||
/**
|
||||
* @var string error file
|
||||
*/
|
||||
public $line;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
* @param mixed $sender sender of the event
|
||||
* @param string $code error code
|
||||
* @param string $message error message
|
||||
* @param string $file error file
|
||||
* @param integer $line error line
|
||||
*/
|
||||
public function __construct($sender,$code,$message,$file,$line)
|
||||
{
|
||||
$this->code=$code;
|
||||
$this->message=$message;
|
||||
$this->file=$file;
|
||||
$this->line=$line;
|
||||
parent::__construct($sender);
|
||||
}
|
||||
}
|
||||
578
framework/base/CErrorHandler.php
Normal file
578
framework/base/CErrorHandler.php
Normal file
@@ -0,0 +1,578 @@
|
||||
<?php
|
||||
/**
|
||||
* This file contains the error handler application component.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
Yii::import('CHtml',true);
|
||||
|
||||
/**
|
||||
* CErrorHandler handles uncaught PHP errors and exceptions.
|
||||
*
|
||||
* It displays these errors using appropriate views based on the
|
||||
* nature of the error and the mode the application runs at.
|
||||
* It also chooses the most preferred language for displaying the error.
|
||||
*
|
||||
* CErrorHandler uses two sets of views:
|
||||
* <ul>
|
||||
* <li>development views, named as <code>exception.php</code>;
|
||||
* <li>production views, named as <code>error<StatusCode>.php</code>;
|
||||
* </ul>
|
||||
* where <StatusCode> stands for the HTTP error code (e.g. error500.php).
|
||||
* Localized views are named similarly but located under a subdirectory
|
||||
* whose name is the language code (e.g. zh_cn/error500.php).
|
||||
*
|
||||
* Development views are displayed when the application is in debug mode
|
||||
* (i.e. YII_DEBUG is defined as true). Detailed error information with source code
|
||||
* are displayed in these views. Production views are meant to be shown
|
||||
* to end-users and are used when the application is in production mode.
|
||||
* For security reasons, they only display the error message without any
|
||||
* sensitive information.
|
||||
*
|
||||
* CErrorHandler looks for the view templates from the following locations in order:
|
||||
* <ol>
|
||||
* <li><code>themes/ThemeName/views/system</code>: when a theme is active.</li>
|
||||
* <li><code>protected/views/system</code></li>
|
||||
* <li><code>framework/views</code></li>
|
||||
* </ol>
|
||||
* If the view is not found in a directory, it will be looked for in the next directory.
|
||||
*
|
||||
* The property {@link maxSourceLines} can be changed to specify the number
|
||||
* of source code lines to be displayed in development views.
|
||||
*
|
||||
* CErrorHandler is a core application component that can be accessed via
|
||||
* {@link CApplication::getErrorHandler()}.
|
||||
*
|
||||
* @property array $error The error details. Null if there is no error.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
class CErrorHandler extends CApplicationComponent
|
||||
{
|
||||
/**
|
||||
* @var integer maximum number of source code lines to be displayed. Defaults to 25.
|
||||
*/
|
||||
public $maxSourceLines=25;
|
||||
|
||||
/**
|
||||
* @var integer maximum number of trace source code lines to be displayed. Defaults to 10.
|
||||
* @since 1.1.6
|
||||
*/
|
||||
public $maxTraceSourceLines = 10;
|
||||
|
||||
/**
|
||||
* @var string the application administrator information (could be a name or email link). It is displayed in error pages to end users. Defaults to 'the webmaster'.
|
||||
*/
|
||||
public $adminInfo='the webmaster';
|
||||
/**
|
||||
* @var boolean whether to discard any existing page output before error display. Defaults to true.
|
||||
*/
|
||||
public $discardOutput=true;
|
||||
/**
|
||||
* @var string the route (eg 'site/error') to the controller action that will be used to display external errors.
|
||||
* Inside the action, it can retrieve the error information by Yii::app()->errorHandler->error.
|
||||
* This property defaults to null, meaning CErrorHandler will handle the error display.
|
||||
*/
|
||||
public $errorAction;
|
||||
|
||||
private $_error;
|
||||
|
||||
/**
|
||||
* Handles the exception/error event.
|
||||
* This method is invoked by the application whenever it captures
|
||||
* an exception or PHP error.
|
||||
* @param CEvent $event the event containing the exception/error information
|
||||
*/
|
||||
public function handle($event)
|
||||
{
|
||||
// set event as handled to prevent it from being handled by other event handlers
|
||||
$event->handled=true;
|
||||
|
||||
if($this->discardOutput)
|
||||
{
|
||||
$gzHandler=false;
|
||||
foreach(ob_list_handlers() as $h)
|
||||
{
|
||||
if(strpos($h,'gzhandler')!==false)
|
||||
$gzHandler=true;
|
||||
}
|
||||
// the following manual level counting is to deal with zlib.output_compression set to On
|
||||
// for an output buffer created by zlib.output_compression set to On ob_end_clean will fail
|
||||
for($level=ob_get_level();$level>0;--$level)
|
||||
{
|
||||
if(!@ob_end_clean())
|
||||
ob_clean();
|
||||
}
|
||||
// reset headers in case there was an ob_start("ob_gzhandler") before
|
||||
if($gzHandler && !headers_sent() && ob_list_handlers()===array())
|
||||
{
|
||||
if(function_exists('header_remove')) // php >= 5.3
|
||||
{
|
||||
header_remove('Vary');
|
||||
header_remove('Content-Encoding');
|
||||
}
|
||||
else
|
||||
{
|
||||
header('Vary:');
|
||||
header('Content-Encoding:');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if($event instanceof CExceptionEvent)
|
||||
$this->handleException($event->exception);
|
||||
else // CErrorEvent
|
||||
$this->handleError($event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the details about the error that is currently being handled.
|
||||
* The error is returned in terms of an array, with the following information:
|
||||
* <ul>
|
||||
* <li>code - the HTTP status code (e.g. 403, 500)</li>
|
||||
* <li>type - the error type (e.g. 'CHttpException', 'PHP Error')</li>
|
||||
* <li>message - the error message</li>
|
||||
* <li>file - the name of the PHP script file where the error occurs</li>
|
||||
* <li>line - the line number of the code where the error occurs</li>
|
||||
* <li>trace - the call stack of the error</li>
|
||||
* <li>source - the context source code where the error occurs</li>
|
||||
* </ul>
|
||||
* @return array the error details. Null if there is no error.
|
||||
*/
|
||||
public function getError()
|
||||
{
|
||||
return $this->_error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the exception.
|
||||
* @param Exception $exception the exception captured
|
||||
*/
|
||||
protected function handleException($exception)
|
||||
{
|
||||
$app=Yii::app();
|
||||
if($app instanceof CWebApplication)
|
||||
{
|
||||
if(($trace=$this->getExactTrace($exception))===null)
|
||||
{
|
||||
$fileName=$exception->getFile();
|
||||
$errorLine=$exception->getLine();
|
||||
}
|
||||
else
|
||||
{
|
||||
$fileName=$trace['file'];
|
||||
$errorLine=$trace['line'];
|
||||
}
|
||||
|
||||
$trace = $exception->getTrace();
|
||||
|
||||
foreach($trace as $i=>$t)
|
||||
{
|
||||
if(!isset($t['file']))
|
||||
$trace[$i]['file']='unknown';
|
||||
|
||||
if(!isset($t['line']))
|
||||
$trace[$i]['line']=0;
|
||||
|
||||
if(!isset($t['function']))
|
||||
$trace[$i]['function']='unknown';
|
||||
|
||||
unset($trace[$i]['object']);
|
||||
}
|
||||
|
||||
$this->_error=$data=array(
|
||||
'code'=>($exception instanceof CHttpException)?$exception->statusCode:500,
|
||||
'type'=>get_class($exception),
|
||||
'errorCode'=>$exception->getCode(),
|
||||
'message'=>$exception->getMessage(),
|
||||
'file'=>$fileName,
|
||||
'line'=>$errorLine,
|
||||
'trace'=>$exception->getTraceAsString(),
|
||||
'traces'=>$trace,
|
||||
);
|
||||
|
||||
if(!headers_sent())
|
||||
header("HTTP/1.0 {$data['code']} ".$this->getHttpHeader($data['code'], get_class($exception)));
|
||||
|
||||
if($exception instanceof CHttpException || !YII_DEBUG)
|
||||
$this->render('error',$data);
|
||||
else
|
||||
{
|
||||
if($this->isAjaxRequest())
|
||||
$app->displayException($exception);
|
||||
else
|
||||
$this->render('exception',$data);
|
||||
}
|
||||
}
|
||||
else
|
||||
$app->displayException($exception);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the PHP error.
|
||||
* @param CErrorEvent $event the PHP error event
|
||||
*/
|
||||
protected function handleError($event)
|
||||
{
|
||||
$trace=debug_backtrace();
|
||||
// skip the first 3 stacks as they do not tell the error position
|
||||
if(count($trace)>3)
|
||||
$trace=array_slice($trace,3);
|
||||
$traceString='';
|
||||
foreach($trace as $i=>$t)
|
||||
{
|
||||
if(!isset($t['file']))
|
||||
$trace[$i]['file']='unknown';
|
||||
|
||||
if(!isset($t['line']))
|
||||
$trace[$i]['line']=0;
|
||||
|
||||
if(!isset($t['function']))
|
||||
$trace[$i]['function']='unknown';
|
||||
|
||||
$traceString.="#$i {$trace[$i]['file']}({$trace[$i]['line']}): ";
|
||||
if(isset($t['object']) && is_object($t['object']))
|
||||
$traceString.=get_class($t['object']).'->';
|
||||
$traceString.="{$trace[$i]['function']}()\n";
|
||||
|
||||
unset($trace[$i]['object']);
|
||||
}
|
||||
|
||||
$app=Yii::app();
|
||||
if($app instanceof CWebApplication)
|
||||
{
|
||||
switch($event->code)
|
||||
{
|
||||
case E_WARNING:
|
||||
$type = 'PHP warning';
|
||||
break;
|
||||
case E_NOTICE:
|
||||
$type = 'PHP notice';
|
||||
break;
|
||||
case E_USER_ERROR:
|
||||
$type = 'User error';
|
||||
break;
|
||||
case E_USER_WARNING:
|
||||
$type = 'User warning';
|
||||
break;
|
||||
case E_USER_NOTICE:
|
||||
$type = 'User notice';
|
||||
break;
|
||||
case E_RECOVERABLE_ERROR:
|
||||
$type = 'Recoverable error';
|
||||
break;
|
||||
default:
|
||||
$type = 'PHP error';
|
||||
}
|
||||
$this->_error=$data=array(
|
||||
'code'=>500,
|
||||
'type'=>$type,
|
||||
'message'=>$event->message,
|
||||
'file'=>$event->file,
|
||||
'line'=>$event->line,
|
||||
'trace'=>$traceString,
|
||||
'traces'=>$trace,
|
||||
);
|
||||
if(!headers_sent())
|
||||
header("HTTP/1.0 500 Internal Server Error");
|
||||
if($this->isAjaxRequest())
|
||||
$app->displayError($event->code,$event->message,$event->file,$event->line);
|
||||
elseif(YII_DEBUG)
|
||||
$this->render('exception',$data);
|
||||
else
|
||||
$this->render('error',$data);
|
||||
}
|
||||
else
|
||||
$app->displayError($event->code,$event->message,$event->file,$event->line);
|
||||
}
|
||||
|
||||
/**
|
||||
* whether the current request is an AJAX (XMLHttpRequest) request.
|
||||
* @return boolean whether the current request is an AJAX request.
|
||||
*/
|
||||
protected function isAjaxRequest()
|
||||
{
|
||||
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the exact trace where the problem occurs.
|
||||
* @param Exception $exception the uncaught exception
|
||||
* @return array the exact trace where the problem occurs
|
||||
*/
|
||||
protected function getExactTrace($exception)
|
||||
{
|
||||
$traces=$exception->getTrace();
|
||||
|
||||
foreach($traces as $trace)
|
||||
{
|
||||
// property access exception
|
||||
if(isset($trace['function']) && ($trace['function']==='__get' || $trace['function']==='__set'))
|
||||
return $trace;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the view.
|
||||
* @param string $view the view name (file name without extension).
|
||||
* See {@link getViewFile} for how a view file is located given its name.
|
||||
* @param array $data data to be passed to the view
|
||||
*/
|
||||
protected function render($view,$data)
|
||||
{
|
||||
if($view==='error' && $this->errorAction!==null)
|
||||
Yii::app()->runController($this->errorAction);
|
||||
else
|
||||
{
|
||||
// additional information to be passed to view
|
||||
$data['version']=$this->getVersionInfo();
|
||||
$data['time']=time();
|
||||
$data['admin']=$this->adminInfo;
|
||||
include($this->getViewFile($view,$data['code']));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines which view file should be used.
|
||||
* @param string $view view name (either 'exception' or 'error')
|
||||
* @param integer $code HTTP status code
|
||||
* @return string view file path
|
||||
*/
|
||||
protected function getViewFile($view,$code)
|
||||
{
|
||||
$viewPaths=array(
|
||||
Yii::app()->getTheme()===null ? null : Yii::app()->getTheme()->getSystemViewPath(),
|
||||
Yii::app() instanceof CWebApplication ? Yii::app()->getSystemViewPath() : null,
|
||||
YII_PATH.DIRECTORY_SEPARATOR.'views',
|
||||
);
|
||||
|
||||
foreach($viewPaths as $i=>$viewPath)
|
||||
{
|
||||
if($viewPath!==null)
|
||||
{
|
||||
$viewFile=$this->getViewFileInternal($viewPath,$view,$code,$i===2?'en_us':null);
|
||||
if(is_file($viewFile))
|
||||
return $viewFile;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks for the view under the specified directory.
|
||||
* @param string $viewPath the directory containing the views
|
||||
* @param string $view view name (either 'exception' or 'error')
|
||||
* @param integer $code HTTP status code
|
||||
* @param string $srcLanguage the language that the view file is in
|
||||
* @return string view file path
|
||||
*/
|
||||
protected function getViewFileInternal($viewPath,$view,$code,$srcLanguage=null)
|
||||
{
|
||||
$app=Yii::app();
|
||||
if($view==='error')
|
||||
{
|
||||
$viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR."error{$code}.php",$srcLanguage);
|
||||
if(!is_file($viewFile))
|
||||
$viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR.'error.php',$srcLanguage);
|
||||
}
|
||||
else
|
||||
$viewFile=$viewPath.DIRECTORY_SEPARATOR."exception.php";
|
||||
return $viewFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns server version information.
|
||||
* If the application is in production mode, empty string is returned.
|
||||
* @return string server version information. Empty if in production mode.
|
||||
*/
|
||||
protected function getVersionInfo()
|
||||
{
|
||||
if(YII_DEBUG)
|
||||
{
|
||||
$version='<a href="http://www.yiiframework.com/">Yii Framework</a>/'.Yii::getVersion();
|
||||
if(isset($_SERVER['SERVER_SOFTWARE']))
|
||||
$version=$_SERVER['SERVER_SOFTWARE'].' '.$version;
|
||||
}
|
||||
else
|
||||
$version='';
|
||||
return $version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts arguments array to its string representation
|
||||
*
|
||||
* @param array $args arguments array to be converted
|
||||
* @return string string representation of the arguments array
|
||||
*/
|
||||
protected function argumentsToString($args)
|
||||
{
|
||||
$count=0;
|
||||
|
||||
$isAssoc=$args!==array_values($args);
|
||||
|
||||
foreach($args as $key => $value)
|
||||
{
|
||||
$count++;
|
||||
if($count>=5)
|
||||
{
|
||||
if($count>5)
|
||||
unset($args[$key]);
|
||||
else
|
||||
$args[$key]='...';
|
||||
continue;
|
||||
}
|
||||
|
||||
if(is_object($value))
|
||||
$args[$key] = get_class($value);
|
||||
elseif(is_bool($value))
|
||||
$args[$key] = $value ? 'true' : 'false';
|
||||
elseif(is_string($value))
|
||||
{
|
||||
if(strlen($value)>64)
|
||||
$args[$key] = '"'.substr($value,0,64).'..."';
|
||||
else
|
||||
$args[$key] = '"'.$value.'"';
|
||||
}
|
||||
elseif(is_array($value))
|
||||
$args[$key] = 'array('.$this->argumentsToString($value).')';
|
||||
elseif($value===null)
|
||||
$args[$key] = 'null';
|
||||
elseif(is_resource($value))
|
||||
$args[$key] = 'resource';
|
||||
|
||||
if(is_string($key))
|
||||
{
|
||||
$args[$key] = '"'.$key.'" => '.$args[$key];
|
||||
}
|
||||
elseif($isAssoc)
|
||||
{
|
||||
$args[$key] = $key.' => '.$args[$key];
|
||||
}
|
||||
}
|
||||
$out = implode(", ", $args);
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a value indicating whether the call stack is from application code.
|
||||
* @param array $trace the trace data
|
||||
* @return boolean whether the call stack is from application code.
|
||||
*/
|
||||
protected function isCoreCode($trace)
|
||||
{
|
||||
if(isset($trace['file']))
|
||||
{
|
||||
$systemPath=realpath(dirname(__FILE__).'/..');
|
||||
return $trace['file']==='unknown' || strpos(realpath($trace['file']),$systemPath.DIRECTORY_SEPARATOR)===0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the source code around the error line.
|
||||
* @param string $file source file path
|
||||
* @param integer $errorLine the error line number
|
||||
* @param integer $maxLines maximum number of lines to display
|
||||
* @return string the rendering result
|
||||
*/
|
||||
protected function renderSourceCode($file,$errorLine,$maxLines)
|
||||
{
|
||||
$errorLine--; // adjust line number to 0-based from 1-based
|
||||
if($errorLine<0 || ($lines=@file($file))===false || ($lineCount=count($lines))<=$errorLine)
|
||||
return '';
|
||||
|
||||
$halfLines=(int)($maxLines/2);
|
||||
$beginLine=$errorLine-$halfLines>0 ? $errorLine-$halfLines:0;
|
||||
$endLine=$errorLine+$halfLines<$lineCount?$errorLine+$halfLines:$lineCount-1;
|
||||
$lineNumberWidth=strlen($endLine+1);
|
||||
|
||||
$output='';
|
||||
for($i=$beginLine;$i<=$endLine;++$i)
|
||||
{
|
||||
$isErrorLine = $i===$errorLine;
|
||||
$code=sprintf("<span class=\"ln".($isErrorLine?' error-ln':'')."\">%0{$lineNumberWidth}d</span> %s",$i+1,CHtml::encode(str_replace("\t",' ',$lines[$i])));
|
||||
if(!$isErrorLine)
|
||||
$output.=$code;
|
||||
else
|
||||
$output.='<span class="error">'.$code.'</span>';
|
||||
}
|
||||
return '<div class="code"><pre>'.$output.'</pre></div>';
|
||||
}
|
||||
/**
|
||||
* Return correct message for each known http error code
|
||||
* @param integer $httpCode error code to map
|
||||
* @param string $replacement replacement error string that is returned if code is unknown
|
||||
* @return string the textual representation of the given error code or the replacement string if the error code is unknown
|
||||
*/
|
||||
protected function getHttpHeader($httpCode, $replacement='')
|
||||
{
|
||||
$httpCodes = array(
|
||||
100 => 'Continue',
|
||||
101 => 'Switching Protocols',
|
||||
102 => 'Processing',
|
||||
118 => 'Connection timed out',
|
||||
200 => 'OK',
|
||||
201 => 'Created',
|
||||
202 => 'Accepted',
|
||||
203 => 'Non-Authoritative',
|
||||
204 => 'No Content',
|
||||
205 => 'Reset Content',
|
||||
206 => 'Partial Content',
|
||||
207 => 'Multi-Status',
|
||||
210 => 'Content Different',
|
||||
300 => 'Multiple Choices',
|
||||
301 => 'Moved Permanently',
|
||||
302 => 'Found',
|
||||
303 => 'See Other',
|
||||
304 => 'Not Modified',
|
||||
305 => 'Use Proxy',
|
||||
307 => 'Temporary Redirect',
|
||||
310 => 'Too many Redirect',
|
||||
400 => 'Bad Request',
|
||||
401 => 'Unauthorized',
|
||||
402 => 'Payment Required',
|
||||
403 => 'Forbidden',
|
||||
404 => 'Not Found',
|
||||
405 => 'Method Not Allowed',
|
||||
406 => 'Not Acceptable',
|
||||
407 => 'Proxy Authentication Required',
|
||||
408 => 'Request Time-out',
|
||||
409 => 'Conflict',
|
||||
410 => 'Gone',
|
||||
411 => 'Length Required',
|
||||
412 => 'Precondition Failed',
|
||||
413 => 'Request Entity Too Large',
|
||||
414 => 'Request-URI Too Long',
|
||||
415 => 'Unsupported Media Type',
|
||||
416 => 'Requested range unsatisfiable',
|
||||
417 => 'Expectation failed',
|
||||
418 => 'I’m a teapot',
|
||||
422 => 'Unprocessable entity',
|
||||
423 => 'Locked',
|
||||
424 => 'Method failure',
|
||||
425 => 'Unordered Collection',
|
||||
426 => 'Upgrade Required',
|
||||
449 => 'Retry With',
|
||||
450 => 'Blocked by Windows Parental Controls',
|
||||
500 => 'Internal Server Error',
|
||||
501 => 'Not Implemented',
|
||||
502 => 'Bad Gateway ou Proxy Error',
|
||||
503 => 'Service Unavailable',
|
||||
504 => 'Gateway Time-out',
|
||||
505 => 'HTTP Version not supported',
|
||||
507 => 'Insufficient storage',
|
||||
509 => 'Bandwidth Limit Exceeded',
|
||||
);
|
||||
if(isset($httpCodes[$httpCode]))
|
||||
return $httpCodes[$httpCode];
|
||||
else
|
||||
return $replacement;
|
||||
}
|
||||
}
|
||||
21
framework/base/CException.php
Normal file
21
framework/base/CException.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
/**
|
||||
* CException class file.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CException represents a generic exception for all purposes.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
class CException extends Exception
|
||||
{
|
||||
}
|
||||
|
||||
35
framework/base/CExceptionEvent.php
Normal file
35
framework/base/CExceptionEvent.php
Normal file
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
/**
|
||||
* CExceptionEvent class file.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CExceptionEvent represents the parameter for the {@link CApplication::onException onException} event.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
class CExceptionEvent extends CEvent
|
||||
{
|
||||
/**
|
||||
* @var CException the exception that this event is about.
|
||||
*/
|
||||
public $exception;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
* @param mixed $sender sender of the event
|
||||
* @param CException $exception the exception
|
||||
*/
|
||||
public function __construct($sender,$exception)
|
||||
{
|
||||
$this->exception=$exception;
|
||||
parent::__construct($sender);
|
||||
}
|
||||
}
|
||||
39
framework/base/CHttpException.php
Normal file
39
framework/base/CHttpException.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
/**
|
||||
* CHttpException class file.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CHttpException represents an exception caused by invalid operations of end-users.
|
||||
*
|
||||
* The HTTP error code can be obtained via {@link statusCode}.
|
||||
* Error handlers may use this status code to decide how to format the error page.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
class CHttpException extends CException
|
||||
{
|
||||
/**
|
||||
* @var integer HTTP status code, such as 403, 404, 500, etc.
|
||||
*/
|
||||
public $statusCode;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
* @param integer $status HTTP status code, such as 404, 500, etc.
|
||||
* @param string $message error message
|
||||
* @param integer $code error code
|
||||
*/
|
||||
public function __construct($status,$message=null,$code=0)
|
||||
{
|
||||
$this->statusCode=$status;
|
||||
parent::__construct($message,$code);
|
||||
}
|
||||
}
|
||||
619
framework/base/CModel.php
Normal file
619
framework/base/CModel.php
Normal file
@@ -0,0 +1,619 @@
|
||||
<?php
|
||||
/**
|
||||
* CModel class file.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* CModel is the base class providing the common features needed by data model objects.
|
||||
*
|
||||
* CModel defines the basic framework for data models that need to be validated.
|
||||
*
|
||||
* @property CList $validatorList All the validators declared in the model.
|
||||
* @property array $validators The validators applicable to the current {@link scenario}.
|
||||
* @property array $errors Errors for all attributes or the specified attribute. Empty array is returned if no error.
|
||||
* @property array $attributes Attribute values (name=>value).
|
||||
* @property string $scenario The scenario that this model is in.
|
||||
* @property array $safeAttributeNames Safe attribute names.
|
||||
* @property CMapIterator $iterator An iterator for traversing the items in the list.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
|
||||
{
|
||||
private $_errors=array(); // attribute name => array of errors
|
||||
private $_validators; // validators
|
||||
private $_scenario=''; // scenario
|
||||
|
||||
/**
|
||||
* Returns the list of attribute names of the model.
|
||||
* @return array list of attribute names.
|
||||
*/
|
||||
abstract public function attributeNames();
|
||||
|
||||
/**
|
||||
* Returns the validation rules for attributes.
|
||||
*
|
||||
* This method should be overridden to declare validation rules.
|
||||
* Each rule is an array with the following structure:
|
||||
* <pre>
|
||||
* array('attribute list', 'validator name', 'on'=>'scenario name', ...validation parameters...)
|
||||
* </pre>
|
||||
* where
|
||||
* <ul>
|
||||
* <li>attribute list: specifies the attributes (separated by commas) to be validated;</li>
|
||||
* <li>validator name: specifies the validator to be used. It can be the name of a model class
|
||||
* method, the name of a built-in validator, or a validator class (or its path alias).
|
||||
* A validation method must have the following signature:
|
||||
* <pre>
|
||||
* // $params refers to validation parameters given in the rule
|
||||
* function validatorName($attribute,$params)
|
||||
* </pre>
|
||||
* A built-in validator refers to one of the validators declared in {@link CValidator::builtInValidators}.
|
||||
* And a validator class is a class extending {@link CValidator}.</li>
|
||||
* <li>on: this specifies the scenarios when the validation rule should be performed.
|
||||
* Separate different scenarios with commas. If this option is not set, the rule
|
||||
* will be applied in any scenario that is not listed in "except". Please see {@link scenario} for more details about this option.</li>
|
||||
* <li>except: this specifies the scenarios when the validation rule should not be performed.
|
||||
* Separate different scenarios with commas. Please see {@link scenario} for more details about this option.</li>
|
||||
* <li>additional parameters are used to initialize the corresponding validator properties.
|
||||
* Please refer to individal validator class API for possible properties.</li>
|
||||
* </ul>
|
||||
*
|
||||
* The following are some examples:
|
||||
* <pre>
|
||||
* array(
|
||||
* array('username', 'required'),
|
||||
* array('username', 'length', 'min'=>3, 'max'=>12),
|
||||
* array('password', 'compare', 'compareAttribute'=>'password2', 'on'=>'register'),
|
||||
* array('password', 'authenticate', 'on'=>'login'),
|
||||
* );
|
||||
* </pre>
|
||||
*
|
||||
* Note, in order to inherit rules defined in the parent class, a child class needs to
|
||||
* merge the parent rules with child rules using functions like array_merge().
|
||||
*
|
||||
* @return array validation rules to be applied when {@link validate()} is called.
|
||||
* @see scenario
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of behaviors that this model should behave as.
|
||||
* The return value should be an array of behavior configurations indexed by
|
||||
* behavior names. Each behavior configuration can be either a string specifying
|
||||
* the behavior class or an array of the following structure:
|
||||
* <pre>
|
||||
* 'behaviorName'=>array(
|
||||
* 'class'=>'path.to.BehaviorClass',
|
||||
* 'property1'=>'value1',
|
||||
* 'property2'=>'value2',
|
||||
* )
|
||||
* </pre>
|
||||
*
|
||||
* Note, the behavior classes must implement {@link IBehavior} or extend from
|
||||
* {@link CBehavior}. Behaviors declared in this method will be attached
|
||||
* to the model when it is instantiated.
|
||||
*
|
||||
* For more details about behaviors, see {@link CComponent}.
|
||||
* @return array the behavior configurations (behavior name=>behavior configuration)
|
||||
*/
|
||||
public function behaviors()
|
||||
{
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the attribute labels.
|
||||
* Attribute labels are mainly used in error messages of validation.
|
||||
* By default an attribute label is generated using {@link generateAttributeLabel}.
|
||||
* This method allows you to explicitly specify attribute labels.
|
||||
*
|
||||
* Note, in order to inherit labels defined in the parent class, a child class needs to
|
||||
* merge the parent labels with child labels using functions like array_merge().
|
||||
*
|
||||
* @return array attribute labels (name=>label)
|
||||
* @see generateAttributeLabel
|
||||
*/
|
||||
public function attributeLabels()
|
||||
{
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the validation.
|
||||
*
|
||||
* This method executes the validation rules as declared in {@link rules}.
|
||||
* Only the rules applicable to the current {@link scenario} will be executed.
|
||||
* A rule is considered applicable to a scenario if its 'on' option is not set
|
||||
* or contains the scenario.
|
||||
*
|
||||
* Errors found during the validation can be retrieved via {@link getErrors}.
|
||||
*
|
||||
* @param array $attributes list of attributes that should be validated. Defaults to null,
|
||||
* meaning any attribute listed in the applicable validation rules should be
|
||||
* validated. If this parameter is given as a list of attributes, only
|
||||
* the listed attributes will be validated.
|
||||
* @param boolean $clearErrors whether to call {@link clearErrors} before performing validation
|
||||
* @return boolean whether the validation is successful without any error.
|
||||
* @see beforeValidate
|
||||
* @see afterValidate
|
||||
*/
|
||||
public function validate($attributes=null, $clearErrors=true)
|
||||
{
|
||||
if($clearErrors)
|
||||
$this->clearErrors();
|
||||
if($this->beforeValidate())
|
||||
{
|
||||
foreach($this->getValidators() as $validator)
|
||||
$validator->validate($this,$attributes);
|
||||
$this->afterValidate();
|
||||
return !$this->hasErrors();
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is invoked after a model instance is created by new operator.
|
||||
* The default implementation raises the {@link onAfterConstruct} event.
|
||||
* You may override this method to do postprocessing after model creation.
|
||||
* Make sure you call the parent implementation so that the event is raised properly.
|
||||
*/
|
||||
protected function afterConstruct()
|
||||
{
|
||||
if($this->hasEventHandler('onAfterConstruct'))
|
||||
$this->onAfterConstruct(new CEvent($this));
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is invoked before validation starts.
|
||||
* The default implementation calls {@link onBeforeValidate} to raise an event.
|
||||
* You may override this method to do preliminary checks before validation.
|
||||
* Make sure the parent implementation is invoked so that the event can be raised.
|
||||
* @return boolean whether validation should be executed. Defaults to true.
|
||||
* If false is returned, the validation will stop and the model is considered invalid.
|
||||
*/
|
||||
protected function beforeValidate()
|
||||
{
|
||||
$event=new CModelEvent($this);
|
||||
$this->onBeforeValidate($event);
|
||||
return $event->isValid;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is invoked after validation ends.
|
||||
* The default implementation calls {@link onAfterValidate} to raise an event.
|
||||
* You may override this method to do postprocessing after validation.
|
||||
* Make sure the parent implementation is invoked so that the event can be raised.
|
||||
*/
|
||||
protected function afterValidate()
|
||||
{
|
||||
$this->onAfterValidate(new CEvent($this));
|
||||
}
|
||||
|
||||
/**
|
||||
* This event is raised after the model instance is created by new operator.
|
||||
* @param CEvent $event the event parameter
|
||||
*/
|
||||
public function onAfterConstruct($event)
|
||||
{
|
||||
$this->raiseEvent('onAfterConstruct',$event);
|
||||
}
|
||||
|
||||
/**
|
||||
* This event is raised before the validation is performed.
|
||||
* @param CModelEvent $event the event parameter
|
||||
*/
|
||||
public function onBeforeValidate($event)
|
||||
{
|
||||
$this->raiseEvent('onBeforeValidate',$event);
|
||||
}
|
||||
|
||||
/**
|
||||
* This event is raised after the validation is performed.
|
||||
* @param CEvent $event the event parameter
|
||||
*/
|
||||
public function onAfterValidate($event)
|
||||
{
|
||||
$this->raiseEvent('onAfterValidate',$event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all the validators declared in the model.
|
||||
* This method differs from {@link getValidators} in that the latter
|
||||
* would only return the validators applicable to the current {@link scenario}.
|
||||
* Also, since this method return a {@link CList} object, you may
|
||||
* manipulate it by inserting or removing validators (useful in behaviors).
|
||||
* For example, <code>$model->validatorList->add($newValidator)</code>.
|
||||
* The change made to the {@link CList} object will persist and reflect
|
||||
* in the result of the next call of {@link getValidators}.
|
||||
* @return CList all the validators declared in the model.
|
||||
* @since 1.1.2
|
||||
*/
|
||||
public function getValidatorList()
|
||||
{
|
||||
if($this->_validators===null)
|
||||
$this->_validators=$this->createValidators();
|
||||
return $this->_validators;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the validators applicable to the current {@link scenario}.
|
||||
* @param string $attribute the name of the attribute whose validators should be returned.
|
||||
* If this is null, the validators for ALL attributes in the model will be returned.
|
||||
* @return array the validators applicable to the current {@link scenario}.
|
||||
*/
|
||||
public function getValidators($attribute=null)
|
||||
{
|
||||
if($this->_validators===null)
|
||||
$this->_validators=$this->createValidators();
|
||||
|
||||
$validators=array();
|
||||
$scenario=$this->getScenario();
|
||||
foreach($this->_validators as $validator)
|
||||
{
|
||||
if($validator->applyTo($scenario))
|
||||
{
|
||||
if($attribute===null || in_array($attribute,$validator->attributes,true))
|
||||
$validators[]=$validator;
|
||||
}
|
||||
}
|
||||
return $validators;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates validator objects based on the specification in {@link rules}.
|
||||
* This method is mainly used internally.
|
||||
* @throws CException if current class has an invalid validation rule
|
||||
* @return CList validators built based on {@link rules()}.
|
||||
*/
|
||||
public function createValidators()
|
||||
{
|
||||
$validators=new CList;
|
||||
foreach($this->rules() as $rule)
|
||||
{
|
||||
if(isset($rule[0],$rule[1])) // attributes, validator name
|
||||
$validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
|
||||
else
|
||||
throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
|
||||
array('{class}'=>get_class($this))));
|
||||
}
|
||||
return $validators;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a value indicating whether the attribute is required.
|
||||
* This is determined by checking if the attribute is associated with a
|
||||
* {@link CRequiredValidator} validation rule in the current {@link scenario}.
|
||||
* @param string $attribute attribute name
|
||||
* @return boolean whether the attribute is required
|
||||
*/
|
||||
public function isAttributeRequired($attribute)
|
||||
{
|
||||
foreach($this->getValidators($attribute) as $validator)
|
||||
{
|
||||
if($validator instanceof CRequiredValidator)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a value indicating whether the attribute is safe for massive assignments.
|
||||
* @param string $attribute attribute name
|
||||
* @return boolean whether the attribute is safe for massive assignments
|
||||
* @since 1.1
|
||||
*/
|
||||
public function isAttributeSafe($attribute)
|
||||
{
|
||||
$attributes=$this->getSafeAttributeNames();
|
||||
return in_array($attribute,$attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the text label for the specified attribute.
|
||||
* @param string $attribute the attribute name
|
||||
* @return string the attribute label
|
||||
* @see generateAttributeLabel
|
||||
* @see attributeLabels
|
||||
*/
|
||||
public function getAttributeLabel($attribute)
|
||||
{
|
||||
$labels=$this->attributeLabels();
|
||||
if(isset($labels[$attribute]))
|
||||
return $labels[$attribute];
|
||||
else
|
||||
return $this->generateAttributeLabel($attribute);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a value indicating whether there is any validation error.
|
||||
* @param string $attribute attribute name. Use null to check all attributes.
|
||||
* @return boolean whether there is any error.
|
||||
*/
|
||||
public function hasErrors($attribute=null)
|
||||
{
|
||||
if($attribute===null)
|
||||
return $this->_errors!==array();
|
||||
else
|
||||
return isset($this->_errors[$attribute]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the errors for all attribute or a single attribute.
|
||||
* @param string $attribute attribute name. Use null to retrieve errors for all attributes.
|
||||
* @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
|
||||
*/
|
||||
public function getErrors($attribute=null)
|
||||
{
|
||||
if($attribute===null)
|
||||
return $this->_errors;
|
||||
else
|
||||
return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first error of the specified attribute.
|
||||
* @param string $attribute attribute name.
|
||||
* @return string the error message. Null is returned if no error.
|
||||
*/
|
||||
public function getError($attribute)
|
||||
{
|
||||
return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new error to the specified attribute.
|
||||
* @param string $attribute attribute name
|
||||
* @param string $error new error message
|
||||
*/
|
||||
public function addError($attribute,$error)
|
||||
{
|
||||
$this->_errors[$attribute][]=$error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a list of errors.
|
||||
* @param array $errors a list of errors. The array keys must be attribute names.
|
||||
* The array values should be error messages. If an attribute has multiple errors,
|
||||
* these errors must be given in terms of an array.
|
||||
* You may use the result of {@link getErrors} as the value for this parameter.
|
||||
*/
|
||||
public function addErrors($errors)
|
||||
{
|
||||
foreach($errors as $attribute=>$error)
|
||||
{
|
||||
if(is_array($error))
|
||||
{
|
||||
foreach($error as $e)
|
||||
$this->addError($attribute, $e);
|
||||
}
|
||||
else
|
||||
$this->addError($attribute, $error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes errors for all attributes or a single attribute.
|
||||
* @param string $attribute attribute name. Use null to remove errors for all attribute.
|
||||
*/
|
||||
public function clearErrors($attribute=null)
|
||||
{
|
||||
if($attribute===null)
|
||||
$this->_errors=array();
|
||||
else
|
||||
unset($this->_errors[$attribute]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a user friendly attribute label.
|
||||
* This is done by replacing underscores or dashes with blanks and
|
||||
* changing the first letter of each word to upper case.
|
||||
* For example, 'department_name' or 'DepartmentName' becomes 'Department Name'.
|
||||
* @param string $name the column name
|
||||
* @return string the attribute label
|
||||
*/
|
||||
public function generateAttributeLabel($name)
|
||||
{
|
||||
return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all attribute values.
|
||||
* @param array $names list of attributes whose value needs to be returned.
|
||||
* Defaults to null, meaning all attributes as listed in {@link attributeNames} will be returned.
|
||||
* If it is an array, only the attributes in the array will be returned.
|
||||
* @return array attribute values (name=>value).
|
||||
*/
|
||||
public function getAttributes($names=null)
|
||||
{
|
||||
$values=array();
|
||||
foreach($this->attributeNames() as $name)
|
||||
$values[$name]=$this->$name;
|
||||
|
||||
if(is_array($names))
|
||||
{
|
||||
$values2=array();
|
||||
foreach($names as $name)
|
||||
$values2[$name]=isset($values[$name]) ? $values[$name] : null;
|
||||
return $values2;
|
||||
}
|
||||
else
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the attribute values in a massive way.
|
||||
* @param array $values attribute values (name=>value) to be set.
|
||||
* @param boolean $safeOnly whether the assignments should only be done to the safe attributes.
|
||||
* A safe attribute is one that is associated with a validation rule in the current {@link scenario}.
|
||||
* @see getSafeAttributeNames
|
||||
* @see attributeNames
|
||||
*/
|
||||
public function setAttributes($values,$safeOnly=true)
|
||||
{
|
||||
if(!is_array($values))
|
||||
return;
|
||||
$attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
|
||||
foreach($values as $name=>$value)
|
||||
{
|
||||
if(isset($attributes[$name]))
|
||||
$this->$name=$value;
|
||||
elseif($safeOnly)
|
||||
$this->onUnsafeAttribute($name,$value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the attributes to be null.
|
||||
* @param array $names list of attributes to be set null. If this parameter is not given,
|
||||
* all attributes as specified by {@link attributeNames} will have their values unset.
|
||||
* @since 1.1.3
|
||||
*/
|
||||
public function unsetAttributes($names=null)
|
||||
{
|
||||
if($names===null)
|
||||
$names=$this->attributeNames();
|
||||
foreach($names as $name)
|
||||
$this->$name=null;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is invoked when an unsafe attribute is being massively assigned.
|
||||
* The default implementation will log a warning message if YII_DEBUG is on.
|
||||
* It does nothing otherwise.
|
||||
* @param string $name the unsafe attribute name
|
||||
* @param mixed $value the attribute value
|
||||
* @since 1.1.1
|
||||
*/
|
||||
public function onUnsafeAttribute($name,$value)
|
||||
{
|
||||
if(YII_DEBUG)
|
||||
Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the scenario that this model is used in.
|
||||
*
|
||||
* Scenario affects how validation is performed and which attributes can
|
||||
* be massively assigned.
|
||||
*
|
||||
* A validation rule will be performed when calling {@link validate()}
|
||||
* if its 'except' value does not contain current scenario value while
|
||||
* 'on' option is not set or contains the current scenario value.
|
||||
*
|
||||
* And an attribute can be massively assigned if it is associated with
|
||||
* a validation rule for the current scenario. Note that an exception is
|
||||
* the {@link CUnsafeValidator unsafe} validator which marks the associated
|
||||
* attributes as unsafe and not allowed to be massively assigned.
|
||||
*
|
||||
* @return string the scenario that this model is in.
|
||||
*/
|
||||
public function getScenario()
|
||||
{
|
||||
return $this->_scenario;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the scenario for the model.
|
||||
* @param string $value the scenario that this model is in.
|
||||
* @see getScenario
|
||||
*/
|
||||
public function setScenario($value)
|
||||
{
|
||||
$this->_scenario=$value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the attribute names that are safe to be massively assigned.
|
||||
* A safe attribute is one that is associated with a validation rule in the current {@link scenario}.
|
||||
* @return array safe attribute names
|
||||
*/
|
||||
public function getSafeAttributeNames()
|
||||
{
|
||||
$attributes=array();
|
||||
$unsafe=array();
|
||||
foreach($this->getValidators() as $validator)
|
||||
{
|
||||
if(!$validator->safe)
|
||||
{
|
||||
foreach($validator->attributes as $name)
|
||||
$unsafe[]=$name;
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach($validator->attributes as $name)
|
||||
$attributes[$name]=true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach($unsafe as $name)
|
||||
unset($attributes[$name]);
|
||||
return array_keys($attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator for traversing the attributes in the model.
|
||||
* This method is required by the interface IteratorAggregate.
|
||||
* @return CMapIterator an iterator for traversing the items in the list.
|
||||
*/
|
||||
public function getIterator()
|
||||
{
|
||||
$attributes=$this->getAttributes();
|
||||
return new CMapIterator($attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether there is an element at the specified offset.
|
||||
* This method is required by the interface ArrayAccess.
|
||||
* @param mixed $offset the offset to check on
|
||||
* @return boolean
|
||||
*/
|
||||
public function offsetExists($offset)
|
||||
{
|
||||
return property_exists($this,$offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the element at the specified offset.
|
||||
* This method is required by the interface ArrayAccess.
|
||||
* @param integer $offset the offset to retrieve element.
|
||||
* @return mixed the element at the offset, null if no element is found at the offset
|
||||
*/
|
||||
public function offsetGet($offset)
|
||||
{
|
||||
return $this->$offset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the element at the specified offset.
|
||||
* This method is required by the interface ArrayAccess.
|
||||
* @param integer $offset the offset to set element
|
||||
* @param mixed $item the element value
|
||||
*/
|
||||
public function offsetSet($offset,$item)
|
||||
{
|
||||
$this->$offset=$item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsets the element at the specified offset.
|
||||
* This method is required by the interface ArrayAccess.
|
||||
* @param mixed $offset the offset to unset element
|
||||
*/
|
||||
public function offsetUnset($offset)
|
||||
{
|
||||
unset($this->$offset);
|
||||
}
|
||||
}
|
||||
68
framework/base/CModelBehavior.php
Normal file
68
framework/base/CModelBehavior.php
Normal file
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
/**
|
||||
* CModelBehavior class file.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CModelBehavior is a base class for behaviors that are attached to a model component.
|
||||
* The model should extend from {@link CModel} or its child classes.
|
||||
*
|
||||
* @property CModel $owner The owner model that this behavior is attached to.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
*/
|
||||
class CModelBehavior extends CBehavior
|
||||
{
|
||||
/**
|
||||
* Declares events and the corresponding event handler methods.
|
||||
* The default implementation returns 'onAfterConstruct', 'onBeforeValidate' and 'onAfterValidate' events and handlers.
|
||||
* If you override this method, make sure you merge the parent result to the return value.
|
||||
* @return array events (array keys) and the corresponding event handler methods (array values).
|
||||
* @see CBehavior::events
|
||||
*/
|
||||
public function events()
|
||||
{
|
||||
return array(
|
||||
'onAfterConstruct'=>'afterConstruct',
|
||||
'onBeforeValidate'=>'beforeValidate',
|
||||
'onAfterValidate'=>'afterValidate',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Responds to {@link CModel::onAfterConstruct} event.
|
||||
* Override this method and make it public if you want to handle the corresponding event
|
||||
* of the {@link CBehavior::owner owner}.
|
||||
* @param CEvent $event event parameter
|
||||
*/
|
||||
protected function afterConstruct($event)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Responds to {@link CModel::onBeforeValidate} event.
|
||||
* Override this method and make it public if you want to handle the corresponding event
|
||||
* of the {@link owner}.
|
||||
* You may set {@link CModelEvent::isValid} to be false to quit the validation process.
|
||||
* @param CModelEvent $event event parameter
|
||||
*/
|
||||
protected function beforeValidate($event)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Responds to {@link CModel::onAfterValidate} event.
|
||||
* Override this method and make it public if you want to handle the corresponding event
|
||||
* of the {@link owner}.
|
||||
* @param CEvent $event event parameter
|
||||
*/
|
||||
protected function afterValidate($event)
|
||||
{
|
||||
}
|
||||
}
|
||||
31
framework/base/CModelEvent.php
Normal file
31
framework/base/CModelEvent.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
/**
|
||||
* CModelEvent class file.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* CModelEvent class.
|
||||
*
|
||||
* CModelEvent represents the event parameters needed by events raised by a model.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
class CModelEvent extends CEvent
|
||||
{
|
||||
/**
|
||||
* @var boolean whether the model is in valid status and should continue its normal method execution cycles. Defaults to true.
|
||||
* For example, when this event is raised in a {@link CFormModel} object that is executing {@link CModel::beforeValidate},
|
||||
* if this property is set false by the event handler, the {@link CModel::validate} method will quit after handling this event.
|
||||
* If true, the normal execution cycles will continue, including performing the real validations and calling
|
||||
* {@link CModel::afterValidate}.
|
||||
*/
|
||||
public $isValid=true;
|
||||
}
|
||||
547
framework/base/CModule.php
Normal file
547
framework/base/CModule.php
Normal file
@@ -0,0 +1,547 @@
|
||||
<?php
|
||||
/**
|
||||
* CModule class file.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CModule is the base class for module and application classes.
|
||||
*
|
||||
* CModule mainly manages application components and sub-modules.
|
||||
*
|
||||
* @property string $id The module ID.
|
||||
* @property string $basePath The root directory of the module. Defaults to the directory containing the module class.
|
||||
* @property CAttributeCollection $params The list of user-defined parameters.
|
||||
* @property string $modulePath The directory that contains the application modules. Defaults to the 'modules' subdirectory of {@link basePath}.
|
||||
* @property CModule $parentModule The parent module. Null if this module does not have a parent.
|
||||
* @property array $modules The configuration of the currently installed modules (module ID => configuration).
|
||||
* @property array $components The application components (indexed by their IDs).
|
||||
* @property array $import List of aliases to be imported.
|
||||
* @property array $aliases List of aliases to be defined. The array keys are root aliases,
|
||||
* while the array values are paths or aliases corresponding to the root aliases.
|
||||
* For example,
|
||||
* <pre>
|
||||
* array(
|
||||
* 'models'=>'application.models', // an existing alias
|
||||
* 'extensions'=>'application.extensions', // an existing alias
|
||||
* 'backend'=>dirname(__FILE__).'/../backend', // a directory
|
||||
* )
|
||||
* </pre>.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
*/
|
||||
abstract class CModule extends CComponent
|
||||
{
|
||||
/**
|
||||
* @var array the IDs of the application components that should be preloaded.
|
||||
*/
|
||||
public $preload=array();
|
||||
/**
|
||||
* @var array the behaviors that should be attached to the module.
|
||||
* The behaviors will be attached to the module when {@link init} is called.
|
||||
* Please refer to {@link CModel::behaviors} on how to specify the value of this property.
|
||||
*/
|
||||
public $behaviors=array();
|
||||
|
||||
private $_id;
|
||||
private $_parentModule;
|
||||
private $_basePath;
|
||||
private $_modulePath;
|
||||
private $_params;
|
||||
private $_modules=array();
|
||||
private $_moduleConfig=array();
|
||||
private $_components=array();
|
||||
private $_componentConfig=array();
|
||||
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
* @param string $id the ID of this module
|
||||
* @param CModule $parent the parent module (if any)
|
||||
* @param mixed $config the module configuration. It can be either an array or
|
||||
* the path of a PHP file returning the configuration array.
|
||||
*/
|
||||
public function __construct($id,$parent,$config=null)
|
||||
{
|
||||
$this->_id=$id;
|
||||
$this->_parentModule=$parent;
|
||||
|
||||
// set basePath at early as possible to avoid trouble
|
||||
if(is_string($config))
|
||||
$config=require($config);
|
||||
if(isset($config['basePath']))
|
||||
{
|
||||
$this->setBasePath($config['basePath']);
|
||||
unset($config['basePath']);
|
||||
}
|
||||
Yii::setPathOfAlias($id,$this->getBasePath());
|
||||
|
||||
$this->preinit();
|
||||
|
||||
$this->configure($config);
|
||||
$this->attachBehaviors($this->behaviors);
|
||||
$this->preloadComponents();
|
||||
|
||||
$this->init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter magic method.
|
||||
* This method is overridden to support accessing application components
|
||||
* like reading module properties.
|
||||
* @param string $name application component or property name
|
||||
* @return mixed the named property value
|
||||
*/
|
||||
public function __get($name)
|
||||
{
|
||||
if($this->hasComponent($name))
|
||||
return $this->getComponent($name);
|
||||
else
|
||||
return parent::__get($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a property value is null.
|
||||
* This method overrides the parent implementation by checking
|
||||
* if the named application component is loaded.
|
||||
* @param string $name the property name or the event name
|
||||
* @return boolean whether the property value is null
|
||||
*/
|
||||
public function __isset($name)
|
||||
{
|
||||
if($this->hasComponent($name))
|
||||
return $this->getComponent($name)!==null;
|
||||
else
|
||||
return parent::__isset($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the module ID.
|
||||
* @return string the module ID.
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
return $this->_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the module ID.
|
||||
* @param string $id the module ID
|
||||
*/
|
||||
public function setId($id)
|
||||
{
|
||||
$this->_id=$id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the root directory of the module.
|
||||
* @return string the root directory of the module. Defaults to the directory containing the module class.
|
||||
*/
|
||||
public function getBasePath()
|
||||
{
|
||||
if($this->_basePath===null)
|
||||
{
|
||||
$class=new ReflectionClass(get_class($this));
|
||||
$this->_basePath=dirname($class->getFileName());
|
||||
}
|
||||
return $this->_basePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the root directory of the module.
|
||||
* This method can only be invoked at the beginning of the constructor.
|
||||
* @param string $path the root directory of the module.
|
||||
* @throws CException if the directory does not exist.
|
||||
*/
|
||||
public function setBasePath($path)
|
||||
{
|
||||
if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
|
||||
throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
|
||||
array('{path}'=>$path)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns user-defined parameters.
|
||||
* @return CAttributeCollection the list of user-defined parameters
|
||||
*/
|
||||
public function getParams()
|
||||
{
|
||||
if($this->_params!==null)
|
||||
return $this->_params;
|
||||
else
|
||||
{
|
||||
$this->_params=new CAttributeCollection;
|
||||
$this->_params->caseSensitive=true;
|
||||
return $this->_params;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets user-defined parameters.
|
||||
* @param array $value user-defined parameters. This should be in name-value pairs.
|
||||
*/
|
||||
public function setParams($value)
|
||||
{
|
||||
$params=$this->getParams();
|
||||
foreach($value as $k=>$v)
|
||||
$params->add($k,$v);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the directory that contains the application modules.
|
||||
* @return string the directory that contains the application modules. Defaults to the 'modules' subdirectory of {@link basePath}.
|
||||
*/
|
||||
public function getModulePath()
|
||||
{
|
||||
if($this->_modulePath!==null)
|
||||
return $this->_modulePath;
|
||||
else
|
||||
return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the directory that contains the application modules.
|
||||
* @param string $value the directory that contains the application modules.
|
||||
* @throws CException if the directory is invalid
|
||||
*/
|
||||
public function setModulePath($value)
|
||||
{
|
||||
if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
|
||||
throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
|
||||
array('{path}'=>$value)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the aliases that are used in the module.
|
||||
* @param array $aliases list of aliases to be imported
|
||||
*/
|
||||
public function setImport($aliases)
|
||||
{
|
||||
foreach($aliases as $alias)
|
||||
Yii::import($alias);
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines the root aliases.
|
||||
* @param array $mappings list of aliases to be defined. The array keys are root aliases,
|
||||
* while the array values are paths or aliases corresponding to the root aliases.
|
||||
* For example,
|
||||
* <pre>
|
||||
* array(
|
||||
* 'models'=>'application.models', // an existing alias
|
||||
* 'extensions'=>'application.extensions', // an existing alias
|
||||
* 'backend'=>dirname(__FILE__).'/../backend', // a directory
|
||||
* )
|
||||
* </pre>
|
||||
*/
|
||||
public function setAliases($mappings)
|
||||
{
|
||||
foreach($mappings as $name=>$alias)
|
||||
{
|
||||
if(($path=Yii::getPathOfAlias($alias))!==false)
|
||||
Yii::setPathOfAlias($name,$path);
|
||||
else
|
||||
Yii::setPathOfAlias($name,$alias);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the parent module.
|
||||
* @return CModule the parent module. Null if this module does not have a parent.
|
||||
*/
|
||||
public function getParentModule()
|
||||
{
|
||||
return $this->_parentModule;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the named application module.
|
||||
* The module has to be declared in {@link modules}. A new instance will be created
|
||||
* when calling this method with the given ID for the first time.
|
||||
* @param string $id application module ID (case-sensitive)
|
||||
* @return CModule the module instance, null if the module is disabled or does not exist.
|
||||
*/
|
||||
public function getModule($id)
|
||||
{
|
||||
if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
|
||||
return $this->_modules[$id];
|
||||
elseif(isset($this->_moduleConfig[$id]))
|
||||
{
|
||||
$config=$this->_moduleConfig[$id];
|
||||
if(!isset($config['enabled']) || $config['enabled'])
|
||||
{
|
||||
Yii::trace("Loading \"$id\" module",'system.base.CModule');
|
||||
$class=$config['class'];
|
||||
unset($config['class'], $config['enabled']);
|
||||
if($this===Yii::app())
|
||||
$module=Yii::createComponent($class,$id,null,$config);
|
||||
else
|
||||
$module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
|
||||
return $this->_modules[$id]=$module;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a value indicating whether the specified module is installed.
|
||||
* @param string $id the module ID
|
||||
* @return boolean whether the specified module is installed.
|
||||
* @since 1.1.2
|
||||
*/
|
||||
public function hasModule($id)
|
||||
{
|
||||
return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the configuration of the currently installed modules.
|
||||
* @return array the configuration of the currently installed modules (module ID => configuration)
|
||||
*/
|
||||
public function getModules()
|
||||
{
|
||||
return $this->_moduleConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the sub-modules of this module.
|
||||
*
|
||||
* Call this method to declare sub-modules and configure them with their initial property values.
|
||||
* The parameter should be an array of module configurations. Each array element represents a single module,
|
||||
* which can be either a string representing the module ID or an ID-configuration pair representing
|
||||
* a module with the specified ID and the initial property values.
|
||||
*
|
||||
* For example, the following array declares two modules:
|
||||
* <pre>
|
||||
* array(
|
||||
* 'admin', // a single module ID
|
||||
* 'payment'=>array( // ID-configuration pair
|
||||
* 'server'=>'paymentserver.com',
|
||||
* ),
|
||||
* )
|
||||
* </pre>
|
||||
*
|
||||
* By default, the module class is determined using the expression <code>ucfirst($moduleID).'Module'</code>.
|
||||
* And the class file is located under <code>modules/$moduleID</code>.
|
||||
* You may override this default by explicitly specifying the 'class' option in the configuration.
|
||||
*
|
||||
* You may also enable or disable a module by specifying the 'enabled' option in the configuration.
|
||||
*
|
||||
* @param array $modules module configurations.
|
||||
*/
|
||||
public function setModules($modules)
|
||||
{
|
||||
foreach($modules as $id=>$module)
|
||||
{
|
||||
if(is_int($id))
|
||||
{
|
||||
$id=$module;
|
||||
$module=array();
|
||||
}
|
||||
if(!isset($module['class']))
|
||||
{
|
||||
Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
|
||||
$module['class']=$id.'.'.ucfirst($id).'Module';
|
||||
}
|
||||
|
||||
if(isset($this->_moduleConfig[$id]))
|
||||
$this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
|
||||
else
|
||||
$this->_moduleConfig[$id]=$module;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the named component exists.
|
||||
* @param string $id application component ID
|
||||
* @return boolean whether the named application component exists (including both loaded and disabled.)
|
||||
*/
|
||||
public function hasComponent($id)
|
||||
{
|
||||
return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the named application component.
|
||||
* @param string $id application component ID (case-sensitive)
|
||||
* @param boolean $createIfNull whether to create the component if it doesn't exist yet.
|
||||
* @return IApplicationComponent the application component instance, null if the application component is disabled or does not exist.
|
||||
* @see hasComponent
|
||||
*/
|
||||
public function getComponent($id,$createIfNull=true)
|
||||
{
|
||||
if(isset($this->_components[$id]))
|
||||
return $this->_components[$id];
|
||||
elseif(isset($this->_componentConfig[$id]) && $createIfNull)
|
||||
{
|
||||
$config=$this->_componentConfig[$id];
|
||||
if(!isset($config['enabled']) || $config['enabled'])
|
||||
{
|
||||
Yii::trace("Loading \"$id\" application component",'system.CModule');
|
||||
unset($config['enabled']);
|
||||
$component=Yii::createComponent($config);
|
||||
$component->init();
|
||||
return $this->_components[$id]=$component;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a component under the management of the module.
|
||||
* The component will be initialized by calling its {@link CApplicationComponent::init() init()}
|
||||
* method if it has not done so.
|
||||
* @param string $id component ID
|
||||
* @param array|IApplicationComponent $component application component
|
||||
* (either configuration array or instance). If this parameter is null,
|
||||
* component will be unloaded from the module.
|
||||
* @param boolean $merge whether to merge the new component configuration
|
||||
* with the existing one. Defaults to true, meaning the previously registered
|
||||
* component configuration with the same ID will be merged with the new configuration.
|
||||
* If set to false, the existing configuration will be replaced completely.
|
||||
* This parameter is available since 1.1.13.
|
||||
*/
|
||||
public function setComponent($id,$component,$merge=true)
|
||||
{
|
||||
if($component===null)
|
||||
{
|
||||
unset($this->_components[$id]);
|
||||
return;
|
||||
}
|
||||
elseif($component instanceof IApplicationComponent)
|
||||
{
|
||||
$this->_components[$id]=$component;
|
||||
|
||||
if(!$component->getIsInitialized())
|
||||
$component->init();
|
||||
|
||||
return;
|
||||
}
|
||||
elseif(isset($this->_components[$id]))
|
||||
{
|
||||
if(isset($component['class']) && get_class($this->_components[$id])!==$component['class'])
|
||||
{
|
||||
unset($this->_components[$id]);
|
||||
$this->_componentConfig[$id]=$component; //we should ignore merge here
|
||||
return;
|
||||
}
|
||||
|
||||
foreach($component as $key=>$value)
|
||||
{
|
||||
if($key!=='class')
|
||||
$this->_components[$id]->$key=$value;
|
||||
}
|
||||
}
|
||||
elseif(isset($this->_componentConfig[$id]['class'],$component['class'])
|
||||
&& $this->_componentConfig[$id]['class']!==$component['class'])
|
||||
{
|
||||
$this->_componentConfig[$id]=$component; //we should ignore merge here
|
||||
return;
|
||||
}
|
||||
|
||||
if(isset($this->_componentConfig[$id]) && $merge)
|
||||
$this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
|
||||
else
|
||||
$this->_componentConfig[$id]=$component;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the application components.
|
||||
* @param boolean $loadedOnly whether to return the loaded components only. If this is set false,
|
||||
* then all components specified in the configuration will be returned, whether they are loaded or not.
|
||||
* Loaded components will be returned as objects, while unloaded components as configuration arrays.
|
||||
* This parameter has been available since version 1.1.3.
|
||||
* @return array the application components (indexed by their IDs)
|
||||
*/
|
||||
public function getComponents($loadedOnly=true)
|
||||
{
|
||||
if($loadedOnly)
|
||||
return $this->_components;
|
||||
else
|
||||
return array_merge($this->_componentConfig, $this->_components);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the application components.
|
||||
*
|
||||
* When a configuration is used to specify a component, it should consist of
|
||||
* the component's initial property values (name-value pairs). Additionally,
|
||||
* a component can be enabled (default) or disabled by specifying the 'enabled' value
|
||||
* in the configuration.
|
||||
*
|
||||
* If a configuration is specified with an ID that is the same as an existing
|
||||
* component or configuration, the existing one will be replaced silently.
|
||||
*
|
||||
* The following is the configuration for two components:
|
||||
* <pre>
|
||||
* array(
|
||||
* 'db'=>array(
|
||||
* 'class'=>'CDbConnection',
|
||||
* 'connectionString'=>'sqlite:path/to/file.db',
|
||||
* ),
|
||||
* 'cache'=>array(
|
||||
* 'class'=>'CDbCache',
|
||||
* 'connectionID'=>'db',
|
||||
* 'enabled'=>!YII_DEBUG, // enable caching in non-debug mode
|
||||
* ),
|
||||
* )
|
||||
* </pre>
|
||||
*
|
||||
* @param array $components application components(id=>component configuration or instances)
|
||||
* @param boolean $merge whether to merge the new component configuration with the existing one.
|
||||
* Defaults to true, meaning the previously registered component configuration of the same ID
|
||||
* will be merged with the new configuration. If false, the existing configuration will be replaced completely.
|
||||
*/
|
||||
public function setComponents($components,$merge=true)
|
||||
{
|
||||
foreach($components as $id=>$component)
|
||||
$this->setComponent($id,$component,$merge);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the module with the specified configuration.
|
||||
* @param array $config the configuration array
|
||||
*/
|
||||
public function configure($config)
|
||||
{
|
||||
if(is_array($config))
|
||||
{
|
||||
foreach($config as $key=>$value)
|
||||
$this->$key=$value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads static application components.
|
||||
*/
|
||||
protected function preloadComponents()
|
||||
{
|
||||
foreach($this->preload as $id)
|
||||
$this->getComponent($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Preinitializes the module.
|
||||
* This method is called at the beginning of the module constructor.
|
||||
* You may override this method to do some customized preinitialization work.
|
||||
* Note that at this moment, the module is not configured yet.
|
||||
* @see init
|
||||
*/
|
||||
protected function preinit()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the module.
|
||||
* This method is called at the end of the module constructor.
|
||||
* Note that at this moment, the module has been configured, the behaviors
|
||||
* have been attached and the application components have been registered.
|
||||
* @see preinit
|
||||
*/
|
||||
protected function init()
|
||||
{
|
||||
}
|
||||
}
|
||||
492
framework/base/CSecurityManager.php
Normal file
492
framework/base/CSecurityManager.php
Normal file
@@ -0,0 +1,492 @@
|
||||
<?php
|
||||
/**
|
||||
* This file contains classes implementing security manager feature.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CSecurityManager provides private keys, hashing and encryption functions.
|
||||
*
|
||||
* CSecurityManager is used by Yii components and applications for security-related purpose.
|
||||
* For example, it is used in cookie validation feature to prevent cookie data
|
||||
* from being tampered.
|
||||
*
|
||||
* CSecurityManager is mainly used to protect data from being tampered and viewed.
|
||||
* It can generate HMAC and encrypt the data. The private key used to generate HMAC
|
||||
* is set by {@link setValidationKey ValidationKey}. The key used to encrypt data is
|
||||
* specified by {@link setEncryptionKey EncryptionKey}. If the above keys are not
|
||||
* explicitly set, random keys will be generated and used.
|
||||
*
|
||||
* To protected data with HMAC, call {@link hashData()}; and to check if the data
|
||||
* is tampered, call {@link validateData()}, which will return the real data if
|
||||
* it is not tampered. The algorithm used to generated HMAC is specified by
|
||||
* {@link validation}.
|
||||
*
|
||||
* To encrypt and decrypt data, call {@link encrypt()} and {@link decrypt()}
|
||||
* respectively, which uses 3DES encryption algorithm. Note, the PHP Mcrypt
|
||||
* extension must be installed and loaded.
|
||||
*
|
||||
* CSecurityManager is a core application component that can be accessed via
|
||||
* {@link CApplication::getSecurityManager()}.
|
||||
*
|
||||
* @property string $validationKey The private key used to generate HMAC.
|
||||
* If the key is not explicitly set, a random one is generated and returned.
|
||||
* @property string $encryptionKey The private key used to encrypt/decrypt data.
|
||||
* If the key is not explicitly set, a random one is generated and returned.
|
||||
* @property string $validation
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
class CSecurityManager extends CApplicationComponent
|
||||
{
|
||||
const STATE_VALIDATION_KEY='Yii.CSecurityManager.validationkey';
|
||||
const STATE_ENCRYPTION_KEY='Yii.CSecurityManager.encryptionkey';
|
||||
|
||||
/**
|
||||
* @var string the name of the hashing algorithm to be used by {@link computeHMAC}.
|
||||
* See {@link http://php.net/manual/en/function.hash-algos.php hash-algos} for the list of possible
|
||||
* hash algorithms. Note that if you are using PHP 5.1.1 or below, you can only use 'sha1' or 'md5'.
|
||||
*
|
||||
* Defaults to 'sha1', meaning using SHA1 hash algorithm.
|
||||
* @since 1.1.3
|
||||
*/
|
||||
public $hashAlgorithm='sha1';
|
||||
/**
|
||||
* @var mixed the name of the crypt algorithm to be used by {@link encrypt} and {@link decrypt}.
|
||||
* This will be passed as the first parameter to {@link http://php.net/manual/en/function.mcrypt-module-open.php mcrypt_module_open}.
|
||||
*
|
||||
* This property can also be configured as an array. In this case, the array elements will be passed in order
|
||||
* as parameters to mcrypt_module_open. For example, <code>array('rijndael-256', '', 'ofb', '')</code>.
|
||||
*
|
||||
* Defaults to 'des', meaning using DES crypt algorithm.
|
||||
* @since 1.1.3
|
||||
*/
|
||||
public $cryptAlgorithm='des';
|
||||
|
||||
private $_validationKey;
|
||||
private $_encryptionKey;
|
||||
private $_mbstring;
|
||||
|
||||
public function init()
|
||||
{
|
||||
parent::init();
|
||||
$this->_mbstring=extension_loaded('mbstring');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string a randomly generated private key.
|
||||
* @deprecated in favor of {@link generateRandomString()} since 1.1.14. Never use this method.
|
||||
*/
|
||||
protected function generateRandomKey()
|
||||
{
|
||||
return $this->generateRandomString(32);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string the private key used to generate HMAC.
|
||||
* If the key is not explicitly set, a random one is generated and returned.
|
||||
* @throws CException in case random string cannot be generated.
|
||||
*/
|
||||
public function getValidationKey()
|
||||
{
|
||||
if($this->_validationKey!==null)
|
||||
return $this->_validationKey;
|
||||
else
|
||||
{
|
||||
if(($key=Yii::app()->getGlobalState(self::STATE_VALIDATION_KEY))!==null)
|
||||
$this->setValidationKey($key);
|
||||
else
|
||||
{
|
||||
if(($key=$this->generateRandomString(32,true))===false)
|
||||
if(($key=$this->generateRandomString(32,false))===false)
|
||||
throw new CException(Yii::t('yii',
|
||||
'CSecurityManager::generateRandomString() cannot generate random string in the current environment.'));
|
||||
$this->setValidationKey($key);
|
||||
Yii::app()->setGlobalState(self::STATE_VALIDATION_KEY,$key);
|
||||
}
|
||||
return $this->_validationKey;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $value the key used to generate HMAC
|
||||
* @throws CException if the key is empty
|
||||
*/
|
||||
public function setValidationKey($value)
|
||||
{
|
||||
if(!empty($value))
|
||||
$this->_validationKey=$value;
|
||||
else
|
||||
throw new CException(Yii::t('yii','CSecurityManager.validationKey cannot be empty.'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string the private key used to encrypt/decrypt data.
|
||||
* If the key is not explicitly set, a random one is generated and returned.
|
||||
* @throws CException in case random string cannot be generated.
|
||||
*/
|
||||
public function getEncryptionKey()
|
||||
{
|
||||
if($this->_encryptionKey!==null)
|
||||
return $this->_encryptionKey;
|
||||
else
|
||||
{
|
||||
if(($key=Yii::app()->getGlobalState(self::STATE_ENCRYPTION_KEY))!==null)
|
||||
$this->setEncryptionKey($key);
|
||||
else
|
||||
{
|
||||
if(($key=$this->generateRandomString(32,true))===false)
|
||||
if(($key=$this->generateRandomString(32,false))===false)
|
||||
throw new CException(Yii::t('yii',
|
||||
'CSecurityManager::generateRandomString() cannot generate random string in the current environment.'));
|
||||
$this->setEncryptionKey($key);
|
||||
Yii::app()->setGlobalState(self::STATE_ENCRYPTION_KEY,$key);
|
||||
}
|
||||
return $this->_encryptionKey;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $value the key used to encrypt/decrypt data.
|
||||
* @throws CException if the key is empty
|
||||
*/
|
||||
public function setEncryptionKey($value)
|
||||
{
|
||||
if(!empty($value))
|
||||
$this->_encryptionKey=$value;
|
||||
else
|
||||
throw new CException(Yii::t('yii','CSecurityManager.encryptionKey cannot be empty.'));
|
||||
}
|
||||
|
||||
/**
|
||||
* This method has been deprecated since version 1.1.3.
|
||||
* Please use {@link hashAlgorithm} instead.
|
||||
* @return string -
|
||||
* @deprecated
|
||||
*/
|
||||
public function getValidation()
|
||||
{
|
||||
return $this->hashAlgorithm;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method has been deprecated since version 1.1.3.
|
||||
* Please use {@link hashAlgorithm} instead.
|
||||
* @param string $value -
|
||||
* @deprecated
|
||||
*/
|
||||
public function setValidation($value)
|
||||
{
|
||||
$this->hashAlgorithm=$value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypts data.
|
||||
* @param string $data data to be encrypted.
|
||||
* @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
|
||||
* @return string the encrypted data
|
||||
* @throws CException if PHP Mcrypt extension is not loaded
|
||||
*/
|
||||
public function encrypt($data,$key=null)
|
||||
{
|
||||
$module=$this->openCryptModule();
|
||||
$key=$this->substr($key===null ? md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
|
||||
srand();
|
||||
$iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
|
||||
mcrypt_generic_init($module,$key,$iv);
|
||||
$encrypted=$iv.mcrypt_generic($module,$data);
|
||||
mcrypt_generic_deinit($module);
|
||||
mcrypt_module_close($module);
|
||||
return $encrypted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypts data
|
||||
* @param string $data data to be decrypted.
|
||||
* @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
|
||||
* @return string the decrypted data
|
||||
* @throws CException if PHP Mcrypt extension is not loaded
|
||||
*/
|
||||
public function decrypt($data,$key=null)
|
||||
{
|
||||
$module=$this->openCryptModule();
|
||||
$key=$this->substr($key===null ? md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
|
||||
$ivSize=mcrypt_enc_get_iv_size($module);
|
||||
$iv=$this->substr($data,0,$ivSize);
|
||||
mcrypt_generic_init($module,$key,$iv);
|
||||
$decrypted=mdecrypt_generic($module,$this->substr($data,$ivSize,$this->strlen($data)));
|
||||
mcrypt_generic_deinit($module);
|
||||
mcrypt_module_close($module);
|
||||
return rtrim($decrypted,"\0");
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the mcrypt module with the configuration specified in {@link cryptAlgorithm}.
|
||||
* @throws CException if failed to initialize the mcrypt module or PHP mcrypt extension
|
||||
* @return resource the mycrypt module handle.
|
||||
* @since 1.1.3
|
||||
*/
|
||||
protected function openCryptModule()
|
||||
{
|
||||
if(extension_loaded('mcrypt'))
|
||||
{
|
||||
if(is_array($this->cryptAlgorithm))
|
||||
$module=@call_user_func_array('mcrypt_module_open',$this->cryptAlgorithm);
|
||||
else
|
||||
$module=@mcrypt_module_open($this->cryptAlgorithm,'', MCRYPT_MODE_CBC,'');
|
||||
|
||||
if($module===false)
|
||||
throw new CException(Yii::t('yii','Failed to initialize the mcrypt module.'));
|
||||
|
||||
return $module;
|
||||
}
|
||||
else
|
||||
throw new CException(Yii::t('yii','CSecurityManager requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefixes data with an HMAC.
|
||||
* @param string $data data to be hashed.
|
||||
* @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
|
||||
* @return string data prefixed with HMAC
|
||||
*/
|
||||
public function hashData($data,$key=null)
|
||||
{
|
||||
return $this->computeHMAC($data,$key).$data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates if data is tampered.
|
||||
* @param string $data data to be validated. The data must be previously
|
||||
* generated using {@link hashData()}.
|
||||
* @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
|
||||
* @return string the real data with HMAC stripped off. False if the data
|
||||
* is tampered.
|
||||
*/
|
||||
public function validateData($data,$key=null)
|
||||
{
|
||||
$len=$this->strlen($this->computeHMAC('test'));
|
||||
if($this->strlen($data)>=$len)
|
||||
{
|
||||
$hmac=$this->substr($data,0,$len);
|
||||
$data2=$this->substr($data,$len,$this->strlen($data));
|
||||
return $hmac===$this->computeHMAC($data2,$key)?$data2:false;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the HMAC for the data with {@link getValidationKey validationKey}. This method has been made public
|
||||
* since 1.1.14.
|
||||
* @param string $data data to be generated HMAC.
|
||||
* @param string|null $key the private key to be used for generating HMAC. Defaults to null, meaning using
|
||||
* {@link validationKey} value.
|
||||
* @param string|null $hashAlgorithm the name of the hashing algorithm to be used.
|
||||
* See {@link http://php.net/manual/en/function.hash-algos.php hash-algos} for the list of possible
|
||||
* hash algorithms. Note that if you are using PHP 5.1.1 or below, you can only use 'sha1' or 'md5'.
|
||||
* Defaults to null, meaning using {@link hashAlgorithm} value.
|
||||
* @return string the HMAC for the data.
|
||||
* @throws CException on unsupported hash algorithm given.
|
||||
*/
|
||||
public function computeHMAC($data,$key=null,$hashAlgorithm=null)
|
||||
{
|
||||
if($key===null)
|
||||
$key=$this->getValidationKey();
|
||||
if($hashAlgorithm===null)
|
||||
$hashAlgorithm=$this->hashAlgorithm;
|
||||
|
||||
if(function_exists('hash_hmac'))
|
||||
return hash_hmac($hashAlgorithm,$data,$key);
|
||||
|
||||
if(0===strcasecmp($hashAlgorithm,'sha1'))
|
||||
{
|
||||
$pack='H40';
|
||||
$func='sha1';
|
||||
}
|
||||
elseif(0===strcasecmp($hashAlgorithm,'md5'))
|
||||
{
|
||||
$pack='H32';
|
||||
$func='md5';
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CException(Yii::t('yii','Only SHA1 and MD5 hashing algorithms are supported when using PHP 5.1.1 or below.'));
|
||||
}
|
||||
if($this->strlen($key)>64)
|
||||
$key=pack($pack,$func($key));
|
||||
if($this->strlen($key)<64)
|
||||
$key=str_pad($key,64,chr(0));
|
||||
$key=$this->substr($key,0,64);
|
||||
return $func((str_repeat(chr(0x5C), 64) ^ $key) . pack($pack, $func((str_repeat(chr(0x36), 64) ^ $key) . $data)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a random ASCII string. Generates only [0-9a-zA-z_~] characters which are all
|
||||
* transparent in raw URL encoding.
|
||||
* @param integer $length length of the generated string in characters.
|
||||
* @param boolean $cryptographicallyStrong set this to require cryptographically strong randomness.
|
||||
* @return string|boolean random string or false in case it cannot be generated.
|
||||
* @since 1.1.14
|
||||
*/
|
||||
public function generateRandomString($length,$cryptographicallyStrong=true)
|
||||
{
|
||||
if(($randomBytes=$this->generateRandomBytes($length+2,$cryptographicallyStrong))!==false)
|
||||
return strtr($this->substr(base64_encode($randomBytes),0,$length),array('+'=>'_','/'=>'~'));
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a string of random bytes.
|
||||
* @param integer $length number of random bytes to be generated.
|
||||
* @param boolean $cryptographicallyStrong whether to fail if a cryptographically strong
|
||||
* result cannot be generated. The method attempts to read from a cryptographically strong
|
||||
* pseudorandom number generator (CS-PRNG), see
|
||||
* {@link https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Requirements Wikipedia}.
|
||||
* However, in some runtime environments, PHP has no access to a CS-PRNG, in which case
|
||||
* the method returns false if $cryptographicallyStrong is true. When $cryptographicallyStrong is false,
|
||||
* the method always returns a pseudorandom result but may fall back to using {@link generatePseudoRandomBlock}.
|
||||
* This method does not guarantee that entropy, from sources external to the CS-PRNG, was mixed into
|
||||
* the CS-PRNG state between each successive call. The caller can therefore expect non-blocking
|
||||
* behavior, unlike, for example, reading from /dev/random on Linux, see
|
||||
* {@link http://eprint.iacr.org/2006/086.pdf Gutterman et al 2006}.
|
||||
* @return boolean|string generated random binary string or false on failure.
|
||||
* @since 1.1.14
|
||||
*/
|
||||
public function generateRandomBytes($length,$cryptographicallyStrong=true)
|
||||
{
|
||||
$bytes='';
|
||||
if(function_exists('openssl_random_pseudo_bytes'))
|
||||
{
|
||||
$bytes=openssl_random_pseudo_bytes($length,$strong);
|
||||
if($this->strlen($bytes)>=$length && ($strong || !$cryptographicallyStrong))
|
||||
return $this->substr($bytes,0,$length);
|
||||
}
|
||||
|
||||
if(function_exists('mcrypt_create_iv') &&
|
||||
($bytes=mcrypt_create_iv($length, MCRYPT_DEV_URANDOM))!==false &&
|
||||
$this->strlen($bytes)>=$length)
|
||||
{
|
||||
return $this->substr($bytes,0,$length);
|
||||
}
|
||||
|
||||
if(($file=@fopen('/dev/urandom','rb'))!==false &&
|
||||
($bytes=@fread($file,$length))!==false &&
|
||||
(fclose($file) || true) &&
|
||||
$this->strlen($bytes)>=$length)
|
||||
{
|
||||
return $this->substr($bytes,0,$length);
|
||||
}
|
||||
|
||||
$i=0;
|
||||
while($this->strlen($bytes)<$length &&
|
||||
($byte=$this->generateSessionRandomBlock())!==false &&
|
||||
++$i<3)
|
||||
{
|
||||
$bytes.=$byte;
|
||||
}
|
||||
if($this->strlen($bytes)>=$length)
|
||||
return $this->substr($bytes,0,$length);
|
||||
|
||||
if ($cryptographicallyStrong)
|
||||
return false;
|
||||
|
||||
while($this->strlen($bytes)<$length)
|
||||
$bytes.=$this->generatePseudoRandomBlock();
|
||||
return $this->substr($bytes,0,$length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a pseudo random block of data using several sources. On some systems this may be a bit
|
||||
* better than PHP's {@link mt_rand} built-in function, which is not really random.
|
||||
* @return string of 64 pseudo random bytes.
|
||||
* @since 1.1.14
|
||||
*/
|
||||
public function generatePseudoRandomBlock()
|
||||
{
|
||||
$bytes='';
|
||||
|
||||
if (function_exists('openssl_random_pseudo_bytes')
|
||||
&& ($bytes=openssl_random_pseudo_bytes(512))!==false
|
||||
&& $this->strlen($bytes)>=512)
|
||||
{
|
||||
return $this->substr($bytes,0,512);
|
||||
}
|
||||
|
||||
for($i=0;$i<32;++$i)
|
||||
$bytes.=pack('S',mt_rand(0,0xffff));
|
||||
|
||||
// On UNIX and UNIX-like operating systems the numerical values in `ps`, `uptime` and `iostat`
|
||||
// ought to be fairly unpredictable. Gather the non-zero digits from those.
|
||||
foreach(array('ps','uptime','iostat') as $command) {
|
||||
@exec($command,$commandResult,$retVal);
|
||||
if(is_array($commandResult) && !empty($commandResult) && $retVal==0)
|
||||
$bytes.=preg_replace('/[^1-9]/','',implode('',$commandResult));
|
||||
}
|
||||
|
||||
// Gather the current time's microsecond part. Note: this is only a source of entropy on
|
||||
// the first call! If multiple calls are made, the entropy is only as much as the
|
||||
// randomness in the time between calls.
|
||||
$bytes.=$this->substr(microtime(),2,6);
|
||||
|
||||
// Concatenate everything gathered, mix it with sha512. hash() is part of PHP core and
|
||||
// enabled by default but it can be disabled at compile time but we ignore that possibility here.
|
||||
return hash('sha512',$bytes,true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get random bytes from the system entropy source via PHP session manager.
|
||||
* @return boolean|string 20-byte random binary string or false on error.
|
||||
* @since 1.1.14
|
||||
*/
|
||||
public function generateSessionRandomBlock()
|
||||
{
|
||||
ini_set('session.entropy_length',20);
|
||||
if(ini_get('session.entropy_length')!=20)
|
||||
return false;
|
||||
|
||||
// These calls are (supposed to be, according to PHP manual) safe even if
|
||||
// there is already an active session for the calling script.
|
||||
@session_start();
|
||||
@session_regenerate_id();
|
||||
|
||||
$bytes=session_id();
|
||||
if(!$bytes)
|
||||
return false;
|
||||
|
||||
// $bytes has 20 bytes of entropy but the session manager converts the binary
|
||||
// random bytes into something readable. We have to convert that back.
|
||||
// SHA-1 should do it without losing entropy.
|
||||
return sha1($bytes,true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of the given string.
|
||||
* If available uses the multibyte string function mb_strlen.
|
||||
* @param string $string the string being measured for length
|
||||
* @return integer the length of the string
|
||||
*/
|
||||
private function strlen($string)
|
||||
{
|
||||
return $this->_mbstring ? mb_strlen($string,'8bit') : strlen($string);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the portion of string specified by the start and length parameters.
|
||||
* If available uses the multibyte string function mb_substr
|
||||
* @param string $string the input string. Must be one character or longer.
|
||||
* @param integer $start the starting position
|
||||
* @param integer $length the desired portion length
|
||||
* @return string the extracted part of string, or FALSE on failure or an empty string.
|
||||
*/
|
||||
private function substr($string,$start,$length)
|
||||
{
|
||||
return $this->_mbstring ? mb_substr($string,$start,$length,'8bit') : substr($string,$start,$length);
|
||||
}
|
||||
}
|
||||
107
framework/base/CStatePersister.php
Normal file
107
framework/base/CStatePersister.php
Normal file
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
/**
|
||||
* This file contains classes implementing security manager feature.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* CStatePersister implements a file-based persistent data storage.
|
||||
*
|
||||
* It can be used to keep data available through multiple requests and sessions.
|
||||
*
|
||||
* By default, CStatePersister stores data in a file named 'state.bin' that is located
|
||||
* under the application {@link CApplication::getRuntimePath runtime path}.
|
||||
* You may change the location by setting the {@link stateFile} property.
|
||||
*
|
||||
* To retrieve the data from CStatePersister, call {@link load()}. To save the data,
|
||||
* call {@link save()}.
|
||||
*
|
||||
* Comparison among state persister, session and cache is as follows:
|
||||
* <ul>
|
||||
* <li>session: data persisting within a single user session.</li>
|
||||
* <li>state persister: data persisting through all requests/sessions (e.g. hit counter).</li>
|
||||
* <li>cache: volatile and fast storage. It may be used as storage medium for session or state persister.</li>
|
||||
* </ul>
|
||||
*
|
||||
* Since server resource is often limited, be cautious if you plan to use CStatePersister
|
||||
* to store large amount of data. You should also consider using database-based persister
|
||||
* to improve the throughput.
|
||||
*
|
||||
* CStatePersister is a core application component used to store global application state.
|
||||
* It may be accessed via {@link CApplication::getStatePersister()}.
|
||||
* page state persistent method based on cache.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
class CStatePersister extends CApplicationComponent implements IStatePersister
|
||||
{
|
||||
/**
|
||||
* @var string the file path storing the state data. Make sure the directory containing
|
||||
* the file exists and is writable by the Web server process. If using relative path, also
|
||||
* make sure the path is correct.
|
||||
*/
|
||||
public $stateFile;
|
||||
/**
|
||||
* @var string the ID of the cache application component that is used to cache the state values.
|
||||
* Defaults to 'cache' which refers to the primary cache application component.
|
||||
* Set this property to false if you want to disable caching state values.
|
||||
*/
|
||||
public $cacheID='cache';
|
||||
|
||||
/**
|
||||
* Initializes the component.
|
||||
* This method overrides the parent implementation by making sure {@link stateFile}
|
||||
* contains valid value.
|
||||
*/
|
||||
public function init()
|
||||
{
|
||||
parent::init();
|
||||
if($this->stateFile===null)
|
||||
$this->stateFile=Yii::app()->getRuntimePath().DIRECTORY_SEPARATOR.'state.bin';
|
||||
$dir=dirname($this->stateFile);
|
||||
if(!is_dir($dir) || !is_writable($dir))
|
||||
throw new CException(Yii::t('yii','Unable to create application state file "{file}". Make sure the directory containing the file exists and is writable by the Web server process.',
|
||||
array('{file}'=>$this->stateFile)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads state data from persistent storage.
|
||||
* @return mixed state data. Null if no state data available.
|
||||
*/
|
||||
public function load()
|
||||
{
|
||||
$stateFile=$this->stateFile;
|
||||
if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
|
||||
{
|
||||
$cacheKey='Yii.CStatePersister.'.$stateFile;
|
||||
if(($value=$cache->get($cacheKey))!==false)
|
||||
return unserialize($value);
|
||||
elseif(($content=@file_get_contents($stateFile))!==false)
|
||||
{
|
||||
$cache->set($cacheKey,$content,0,new CFileCacheDependency($stateFile));
|
||||
return unserialize($content);
|
||||
}
|
||||
else
|
||||
return null;
|
||||
}
|
||||
elseif(($content=@file_get_contents($stateFile))!==false)
|
||||
return unserialize($content);
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves application state in persistent storage.
|
||||
* @param mixed $state state data (must be serializable).
|
||||
*/
|
||||
public function save($state)
|
||||
{
|
||||
file_put_contents($this->stateFile,serialize($state),LOCK_EX);
|
||||
}
|
||||
}
|
||||
631
framework/base/interfaces.php
Normal file
631
framework/base/interfaces.php
Normal file
@@ -0,0 +1,631 @@
|
||||
<?php
|
||||
/**
|
||||
* This file contains core interfaces for Yii framework.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright 2008-2013 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
/**
|
||||
* IApplicationComponent is the interface that all application components must implement.
|
||||
*
|
||||
* After the application completes configuration, it will invoke the {@link init()}
|
||||
* method of every loaded application component.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
interface IApplicationComponent
|
||||
{
|
||||
/**
|
||||
* Initializes the application component.
|
||||
* This method is invoked after the application completes configuration.
|
||||
*/
|
||||
public function init();
|
||||
/**
|
||||
* @return boolean whether the {@link init()} method has been invoked.
|
||||
*/
|
||||
public function getIsInitialized();
|
||||
}
|
||||
|
||||
/**
|
||||
* ICache is the interface that must be implemented by cache components.
|
||||
*
|
||||
* This interface must be implemented by classes supporting caching feature.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.caching
|
||||
* @since 1.0
|
||||
*/
|
||||
interface ICache
|
||||
{
|
||||
/**
|
||||
* Retrieves a value from cache with a specified key.
|
||||
* @param string $id a key identifying the cached value
|
||||
* @return mixed the value stored in cache, false if the value is not in the cache or expired.
|
||||
*/
|
||||
public function get($id);
|
||||
/**
|
||||
* Retrieves multiple values from cache with the specified keys.
|
||||
* Some caches (such as memcache, apc) allow retrieving multiple cached values at one time,
|
||||
* which may improve the performance since it reduces the communication cost.
|
||||
* In case a cache doesn't support this feature natively, it will be simulated by this method.
|
||||
* @param array $ids list of keys identifying the cached values
|
||||
* @return array list of cached values corresponding to the specified keys. The array
|
||||
* is returned in terms of (key,value) pairs.
|
||||
* If a value is not cached or expired, the corresponding array value will be false.
|
||||
*/
|
||||
public function mget($ids);
|
||||
/**
|
||||
* Stores a value identified by a key into cache.
|
||||
* If the cache already contains such a key, the existing value and
|
||||
* expiration time will be replaced with the new ones.
|
||||
*
|
||||
* @param string $id the key identifying the value to be cached
|
||||
* @param mixed $value the value to be cached
|
||||
* @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
|
||||
* @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labelled invalid.
|
||||
* @return boolean true if the value is successfully stored into cache, false otherwise
|
||||
*/
|
||||
public function set($id,$value,$expire=0,$dependency=null);
|
||||
/**
|
||||
* Stores a value identified by a key into cache if the cache does not contain this key.
|
||||
* Nothing will be done if the cache already contains the key.
|
||||
* @param string $id the key identifying the value to be cached
|
||||
* @param mixed $value the value to be cached
|
||||
* @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
|
||||
* @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labelled invalid.
|
||||
* @return boolean true if the value is successfully stored into cache, false otherwise
|
||||
*/
|
||||
public function add($id,$value,$expire=0,$dependency=null);
|
||||
/**
|
||||
* Deletes a value with the specified key from cache
|
||||
* @param string $id the key of the value to be deleted
|
||||
* @return boolean whether the deletion is successful
|
||||
*/
|
||||
public function delete($id);
|
||||
/**
|
||||
* Deletes all values from cache.
|
||||
* Be careful of performing this operation if the cache is shared by multiple applications.
|
||||
* @return boolean whether the flush operation was successful.
|
||||
*/
|
||||
public function flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* ICacheDependency is the interface that must be implemented by cache dependency classes.
|
||||
*
|
||||
* This interface must be implemented by classes meant to be used as
|
||||
* cache dependencies.
|
||||
*
|
||||
* Objects implementing this interface must be able to be serialized and unserialized.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.caching
|
||||
* @since 1.0
|
||||
*/
|
||||
interface ICacheDependency
|
||||
{
|
||||
/**
|
||||
* Evaluates the dependency by generating and saving the data related with dependency.
|
||||
* This method is invoked by cache before writing data into it.
|
||||
*/
|
||||
public function evaluateDependency();
|
||||
/**
|
||||
* @return boolean whether the dependency has changed.
|
||||
*/
|
||||
public function getHasChanged();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* IStatePersister is the interface that must be implemented by state persister classes.
|
||||
*
|
||||
* This interface must be implemented by all state persister classes (such as
|
||||
* {@link CStatePersister}.
|
||||
*
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
interface IStatePersister
|
||||
{
|
||||
/**
|
||||
* Loads state data from a persistent storage.
|
||||
* @return mixed the state
|
||||
*/
|
||||
public function load();
|
||||
/**
|
||||
* Saves state data into a persistent storage.
|
||||
* @param mixed $state the state to be saved
|
||||
*/
|
||||
public function save($state);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* IFilter is the interface that must be implemented by action filters.
|
||||
*
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
interface IFilter
|
||||
{
|
||||
/**
|
||||
* Performs the filtering.
|
||||
* This method should be implemented to perform actual filtering.
|
||||
* If the filter wants to continue the action execution, it should call
|
||||
* <code>$filterChain->run()</code>.
|
||||
* @param CFilterChain $filterChain the filter chain that the filter is on.
|
||||
*/
|
||||
public function filter($filterChain);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* IAction is the interface that must be implemented by controller actions.
|
||||
*
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
interface IAction
|
||||
{
|
||||
/**
|
||||
* @return string id of the action
|
||||
*/
|
||||
public function getId();
|
||||
/**
|
||||
* @return CController the controller instance
|
||||
*/
|
||||
public function getController();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* IWebServiceProvider interface may be implemented by Web service provider classes.
|
||||
*
|
||||
* If this interface is implemented, the provider instance will be able
|
||||
* to intercept the remote method invocation (e.g. for logging or authentication purpose).
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
interface IWebServiceProvider
|
||||
{
|
||||
/**
|
||||
* This method is invoked before the requested remote method is invoked.
|
||||
* @param CWebService $service the currently requested Web service.
|
||||
* @return boolean whether the remote method should be executed.
|
||||
*/
|
||||
public function beforeWebMethod($service);
|
||||
/**
|
||||
* This method is invoked after the requested remote method is invoked.
|
||||
* @param CWebService $service the currently requested Web service.
|
||||
*/
|
||||
public function afterWebMethod($service);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* IViewRenderer interface is implemented by a view renderer class.
|
||||
*
|
||||
* A view renderer is {@link CWebApplication::viewRenderer viewRenderer}
|
||||
* application component whose wants to replace the default view rendering logic
|
||||
* implemented in {@link CBaseController}.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
interface IViewRenderer
|
||||
{
|
||||
/**
|
||||
* Renders a view file.
|
||||
* @param CBaseController $context the controller or widget who is rendering the view file.
|
||||
* @param string $file the view file path
|
||||
* @param mixed $data the data to be passed to the view
|
||||
* @param boolean $return whether the rendering result should be returned
|
||||
* @return mixed the rendering result, or null if the rendering result is not needed.
|
||||
*/
|
||||
public function renderFile($context,$file,$data,$return);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* IUserIdentity interface is implemented by a user identity class.
|
||||
*
|
||||
* An identity represents a way to authenticate a user and retrieve
|
||||
* information needed to uniquely identity the user. It is normally
|
||||
* used with the {@link CWebApplication::user user application component}.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
interface IUserIdentity
|
||||
{
|
||||
/**
|
||||
* Authenticates the user.
|
||||
* The information needed to authenticate the user
|
||||
* are usually provided in the constructor.
|
||||
* @return boolean whether authentication succeeds.
|
||||
*/
|
||||
public function authenticate();
|
||||
/**
|
||||
* Returns a value indicating whether the identity is authenticated.
|
||||
* @return boolean whether the identity is valid.
|
||||
*/
|
||||
public function getIsAuthenticated();
|
||||
/**
|
||||
* Returns a value that uniquely represents the identity.
|
||||
* @return mixed a value that uniquely represents the identity (e.g. primary key value).
|
||||
*/
|
||||
public function getId();
|
||||
/**
|
||||
* Returns the display name for the identity (e.g. username).
|
||||
* @return string the display name for the identity.
|
||||
*/
|
||||
public function getName();
|
||||
/**
|
||||
* Returns the additional identity information that needs to be persistent during the user session.
|
||||
* @return array additional identity information that needs to be persistent during the user session (excluding {@link id}).
|
||||
*/
|
||||
public function getPersistentStates();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* IWebUser interface is implemented by a {@link CWebApplication::user user application component}.
|
||||
*
|
||||
* A user application component represents the identity information
|
||||
* for the current user.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
interface IWebUser
|
||||
{
|
||||
/**
|
||||
* Returns a value that uniquely represents the identity.
|
||||
* @return mixed a value that uniquely represents the identity (e.g. primary key value).
|
||||
*/
|
||||
public function getId();
|
||||
/**
|
||||
* Returns the display name for the identity (e.g. username).
|
||||
* @return string the display name for the identity.
|
||||
*/
|
||||
public function getName();
|
||||
/**
|
||||
* Returns a value indicating whether the user is a guest (not authenticated).
|
||||
* @return boolean whether the user is a guest (not authenticated)
|
||||
*/
|
||||
public function getIsGuest();
|
||||
/**
|
||||
* Performs access check for this user.
|
||||
* @param string $operation the name of the operation that need access check.
|
||||
* @param array $params name-value pairs that would be passed to business rules associated
|
||||
* with the tasks and roles assigned to the user.
|
||||
* @return boolean whether the operations can be performed by this user.
|
||||
*/
|
||||
public function checkAccess($operation,$params=array());
|
||||
/**
|
||||
* Redirects the user browser to the login page.
|
||||
* Before the redirection, the current URL (if it's not an AJAX url) will be
|
||||
* kept in {@link returnUrl} so that the user browser may be redirected back
|
||||
* to the current page after successful login. Make sure you set {@link loginUrl}
|
||||
* so that the user browser can be redirected to the specified login URL after
|
||||
* calling this method.
|
||||
* After calling this method, the current request processing will be terminated.
|
||||
*/
|
||||
public function loginRequired();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* IAuthManager interface is implemented by an auth manager application component.
|
||||
*
|
||||
* An auth manager is mainly responsible for providing role-based access control (RBAC) service.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
* @since 1.0
|
||||
*/
|
||||
interface IAuthManager
|
||||
{
|
||||
/**
|
||||
* Performs access check for the specified user.
|
||||
* @param string $itemName the name of the operation that we are checking access to
|
||||
* @param mixed $userId the user ID. This should be either an integer or a string representing
|
||||
* the unique identifier of a user. See {@link IWebUser::getId}.
|
||||
* @param array $params 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.
|
||||
*/
|
||||
public function checkAccess($itemName,$userId,$params=array());
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @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
|
||||
* @param string $bizRule business rule associated with the item. This is a piece of
|
||||
* PHP code that will be executed when {@link checkAccess} is called for the item.
|
||||
* @param mixed $data additional data associated with the item.
|
||||
* @return CAuthItem the authorization item
|
||||
* @throws CException if an item with the same name already exists
|
||||
*/
|
||||
public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
|
||||
/**
|
||||
* Removes the specified authorization item.
|
||||
* @param string $name the name of the item to be removed
|
||||
* @return boolean whether the item exists in the storage and has been removed
|
||||
*/
|
||||
public function removeAuthItem($name);
|
||||
/**
|
||||
* Returns the authorization items of the specific type and user.
|
||||
* @param integer $type the item type (0: operation, 1: task, 2: role). Defaults to null,
|
||||
* meaning returning all items regardless of their type.
|
||||
* @param mixed $userId 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.
|
||||
*/
|
||||
public function getAuthItems($type=null,$userId=null);
|
||||
/**
|
||||
* Returns the authorization item with the specified name.
|
||||
* @param string $name the name of the item
|
||||
* @return CAuthItem the authorization item. Null if the item cannot be found.
|
||||
*/
|
||||
public function getAuthItem($name);
|
||||
/**
|
||||
* Saves an authorization item to persistent storage.
|
||||
* @param CAuthItem $item the item to be saved.
|
||||
* @param string $oldName the old item name. If null, it means the item name is not changed.
|
||||
*/
|
||||
public function saveAuthItem($item,$oldName=null);
|
||||
|
||||
/**
|
||||
* Adds an item as a child of another item.
|
||||
* @param string $itemName the parent item name
|
||||
* @param string $childName the child item name
|
||||
* @throws CException if either parent or child doesn't exist or if a loop has been detected.
|
||||
*/
|
||||
public function addItemChild($itemName,$childName);
|
||||
/**
|
||||
* Removes a child from its parent.
|
||||
* Note, the child item is not deleted. Only the parent-child relationship is removed.
|
||||
* @param string $itemName the parent item name
|
||||
* @param string $childName the child item name
|
||||
* @return boolean whether the removal is successful
|
||||
*/
|
||||
public function removeItemChild($itemName,$childName);
|
||||
/**
|
||||
* Returns a value indicating whether a child exists within a parent.
|
||||
* @param string $itemName the parent item name
|
||||
* @param string $childName the child item name
|
||||
* @return boolean whether the child exists
|
||||
*/
|
||||
public function hasItemChild($itemName,$childName);
|
||||
/**
|
||||
* Returns the children of the specified item.
|
||||
* @param mixed $itemName the parent item name. This can be either a string or an array.
|
||||
* The latter represents a list of item names.
|
||||
* @return array all child items of the parent
|
||||
*/
|
||||
public function getItemChildren($itemName);
|
||||
|
||||
/**
|
||||
* Assigns an authorization item to a user.
|
||||
* @param string $itemName the item name
|
||||
* @param mixed $userId the user ID (see {@link IWebUser::getId})
|
||||
* @param string $bizRule the business rule to be executed when {@link checkAccess} is called
|
||||
* for this particular authorization item.
|
||||
* @param mixed $data additional data associated with this assignment
|
||||
* @return CAuthAssignment the authorization assignment information.
|
||||
* @throws CException if the item does not exist or if the item has already been assigned to the user
|
||||
*/
|
||||
public function assign($itemName,$userId,$bizRule=null,$data=null);
|
||||
/**
|
||||
* Revokes an authorization assignment from a user.
|
||||
* @param string $itemName the item name
|
||||
* @param mixed $userId the user ID (see {@link IWebUser::getId})
|
||||
* @return boolean whether removal is successful
|
||||
*/
|
||||
public function revoke($itemName,$userId);
|
||||
/**
|
||||
* Returns a value indicating whether the item has been assigned to the user.
|
||||
* @param string $itemName the item name
|
||||
* @param mixed $userId the user ID (see {@link IWebUser::getId})
|
||||
* @return boolean whether the item has been assigned to the user.
|
||||
*/
|
||||
public function isAssigned($itemName,$userId);
|
||||
/**
|
||||
* Returns the item assignment information.
|
||||
* @param string $itemName the item name
|
||||
* @param mixed $userId the user ID (see {@link IWebUser::getId})
|
||||
* @return CAuthAssignment the item assignment information. Null is returned if
|
||||
* the item is not assigned to the user.
|
||||
*/
|
||||
public function getAuthAssignment($itemName,$userId);
|
||||
/**
|
||||
* Returns the item assignments for the specified user.
|
||||
* @param mixed $userId the user ID (see {@link 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.
|
||||
*/
|
||||
public function getAuthAssignments($userId);
|
||||
/**
|
||||
* Saves the changes to an authorization assignment.
|
||||
* @param CAuthAssignment $assignment the assignment that has been changed.
|
||||
*/
|
||||
public function saveAuthAssignment($assignment);
|
||||
|
||||
/**
|
||||
* Removes all authorization data.
|
||||
*/
|
||||
public function clearAll();
|
||||
/**
|
||||
* Removes all authorization assignments.
|
||||
*/
|
||||
public function clearAuthAssignments();
|
||||
|
||||
/**
|
||||
* 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();
|
||||
|
||||
/**
|
||||
* Executes a business rule.
|
||||
* A business rule is a piece of PHP code that will be executed when {@link checkAccess} is called.
|
||||
* @param string $bizRule the business rule to be executed.
|
||||
* @param array $params additional parameters to be passed to the business rule when being executed.
|
||||
* @param mixed $data additional data that is associated with the corresponding authorization item or assignment
|
||||
* @return boolean whether the execution returns a true value.
|
||||
* If the business rule is empty, it will also return true.
|
||||
*/
|
||||
public function executeBizRule($bizRule,$params,$data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* IBehavior interfaces is implemented by all behavior classes.
|
||||
*
|
||||
* A behavior is a way to enhance a component with additional methods that
|
||||
* are defined in the behavior class and not available in the component class.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.base
|
||||
*/
|
||||
interface IBehavior
|
||||
{
|
||||
/**
|
||||
* Attaches the behavior object to the component.
|
||||
* @param CComponent $component the component that this behavior is to be attached to.
|
||||
*/
|
||||
public function attach($component);
|
||||
/**
|
||||
* Detaches the behavior object from the component.
|
||||
* @param CComponent $component the component that this behavior is to be detached from.
|
||||
*/
|
||||
public function detach($component);
|
||||
/**
|
||||
* @return boolean whether this behavior is enabled
|
||||
*/
|
||||
public function getEnabled();
|
||||
/**
|
||||
* @param boolean $value whether this behavior is enabled
|
||||
*/
|
||||
public function setEnabled($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* IWidgetFactory is the interface that must be implemented by a widget factory class.
|
||||
*
|
||||
* When calling {@link CBaseController::createWidget}, if a widget factory is available,
|
||||
* it will be used for creating the requested widget.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.web
|
||||
* @since 1.1
|
||||
*/
|
||||
interface IWidgetFactory
|
||||
{
|
||||
/**
|
||||
* Creates a new widget based on the given class name and initial properties.
|
||||
* @param CBaseController $owner the owner of the new widget
|
||||
* @param string $className the class name of the widget. This can also be a path alias (e.g. system.web.widgets.COutputCache)
|
||||
* @param array $properties the initial property values (name=>value) of the widget.
|
||||
* @return CWidget the newly created widget whose properties have been initialized with the given values.
|
||||
*/
|
||||
public function createWidget($owner,$className,$properties=array());
|
||||
}
|
||||
|
||||
/**
|
||||
* IDataProvider is the interface that must be implemented by data provider classes.
|
||||
*
|
||||
* Data providers are components that can feed data for widgets such as data grid, data list.
|
||||
* Besides providing data, they also support pagination and sorting.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @package system.web
|
||||
* @since 1.1
|
||||
*/
|
||||
interface IDataProvider
|
||||
{
|
||||
/**
|
||||
* @return string the unique ID that identifies the data provider from other data providers.
|
||||
*/
|
||||
public function getId();
|
||||
/**
|
||||
* Returns the number of data items in the current page.
|
||||
* This is equivalent to <code>count($provider->getData())</code>.
|
||||
* When {@link pagination} is set false, this returns the same value as {@link totalItemCount}.
|
||||
* @param boolean $refresh whether the number of data items should be re-calculated.
|
||||
* @return integer the number of data items in the current page.
|
||||
*/
|
||||
public function getItemCount($refresh=false);
|
||||
/**
|
||||
* Returns the total number of data items.
|
||||
* When {@link pagination} is set false, this returns the same value as {@link itemCount}.
|
||||
* @param boolean $refresh whether the total number of data items should be re-calculated.
|
||||
* @return integer total number of possible data items.
|
||||
*/
|
||||
public function getTotalItemCount($refresh=false);
|
||||
/**
|
||||
* Returns the data items currently available.
|
||||
* @param boolean $refresh whether the data should be re-fetched from persistent storage.
|
||||
* @return array the list of data items currently available in this data provider.
|
||||
*/
|
||||
public function getData($refresh=false);
|
||||
/**
|
||||
* Returns the key values associated with the data items.
|
||||
* @param boolean $refresh whether the keys should be re-calculated.
|
||||
* @return array the list of key values corresponding to {@link data}. Each data item in {@link data}
|
||||
* is uniquely identified by the corresponding key value in this array.
|
||||
*/
|
||||
public function getKeys($refresh=false);
|
||||
/**
|
||||
* @return CSort the sorting object. If this is false, it means the sorting is disabled.
|
||||
*/
|
||||
public function getSort();
|
||||
/**
|
||||
* @return CPagination the pagination object. If this is false, it means the pagination is disabled.
|
||||
*/
|
||||
public function getPagination();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* ILogFilter is the interface that must be implemented by log filters.
|
||||
*
|
||||
* A log filter preprocesses the logged messages before they are handled by a log route.
|
||||
* You can attach classes that implement ILogFilter to {@link CLogRoute::$filter}.
|
||||
*
|
||||
* @package system.logging
|
||||
* @since 1.1.11
|
||||
*/
|
||||
interface ILogFilter
|
||||
{
|
||||
/**
|
||||
* This method should be implemented to perform actual filtering of log messages
|
||||
* by working on the array given as the first parameter.
|
||||
* Implementation might reformat, remove or add information to logged messages.
|
||||
* @param array $logs list of messages. Each array element represents one message
|
||||
* with the following structure:
|
||||
* array(
|
||||
* [0] => message (string)
|
||||
* [1] => level (string)
|
||||
* [2] => category (string)
|
||||
* [3] => timestamp (float, obtained by microtime(true));
|
||||
*/
|
||||
public function filter(&$logs);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user