* @link http://www.yiiframework.com/ * @copyright Copyright © 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ * @version $Id$ * @since 1.0 */ defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME',microtime(true)); defined('YII_DEBUG') or define('YII_DEBUG',false); defined('YII_ENABLE_EXCEPTION_HANDLER') or define('YII_ENABLE_EXCEPTION_HANDLER',true); defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER',true); defined('YII_PATH') or define('YII_PATH',dirname(__FILE__)); class YiiBase { private static $_aliases=array('system'=>YII_PATH); // alias => path private static $_imports=array(); // alias => class name or directory private static $_classes=array(); private static $_app; private static $_logger; public static function getVersion() { return '1.0b'; } public static function createWebApplication($config=null) { return new CWebApplication($config); } public static function createConsoleApplication($config=null) { return new CConsoleApplication($config); } public static function app() { return self::$_app; } public static function setApplication($app) { if(self::$_app===null || $app===null) self::$_app=$app; else throw new CException(Yii::t('yii#Yii application can only be created once.')); } public static function getFrameworkPath() { return YII_PATH; } public static function createComponent($type) { $type=self::import($type,true); if(($n=func_num_args())>1) { $args=func_get_args(); for($s='$args[1]',$i=2;$i<$n;++$i) $s.=",\$args[$i]"; eval("\$component=new $type($s);"); return $component; } else return new $type; } public static function import($alias,$forceInclude=false) { if(isset(self::$_imports[$alias])) // previously imported return self::$_imports[$alias]; if(isset(self::$_coreClasses[$alias]) || ($pos=strrpos($alias,'.'))===false) // a simple class name { self::$_imports[$alias]=$alias; if($forceInclude && !class_exists($alias,false)) { if(isset(self::$_coreClasses[$alias])) // a core class require_once(YII_PATH.self::$_coreClasses[$alias]); else require_once($alias.'.php'); } return $alias; } if(($className=(string)substr($alias,$pos+1))!=='*' && class_exists($className,false)) return self::$_imports[$alias]=$className; if(($path=self::getPathOfAlias($alias))!==false) { if($className!=='*') { self::$_imports[$alias]=$className; if($forceInclude) require_once($path.'.php'); else self::$_classes[$className]=$path.'.php'; return $className; } else // a directory { set_include_path(get_include_path().PATH_SEPARATOR.$path); return self::$_imports[$alias]=$path; } } else throw new CException(Yii::t('yii#Alias "{alias}" is invalid. Make sure it points to an existing directory or file.', array('{alias}'=>$alias))); } public static function getPathOfAlias($alias) { if(isset(self::$_aliases[$alias])) return self::$_aliases[$alias]; else if(($pos=strpos($alias,'.'))!==false) { $rootAlias=substr($alias,0,$pos); if(isset(self::$_aliases[$rootAlias])) return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR); } return self::$_aliases[$alias]=false; } public static function setPathOfAlias($alias,$path) { if($path===null) unset(self::$_aliases[$alias]); else if(!isset(self::$_aliases[$alias]) && ($rp=realpath($path))!==false) self::$_aliases[$alias]=rtrim($rp,'\\/'); else if(isset(self::$_aliases[$alias])) throw new CException(Yii::t('yii#Path alias "{alias}" is redefined.', array('{alias}'=>$alias))); else throw new CException(Yii::t('yii#Path alias "{alias}" points to an invalid directory "{path}".', array('{alias}'=>$alias, '{path}'=>$path))); } public static function autoload($className) { // use include_once so that the error PHP file may appear if(isset(self::$_coreClasses[$className])) include_once(YII_PATH.self::$_coreClasses[$className]); else if(isset(self::$_classes[$className])) include_once(self::$_classes[$className]); else include_once($className.'.php'); } public static function trace($msg,$category='application') { if(YII_DEBUG) self::log($msg,CLogger::LEVEL_TRACE,$category); } public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application') { if(self::$_logger===null) self::$_logger=new CLogger; self::$_logger->log($msg,$level,$category); } public static function beginProfile($token,$category='application') { self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category); } public static function endProfile($token,$category='application') { self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category); } public static function getLogger() { if(self::$_logger!==null) return self::$_logger; else return self::$_logger=new CLogger; } public static function powered() { return 'Powered by Yii Framework.'; } public static function t($message,$params=array()) { if(self::$_app!==null && ($pos=strpos($message,'#'))!==false) { $category=substr($message,0,$pos); $source=$category==='yii'?self::$_app->getCoreMessages():self::$_app->getMessages(); if($source!==null) $message=$source->translate((string)substr($message,$pos+1),$category); } return $params!==array() ? strtr($message,$params) : $message; } private static $_coreClasses=array( 'CApcCache' => '/caching/CApcCache.php', 'CCache' => '/caching/CCache.php', 'CDbCache' => '/caching/CDbCache.php', 'CMemCache' => '/caching/CMemCache.php', 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php', 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php', 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php', 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php', 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php', 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php', 'CAttributeCollection' => '/collections/CAttributeCollection.php', 'CConfiguration' => '/collections/CConfiguration.php', 'CList' => '/collections/CList.php', 'CMap' => '/collections/CMap.php', 'CQueue' => '/collections/CQueue.php', 'CStack' => '/collections/CStack.php', 'CTypedList' => '/collections/CTypedList.php', 'CConsoleApplication' => '/console/CConsoleApplication.php', 'CConsoleCommand' => '/console/CConsoleCommand.php', 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php', 'CHelpCommand' => '/console/CHelpCommand.php', 'CApplication' => '/core/CApplication.php', 'CApplicationComponent' => '/core/CApplicationComponent.php', 'CComponent' => '/core/CComponent.php', 'CErrorHandler' => '/core/CErrorHandler.php', 'CException' => '/core/CException.php', 'CHttpException' => '/core/CHttpException.php', 'CModel' => '/core/CModel.php', 'CSecurityManager' => '/core/CSecurityManager.php', 'CStatePersister' => '/core/CStatePersister.php', 'CDbLogRoute' => '/core/log/CDbLogRoute.php', 'CEmailLogRoute' => '/core/log/CEmailLogRoute.php', 'CFileLogRoute' => '/core/log/CFileLogRoute.php', 'CLogRoute' => '/core/log/CLogRoute.php', 'CLogRouter' => '/core/log/CLogRouter.php', 'CLogger' => '/core/log/CLogger.php', 'CProfileLogRoute' => '/core/log/CProfileLogRoute.php', 'CWebLogRoute' => '/core/log/CWebLogRoute.php', 'CDbCommand' => '/db/CDbCommand.php', 'CDbConnection' => '/db/CDbConnection.php', 'CDbDataReader' => '/db/CDbDataReader.php', 'CDbException' => '/db/CDbException.php', 'CDbTransaction' => '/db/CDbTransaction.php', 'CActiveFinder' => '/db/ar/CActiveFinder.php', 'CActiveRecord' => '/db/ar/CActiveRecord.php', 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php', 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php', 'CDbCriteria' => '/db/schema/CDbCriteria.php', 'CDbSchema' => '/db/schema/CDbSchema.php', 'CDbTableSchema' => '/db/schema/CDbTableSchema.php', 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php', 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php', 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php', 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php', 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php', 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php', 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php', 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php', 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php', 'CDateFormatter' => '/i18n/CDateFormatter.php', 'CDbMessageSource' => '/i18n/CDbMessageSource.php', 'CLocale' => '/i18n/CLocale.php', 'CMessageSource' => '/i18n/CMessageSource.php', 'CNumberFormatter' => '/i18n/CNumberFormatter.php', 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php', 'CDateParser' => '/utils/CDateParser.php', 'CFileHelper' => '/utils/CFileHelper.php', 'CTimestamp' => '/utils/CTimestamp.php', 'CVarDumper' => '/utils/CVarDumper.php', 'CCaptchaValidator' => '/validators/CCaptchaValidator.php', 'CCompareValidator' => '/validators/CCompareValidator.php', 'CEmailValidator' => '/validators/CEmailValidator.php', 'CFilterValidator' => '/validators/CFilterValidator.php', 'CInlineValidator' => '/validators/CInlineValidator.php', 'CNumberValidator' => '/validators/CNumberValidator.php', 'CRangeValidator' => '/validators/CRangeValidator.php', 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php', 'CRequiredValidator' => '/validators/CRequiredValidator.php', 'CStringValidator' => '/validators/CStringValidator.php', 'CTypeValidator' => '/validators/CTypeValidator.php', 'CUniqueValidator' => '/validators/CUniqueValidator.php', 'CUrlValidator' => '/validators/CUrlValidator.php', 'CValidator' => '/validators/CValidator.php', 'CAssetManager' => '/web/CAssetManager.php', 'CBaseController' => '/web/CBaseController.php', 'CCacheHttpSession' => '/web/CCacheHttpSession.php', 'CClientScript' => '/web/CClientScript.php', 'CController' => '/web/CController.php', 'CDbHttpSession' => '/web/CDbHttpSession.php', 'CExtController' => '/web/CExtController.php', 'CFormModel' => '/web/CFormModel.php', 'CHttpCookie' => '/web/CHttpCookie.php', 'CHttpRequest' => '/web/CHttpRequest.php', 'CHttpSession' => '/web/CHttpSession.php', 'COutputEvent' => '/web/COutputEvent.php', 'CPagination' => '/web/CPagination.php', 'CTheme' => '/web/CTheme.php', 'CThemeManager' => '/web/CThemeManager.php', 'CUrlManager' => '/web/CUrlManager.php', 'CWebApplication' => '/web/CWebApplication.php', 'CWebService' => '/web/CWebService.php', 'CWsdlGenerator' => '/web/CWsdlGenerator.php', 'CAction' => '/web/actions/CAction.php', 'CCaptchaAction' => '/web/actions/CCaptchaAction.php', 'CInlineAction' => '/web/actions/CInlineAction.php', 'CViewAction' => '/web/actions/CViewAction.php', 'CWebServiceAction' => '/web/actions/CWebServiceAction.php', 'CAuthAssignment' => '/web/auth/CAuthAssignment.php', 'CAuthItem' => '/web/auth/CAuthItem.php', 'CAuthManager' => '/web/auth/CAuthManager.php', 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php', 'CDbAuthManager' => '/web/auth/CDbAuthManager.php', 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php', 'CUserIdentity' => '/web/auth/CUserIdentity.php', 'CWebUser' => '/web/auth/CWebUser.php', 'CAccessControlFilter' => '/web/filters/CAccessControlFilter.php', 'CFilter' => '/web/filters/CFilter.php', 'CFilterChain' => '/web/filters/CFilterChain.php', 'CInlineFilter' => '/web/filters/CInlineFilter.php', 'CHtml' => '/web/helpers/CHtml.php', 'CJSON' => '/web/helpers/CJSON.php', 'CJavaScript' => '/web/helpers/CJavaScript.php', 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php', 'CViewRenderer' => '/web/renderers/CViewRenderer.php', 'CAutoComplete' => '/web/widgets/CAutoComplete.php', 'CCaptcha' => '/web/widgets/CCaptcha.php', 'CClipWidget' => '/web/widgets/CClipWidget.php', 'CContentDecorator' => '/web/widgets/CContentDecorator.php', 'CFilterWidget' => '/web/widgets/CFilterWidget.php', 'CFlexWidget' => '/web/widgets/CFlexWidget.php', 'CInputWidget' => '/web/widgets/CInputWidget.php', 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php', 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php', 'COutputCache' => '/web/widgets/COutputCache.php', 'COutputProcessor' => '/web/widgets/COutputProcessor.php', 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php', 'CTreeView' => '/web/widgets/CTreeView.php', 'CWidget' => '/web/widgets/CWidget.php', 'CBasePager' => '/web/widgets/pagers/CBasePager.php', 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php', 'CListPager' => '/web/widgets/pagers/CListPager.php', ); } spl_autoload_register(array('YiiBase','autoload')); class Yii extends YiiBase { } class CComponent { private $_e; public function __get($name) { $getter='get'.$name; if(method_exists($this,$getter)) return $this->$getter(); else if(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]; } else throw new CException(Yii::t('yii#Property "{class}.{property}" is not defined.', array('{class}'=>get_class($this), '{property}'=>$name))); } public function __set($name,$value) { $setter='set'.$name; if(method_exists($this,$setter)) $this->$setter($value); else if(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; $this->_e[$name]->add($value); } else 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))); } public function hasProperty($name) { return method_exists($this,'get'.$name) || method_exists($this,'set'.$name); } public function canGetProperty($name) { return method_exists($this,'get'.$name); } public function canSetProperty($name) { return method_exists($this,'set'.$name); } public function hasEvent($name) { return !strncasecmp($name,'on',2) && method_exists($this,$name); } public function hasEventHandler($name) { $name=strtolower($name); return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0; } 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))); } public function attachEventHandler($name,$handler) { $this->getEventHandlers($name)->add($handler); } public function detachEventHandler($name,$handler) { if($this->hasEventHandler($name)) { try { $this->getEventHandlers($name)->remove($handler); return true; } catch(Exception $e) { } } return false; } 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); else if(is_callable($handler,true)) { // an array: 0 - object, 1 - method name list($object,$method)=$handler; if(is_string($object)) // static method call call_user_func($handler,$event); else if(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 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; } } else if(!$this->hasEvent($name)) throw new CException(Yii::t('yii#Event "{class}.{event}" is not defined.', array('{class}'=>get_class($this), '{event}'=>$name))); } } class CEvent extends CComponent { public $sender; public $handled=false; public function __construct($sender=null) { $this->sender=$sender; } } class CEnumerable { } class CPropertyValue { public static function ensureBoolean($value) { if (is_string($value)) return !strcasecmp($value,'true') || $value!=0; else return (boolean)$value; } public static function ensureString($value) { if (is_bool($value)) return $value?'true':'false'; else return (string)$value; } public static function ensureInteger($value) { return (integer)$value; } public static function ensureFloat($value) { return (float)$value; } public static function ensureArray($value) { if(is_string($value)) { $value = trim($value); $len = strlen($value); if ($len >= 2 && $value[0] == '(' && $value[$len-1] == ')') { eval('$array=array'.$value.';'); return $array; } else return $len>0?array($value):array(); } else return (array)$value; } public static function ensureObject($value) { return (object)$value; } public static function ensureEnum($value,$enumType) { static $types=array(); if(!isset($types[$enumType])) $types[$enumType]=new ReflectionClass($enumType); if($types[$enumType]->hasConstant($value)) return $value; else throw new CException(Yii::t('yii#Invalid enumerable value "{value}". Please make sure it is among ({enum}).', array('{value}'=>$value, '{enum}'=>implode(', ',$types[$enumType]->getConstants())))); } } abstract class CApplication extends CComponent { public $name='My Application'; public $charset='UTF-8'; public $preload=array(); public $sourceLanguage='en_us'; private $_id; private $_basePath; private $_runtimePath; private $_extensionPath; private $_globalState; private $_stateChanged; private $_params; private $_components=array(); private $_componentConfig=array(); private $_ended=false; private $_language; abstract public function processRequest(); public function __construct($config=null) { Yii::setApplication($this); $this->initSystemHandlers(); $this->registerCoreComponents(); $this->configure($config); $this->init(); } protected function init() { $this->preloadComponents(); } public function __get($name) { if($this->hasComponent($name)) return $this->getComponent($name); else return parent::__get($name); } public function run() { $this->onBeginRequest(new CEvent($this)); $this->processRequest(); $this->onEndRequest(new CEvent($this)); } public function end($status=0) { $this->onEndRequest(new CEvent($this)); exit($status); } public function onBeginRequest($event) { $this->raiseEvent('onBeginRequest',$event); } public function onEndRequest($event) { if(!$this->_ended) { $this->_ended=true; $this->raiseEvent('onEndRequest',$event); } } public function getId() { if($this->_id!==null) return $this->_id; else return $this->_id=md5($this->getBasePath().$this->name); } public function setId($id) { $this->_id=$id; } public function getBasePath() { return $this->_basePath; } 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))); } public function getRuntimePath() { if($this->_runtimePath!==null) return $this->_runtimePath; else { $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime'); return $this->_runtimePath; } } 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}'=>$runtimePath))); $this->_runtimePath=$runtimePath; } final public function getExtensionPath() { if($this->_extensionPath!==null) return $this->_extensionPath; else return $this->_extensionPath=$this->getBasePath().DIRECTORY_SEPARATOR.'extensions'; } public function setImport($aliases) { foreach($aliases as $alias) Yii::import($alias); } public function getLanguage() { return $this->_language===null ? $this->sourceLanguage : $this->_language; } public function setLanguage($language) { $this->_language=$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; } public function getLocale($localeID=null) { return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID); } public function getNumberFormatter() { return $this->getLocale()->getNumberFormatter(); } public function getDateFormatter() { return $this->getLocale()->getDateFormatter(); } public function getDb() { return $this->getComponent('db'); } public function getErrorHandler() { return $this->getComponent('errorHandler'); } public function getSecurityManager() { return $this->getComponent('securityManager'); } public function getStatePersister() { return $this->getComponent('statePersister'); } public function getCache() { return $this->getComponent('cache'); } public function getCoreMessages() { return $this->getComponent('coreMessages'); } public function getMessages() { return $this->getComponent('messages'); } public function getParams() { if($this->_params!==null) return $this->_params; else return $this->_params=new CAttributeCollection; } public function setParams($value) { if(is_array($value)) $this->_params=new CAttributeCollection($value); else $this->_params=$value; } public function getGlobalState($key,$defaultValue=null) { if($this->_globalState===null) $this->loadGlobalState(); if(isset($this->_globalState[$key])) return $this->_globalState[$key]; else return $defaultValue; } public function setGlobalState($key,$value,$defaultValue=null) { if($this->_globalState===null) $this->loadGlobalState(); $this->_stateChanged=true; if($value===$defaultValue) unset($this->_globalState[$key]); else $this->_globalState[$key]=$value; } public function clearGlobalState($key) { if($this->_globalState===null) $this->loadGlobalState(); if(isset($this->_globals[$key])) { $this->_stateChanged=true; unset($this->_globals[$key]); } } protected function loadGlobalState() { $persister=$this->getStatePersister(); if(($this->_globalState=$persister->load())===null) $this->_globalState=array(); $this->_stateChanged=false; $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState')); } protected function saveGlobalState() { if($this->_stateChanged) { $persister=$this->getStatePersister(); $this->_stateChanged=false; $persister->save($this->_globalState); } } 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; $message=(string)$exception; if(isset($_SERVER['REQUEST_URI'])) $message.=' REQUEST_URI='.$_SERVER['REQUEST_URI']; Yii::log($message,CLogger::LEVEL_ERROR,$category); $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); } $this->end(1); } 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)"; if(isset($_SERVER['REQUEST_URI'])) $log.=' REQUEST_URI='.$_SERVER['REQUEST_URI']; Yii::log($log,CLogger::LEVEL_ERROR,'php'); $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); } $this->end(1); } } public function onException($event) { $this->raiseEvent('onException',$event); } public function onError($event) { $this->raiseEvent('onError',$event); } public function displayError($code,$message,$file,$line) { if(YII_DEBUG) { echo "
$message ($file:$line)
\n"; echo ''; debug_print_backtrace(); echo ''; } else { echo "
$message
\n"; } } public function displayException($exception) { if(YII_DEBUG) { echo ''.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')
'; echo ''.$exception->getTraceAsString().''; } else { echo '
'.$exception->getMessage().'
'; } } public function hasComponent($id) { return isset($this->_components[$id]) || isset($this->_componentConfig[$id]); } public function getComponent($id) { if(isset($this->_components[$id])) return $this->_components[$id]; else if(isset($this->_componentConfig[$id])) { $config=$this->_componentConfig[$id]; unset($this->_componentConfig[$id]); if(!isset($config['enabled']) || $config['enabled']) { unset($config['enabled']); $component=CConfiguration::createObject($config); $component->init(); return $this->_components[$id]=$component; } } return null; } public function setComponent($id,$component) { $this->_components[$id]=$component; if(!$component->getIsInitialized()) $component->init(); } protected function configure($config) { $config=new CConfiguration($config); if(($basePath=$config->remove('basePath'))===null) $basePath='protected'; $this->setBasePath($basePath); Yii::setPathOfAlias('application',$this->getBasePath()); $config->applyTo($this); } 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()); } 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', ), ); $this->setComponents($components); } protected function preloadComponents() { foreach($this->preload as $id) $this->getComponent($id); } public function getComponents() { return $this->_components; } public function setComponents($components) { foreach($components as $id=>$component) { if($component instanceof IApplicationComponent) $this->setComponent($id,$component); else if(isset($this->_componentConfig[$id])) $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component); else $this->_componentConfig[$id]=$component; } } } class CExceptionEvent extends CEvent { public $exception; public function __construct($sender,$exception) { $this->exception=$exception; parent::__construct($sender); } } class CErrorEvent extends CEvent { public $code; public $message; public $file; public $line; public function __construct($sender,$code,$message,$file,$line) { $this->code=$code; $this->message=$message; $this->file=$file; $this->line=$line; parent::__construct($sender); } } class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable { private $_d=array(); private $_r=false; public function __construct($data=null,$readOnly=false) { if($data!==null) $this->copyFrom($data); $this->setReadOnly($readOnly); } public function getReadOnly() { return $this->_r; } protected function setReadOnly($value) { $this->_r=$value; } public function getIterator() { return new CMapIterator($this->_d); } public function count() { return $this->getCount(); } public function getCount() { return count($this->_d); } public function getKeys() { return array_keys($this->_d); } public function itemAt($key) { if(isset($this->_d[$key])) return $this->_d[$key]; else return null; } public function add($key,$value) { if(!$this->_r) $this->_d[$key]=$value; else throw new CException(Yii::t('yii#The map is read only.')); } public function remove($key) { if(!$this->_r) { if(isset($this->_d[$key])) { $value=$this->_d[$key]; unset($this->_d[$key]); return $value; } else { // it is possible the value is null, which is not detected by isset unset($this->_d[$key]); return null; } } else throw new CException(Yii::t('yii#The map is read only.')); } public function clear() { foreach(array_keys($this->_d) as $key) $this->remove($key); } public function contains($key) { return isset($this->_d[$key]) || array_key_exists($key,$this->_d); } public function toArray() { return $this->_d; } public function copyFrom($data) { if(is_array($data) || $data instanceof Traversable) { if($this->getCount()>0) $this->clear(); if($data instanceof CMap) $data=$data->_d; foreach($data as $key=>$value) $this->add($key,$value); } else if($data!==null) throw new CException(Yii::t('yii#Map data must be an array or an object implementing Traversable.')); } public function mergeWith($data,$recursive=true) { if(is_array($data) || $data instanceof Traversable) { if($data instanceof CMap) $data=$data->_d; if($recursive) { if($data instanceof Traversable) { $d=array(); foreach($data as $key=>$value) $d[$key]=$value; $this->_d=self::mergeArray($this->_d,$d); } else $this->_d=self::mergeArray($this->_d,$data); } else { foreach($data as $key=>$value) $this->add($key,$value); } } else if($data!==null) throw new CException(Yii::t('yii#Map data must be an array or an object implementing Traversable.')); } public static function mergeArray($a,$b) { foreach($b as $k=>$v) { if(is_integer($k)) $a[]=$v; else if(is_array($v) && isset($a[$k]) && is_array($a[$k])) $a[$k]=self::mergeArray($a[$k],$v); else $a[$k]=$v; } return $a; } public function offsetExists($offset) { return $this->contains($offset); } public function offsetGet($offset) { return $this->itemAt($offset); } public function offsetSet($offset,$item) { $this->add($offset,$item); } public function offsetUnset($offset) { $this->remove($offset); } } class CMapIterator implements Iterator { private $_d; private $_keys; private $_key; public function __construct(&$data) { $this->_d=&$data; $this->_keys=array_keys($data); } public function rewind() { $this->_key=reset($this->_keys); } public function key() { return $this->_key; } public function current() { return $this->_d[$this->_key]; } public function next() { $this->_key=next($this->_keys); } public function valid() { return $this->_key!==false; } } class CConfiguration extends CMap { public function __construct($data=null) { if(is_string($data)) parent::__construct(require($data)); else parent::__construct($data); } public function loadFromFile($configFile) { $data=require($configFile); if($this->getCount()>0) $this->mergeWith($data); else $this->copyFrom($data); } public function saveAsString() { return str_replace("\r",'',var_export($this->toArray(),true)); } public function applyTo($object) { foreach($this->toArray() as $key=>$value) $object->$key=$value; } public static function createObject($config) { if(is_string($config)) $config=array('class'=>$config); else if($config instanceof self) $config=$config->toArray(); if(is_array($config) && isset($config['class'])) { $className=Yii::import($config['class'],true); unset($config['class']); if(($n=func_num_args())>1) { $args=func_get_args(); for($s='$args[1]',$i=2;$i<$n;++$i) $s.=",\$args[$i]"; eval("\$object=new $className($s);"); } else $object=new $className; foreach($config as $key=>$value) $object->$key=$value; return $object; } else throw new CException(Yii::t('yii#Object configuration must be an array containing a "class" element.')); } } class CWebApplication extends CApplication { public $defaultController='site'; public $layout='main'; public $controllerMap=array(); public $catchAllRequest; private $_controllerPath; private $_viewPath; private $_systemViewPath; private $_layoutPath; private $_controller; private $_homeUrl; private $_theme; public function processRequest() { if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0])) { $segs=explode('/',$this->catchAllRequest[0]); $controllerID=$segs[0]; $actionID=isset($segs[1])?$segs[1]:''; foreach(array_splice($this->catchAllRequest,1) as $name=>$value) $_GET[$name]=$value; } else list($controllerID,$actionID)=$this->resolveRequest(); $this->runController($controllerID,$actionID); } protected function resolveRequest() { $route=$this->getUrlManager()->parseUrl($this->getRequest()); if(($pos=strrpos($route,'/'))!==false) return array(substr($route,0,$pos),(string)substr($route,$pos+1)); else return array($route,''); } public function runController($controllerID,$actionID) { if(($controller=$this->createController($controllerID))!==null) { $oldController=$this->_controller; $this->_controller=$controller; $controller->run($actionID); $this->_controller=$oldController; } else throw new CHttpException(404,Yii::t('yii#The requested controller "{controller}" does not exist.', array('{controller}'=>$controllerID))); } protected function registerCoreComponents() { parent::registerCoreComponents(); $components=array( 'urlManager'=>array( 'class'=>'CUrlManager', ), 'request'=>array( 'class'=>'CHttpRequest', ), 'session'=>array( 'class'=>'CHttpSession', ), 'assetManager'=>array( 'class'=>'CAssetManager', ), 'user'=>array( 'class'=>'CWebUser', ), 'themeManager'=>array( 'class'=>'CThemeManager', ), 'authManager'=>array( 'class'=>'CPhpAuthManager', ), ); $this->setComponents($components); } public function getRequest() { return $this->getComponent('request'); } public function getUrlManager() { return $this->getComponent('urlManager'); } public function getAuthManager() { return $this->getComponent('authManager'); } public function getAssetManager() { return $this->getComponent('assetManager'); } public function getSession() { return $this->getComponent('session'); } public function getUser() { return $this->getComponent('user'); } public function getViewRenderer() { return $this->getComponent('viewRenderer'); } public function getThemeManager() { return $this->getComponent('themeManager'); } public function getTheme() { if(is_string($this->_theme)) $this->_theme=$this->getThemeManager()->getTheme($this->_theme); return $this->_theme; } public function setTheme($value) { $this->_theme=$value; } public function createUrl($route,$params=array(),$ampersand='&') { return $this->getUrlManager()->createUrl($route,$params,$ampersand); } public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&') { return $this->getRequest()->getHostInfo($schema).$this->createUrl($route,$params,$ampersand); } public function getBaseUrl() { return $this->getRequest()->getBaseUrl(); } public function getHomeUrl() { if($this->_homeUrl===null) { if($this->getUrlManager()->showScriptName) return $this->getRequest()->getScriptUrl(); else return $this->getRequest()->getBaseUrl().'/'; } else return $this->_homeUrl; } public function setHomeUrl($value) { $this->_homeUrl=$value; } public function createController($id) { if($id==='') $id=$this->defaultController; if(preg_match('/^\w+$/',$id)) { if(isset($this->controllerMap[$id])) return CConfiguration::createObject($this->controllerMap[$id],$id); else return $this->createControllerIn($this->getControllerPath(),ucfirst($id).'Controller',$id); } } protected function createControllerIn($directory,$className,$id) { $filePath=$directory.DIRECTORY_SEPARATOR.$className.'.php'; if(is_file($filePath)) { require_once($filePath); if(class_exists($className,false) && is_subclass_of($className,'CController')) return new $className($id); } } public function getController() { return $this->_controller; } public function getControllerPath() { if($this->_controllerPath!==null) return $this->_controllerPath; else return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers'; } public function setControllerPath($value) { if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath)) throw new CException(Yii::t('yii#The controller path "{path}" is not a valid directory.', array('{path}'=>$value))); } public function getViewPath() { if($this->_viewPath!==null) return $this->_viewPath; else return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views'; } public function setViewPath($path) { if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath)) throw new CException(Yii::t('yii#The view path "{path}" is not a valid directory.', array('{path}'=>$path))); } public function getSystemViewPath() { if($this->_systemViewPath!==null) return $this->_systemViewPath; else return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system'; } public function setSystemViewPath($path) { if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath)) throw new CException(Yii::t('yii#The system view path "{path}" is not a valid directory.', array('{path}'=>$path))); } public function getLayoutPath() { if($this->_layoutPath!==null) return $this->_layoutPath; else return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts'; } public function setLayoutPath($path) { if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath)) throw new CException(Yii::t('yii#The layout path "{path}" is not a valid directory.', array('{path}'=>$path))); } } class CLogger extends CComponent { const LEVEL_TRACE='trace'; const LEVEL_WARNING='warning'; const LEVEL_ERROR='error'; const LEVEL_INFO='info'; const LEVEL_PROFILE='profile'; private $_logs=array(); private $_levels; private $_categories; public function log($message,$level='info',$category='application') { $this->_logs[]=array($message,$level,$category,microtime(true)); } public function getLogs($levels='',$categories='') { $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY); $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY); if(empty($levels) && empty($categories)) return $this->_logs; else if(empty($levels)) return array_values(array_filter(array_filter($this->_logs,array($this,'filterByCategory')))); else if(empty($categories)) return array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel')))); else { $ret=array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel')))); return array_values(array_filter(array_filter($ret,array($this,'filterByCategory')))); } } private function filterByCategory($value) { foreach($this->_categories as $category) { $cat=strtolower($value[2]); if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0)) return $value; } return false; } private function filterByLevel($value) { return in_array(strtolower($value[1]),$this->_levels)?$value:false; } public function getExecutionTime() { return microtime(true)-YII_BEGIN_TIME; } public function getMemoryUsage() { if(function_exists('memory_get_usage')) return memory_get_usage(); else { $output=array(); if(strncmp(PHP_OS,'WIN',3)===0) { exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output); return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0; } else { $pid=getmypid(); exec("ps -eo%mem,rss,pid | grep $pid", $output); $output=explode(" ",$output[0]); return isset($output[1]) ? $output[1]*1024 : 0; } } } } abstract class CApplicationComponent extends CComponent implements IApplicationComponent { private $_initialized=false; public function init() { $this->_initialized=true; } public function getIsInitialized() { return $this->_initialized; } } class CUrlManager extends CApplicationComponent { const CACHE_KEY='CPhpMessageSource.CUrlManager.rules'; const GET_FORMAT='get'; const PATH_FORMAT='path'; public $urlSuffix=''; public $showScriptName=true; public $routeVar='r'; private $_urlFormat=self::GET_FORMAT; private $_rules=array(); private $_groups=array(); private $_baseUrl; public function init() { parent::init(); $this->processRules(); } protected function processRules() { if(empty($this->_rules) || $this->getUrlFormat()===self::GET_FORMAT) return; if(($cache=Yii::app()->getCache())!==null) { $hash=md5(serialize($this->_rules)); if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash) { $this->_groups=$data[0]; return; } } foreach($this->_rules as $pattern=>$route) $this->_groups[$route][]=new CUrlRule($route,$pattern); if($cache!==null) $cache->set(self::CACHE_KEY,array($this->_groups,$hash)); } public function getRules() { return $this->_rules; } public function setRules($value) { if($this->_rules===array()) $this->_rules=$value; else $this->_rules=array_merge($this->_rules,$value); } public function createUrl($route,$params=array(),$ampersand='&') { unset($params[$this->routeVar]); if(isset($this->_groups[$route])) { foreach($this->_groups[$route] as $rule) { if(($url=$rule->createUrl($params,$this->urlSuffix,$ampersand))!==false) return $this->getBaseUrl().'/'.$url; } } return $this->createUrlDefault($route,$params,$ampersand); } protected function createUrlDefault($route,$params,$ampersand) { if($this->getUrlFormat()===self::PATH_FORMAT) { $url=rtrim($this->getBaseUrl().'/'.$route,'/'); foreach($params as $key=>$value) $url.='/'.urlencode($key).'/'.urlencode($value); return $url.$this->urlSuffix; } else { $pairs=$route!==''?array($this->routeVar.'='.$route):array(); foreach($params as $key=>$value) $pairs[]=urlencode($key).'='.urlencode($value); $baseUrl=$this->getBaseUrl(); if(!$this->showScriptName) $baseUrl.='/'; if(($query=implode($ampersand,$pairs))!=='') return $baseUrl.'?'.$query; else return $baseUrl; } } public function parseUrl($request) { if($this->getUrlFormat()===self::PATH_FORMAT) { $pathInfo=$this->removeUrlSuffix($request->getPathInfo()); foreach($this->_groups as $rules) { foreach($rules as $rule) { if(($r=$rule->parseUrl($pathInfo))!==false) return isset($_GET[$this->routeVar])?$_GET[$this->routeVar]:$r; } } return $this->parseUrlDefault($pathInfo); } else if(isset($_GET[$this->routeVar])) return $_GET[$this->routeVar]; else return isset($_POST[$this->routeVar])?$_POST[$this->routeVar]:''; } protected function removeUrlSuffix($pathInfo) { if(($ext=$this->urlSuffix)!=='' && substr($pathInfo,-strlen($ext))===$ext) return substr($pathInfo,0,-strlen($ext)); else return $pathInfo; } protected function parseUrlDefault($pathInfo) { $segs=explode('/',$pathInfo.'/'); $n=count($segs); for($i=2;$i<$n-1;$i+=2) $_GET[$segs[$i]]=$segs[$i+1]; return $segs[0].'/'.$segs[1]; } public function getBaseUrl() { if($this->_baseUrl!==null) return $this->_baseUrl; else { if($this->showScriptName) $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl(); else $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl(); return $this->_baseUrl; } } public function getUrlFormat() { return $this->_urlFormat; } public function setUrlFormat($value) { if($value===self::PATH_FORMAT || $value===self::GET_FORMAT) $this->_urlFormat=$value; else throw new CException(Yii::t('yii#CUrlManager.UrlFormat must be either "path" or "get".')); } } class CUrlRule extends CComponent { public $route; public $pattern; public $template; public $params; public $append; public $signature; public function __construct($route,$pattern) { $this->route=$route; if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches)) $this->params=array_combine($matches[1],$matches[2]); else $this->params=array(); $p=rtrim($pattern,'*'); $this->append=$p!==$pattern; $p=trim($p,'/'); $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p); if(($pos=strpos($p,'<'))!==false) $this->signature=substr($p,0,$pos); else $this->signature=$p; $tr['/']='\\/'; foreach($this->params as $key=>$value) $tr["<$key>"]="(?P<$key>".($value!==''?$value:'[^\/]+').')'; $this->pattern='/^'.strtr($this->template,$tr).'\/'; if($this->append) $this->pattern.='/u'; else $this->pattern.='$/u'; if(@preg_match($this->pattern,'test')===false) throw new CException(Yii::t('yii#The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.', array('{route}'=>$route,'{pattern}'=>$pattern))); } public function createUrl($params,$suffix,$ampersand) { foreach($this->params as $key=>$value) { if(!isset($params[$key])) return false; } $tr=array(); $rest=array(); $sep=$this->append?'/':'='; foreach($params as $key=>$value) { if(isset($this->params[$key])) $tr["<$key>"]=$value; else $rest[]=urlencode($key).$sep.urlencode($value); } $url=strtr($this->template,$tr); if($rest===array()) return $url!=='' ? $url.$suffix : $url; else { if($this->append) { $url.='/'.implode('/',$rest); if($url!=='') $url.=$suffix; } else { if($url!=='') $url.=$suffix; $url.='?'.implode($ampersand,$rest); } return $url; } } public function parseUrl($pathInfo) { if(strncmp($pathInfo,$this->signature,strlen($this->signature))) return false; $pathInfo.='/'; if(preg_match($this->pattern,$pathInfo,$matches)) { foreach($matches as $key=>$value) { if(is_string($key)) $_GET[$key]=$value; } if($pathInfo!==$matches[0]) { $segs=explode('/',ltrim(substr($pathInfo,strlen($matches[0])),'/')); $n=count($segs); for($i=0;$i<$n-1;$i+=2) $_GET[$segs[$i]]=$segs[$i+1]; } return $this->route; } else return false; } } class CHttpRequest extends CApplicationComponent { public $enableCookieValidation=false; private $_pathInfo; private $_scriptFile; private $_scriptUrl; private $_hostInfo; private $_url; private $_baseUrl; private $_cookies; private $_preferredLanguage; public function init() { parent::init(); $this->normalizeRequest(); } protected function normalizeRequest() { // normalize request if(get_magic_quotes_gpc()) { if(isset($_GET)) $_GET=$this->stripSlashes($_GET); if(isset($_POST)) $_POST=$this->stripSlashes($_POST); if(isset($_REQUEST)) $_REQUEST=$this->stripSlashes($_REQUEST); if(isset($_COOKIE)) $_COOKIE=$this->stripSlashes($_COOKIE); } } public function stripSlashes(&$data) { return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data); } public function getUrl() { if($this->_url!==null) return $this->_url; else { if(isset($_SERVER['REQUEST_URI'])) $this->_url=$_SERVER['REQUEST_URI']; else { $this->_url=$this->getScriptUrl(); if(($pathInfo=$this->getPathInfo())!=='') $this->_url.='/'.$pathInfo; if(($queryString=$this->getQueryString())!=='') $this->_url.='?'.$queryString; } return $this->_url; } } public function getHostInfo($schema='') { if($this->_hostInfo===null) { if($secure=$this->getIsSecureConnection()) $schema='https'; else $schema='http'; $segs=explode(':',$_SERVER['HTTP_HOST']); $url=$schema.'://'.$segs[0]; $port=$_SERVER['SERVER_PORT']; if(($port!=80 && !$secure) || ($port!=443 && $secure)) $url.=':'.$port; $this->_hostInfo=$url; } if($schema!=='' && ($pos=strpos($this->_hostInfo,':'))!==false) return $schema.substr($this->_hostInfo,$pos); else return $this->_hostInfo; } public function setHostInfo($value) { $this->_hostInfo=rtrim($value,'/'); } public function getBaseUrl() { if($this->_baseUrl===null) $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/'); return $this->_baseUrl; } public function setBaseUrl($value) { $this->_baseUrl=$value; } public function getScriptUrl() { if($this->_scriptUrl!==null) return $this->_scriptUrl; else { if(isset($_SERVER['SCRIPT_NAME'])) $this->_scriptUrl=$_SERVER['SCRIPT_NAME']; else throw new CException(Yii::t('yii#CHttpRequest is unable to determine the entry script URL.')); return $this->_scriptUrl; } } public function setScriptUrl($value) { $this->_scriptUrl='/'.trim($value,'/'); } public function getPathInfo() { if($this->_pathInfo===null) $this->_pathInfo=trim(isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : $this->guessPathInfo(), '/'); return $this->_pathInfo; } protected function guessPathInfo() { if($_SERVER['PHP_SELF']!==$_SERVER['SCRIPT_NAME']) { if(strpos($_SERVER['PHP_SELF'],$_SERVER['SCRIPT_NAME'])===0) return substr($_SERVER['PHP_SELF'],strlen($_SERVER['SCRIPT_NAME'])); } else if(isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'],$_SERVER['SCRIPT_NAME'])!==0) { // REQUEST_URI doesn't contain SCRIPT_NAME, which means some rewrite rule is in effect $base=strtr(dirname($_SERVER['SCRIPT_NAME']),'\\','/'); if(strpos($_SERVER['REQUEST_URI'],$base)===0) { $pathInfo=substr($_SERVER['REQUEST_URI'],strlen($base)); if(($pos=strpos($pathInfo,'?'))!==false) return substr($pathInfo,0,$pos); else return $pathInfo; } } return ''; } public function getQueryString() { return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:''; } public function getIsSecureConnection() { return isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'],'on'); } public function getRequestType() { return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET'); } public function getIsPostRequest() { return !strcasecmp($_SERVER['REQUEST_METHOD'],'POST'); } public function getIsAjaxRequest() { return isset($_SERVER['HTTP_X_REQUESTED_WITH'])?$_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest' : false; } public function getServerName() { return $_SERVER['SERVER_NAME']; } public function getServerPort() { return $_SERVER['SERVER_PORT']; } public function getUrlReferrer() { return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null; } public function getUserAgent() { return $_SERVER['HTTP_USER_AGENT']; } public function getUserHostAddress() { return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1'; } public function getUserHost() { return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null; } public function getScriptFile() { if($this->_scriptFile!==null) return $this->_scriptFile; else return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']); } public function getBrowser() { return get_browser(); } public function getAcceptTypes() { return $_SERVER['HTTP_ACCEPT']; } public function getCookies() { if($this->_cookies!==null) return $this->_cookies; else return $this->_cookies=new CCookieCollection($this); } public function redirect($url,$terminate=true) { if(strpos($url,'/')===0) $url=$this->getHostInfo().$url; header('Location: '.$url); if($terminate) Yii::app()->end(); } public function getPreferredLanguage() { if($this->_preferredLanguage===null) { if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && ($n=preg_match_all('/([\w\-_]+)\s*(;\s*q\s*=\s*(\d*\.\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))>0) { $languages=array(); for($i=0;$i<$n;++$i) $languages[$matches[1][$i]]=empty($matches[3][$i]) ? 1.0 : floatval($matches[3][$i]); arsort($languages); foreach($languages as $language=>$pref) return $this->_preferredLanguage=CLocale::getCanonicalID($language); } return $this->_preferredLanguage=false; } return $this->_preferredLanguage; } public function sendFile($fileName,$content,$mimeType=null,$terminate=true) { static $defaultMimeTypes=array( 'css'=>'text/css', 'gif'=>'image/gif', 'jpg'=>'image/jpeg', 'jpeg'=>'image/jpeg', 'htm'=>'text/html', 'html'=>'text/html', 'js'=>'javascript/js', 'pdf'=>'application/pdf', 'xls'=>'application/vnd.ms-excel', ); if($mimeType===null) { $mimeType='text/plain'; if(function_exists('mime_content_type')) $mimeType=mime_content_type($fileName); else if(($ext=strrchr($fileName,'.'))!==false) { $ext=strtolower(substr($ext,1)); if(isset($defaultMimeTypes[$ext])) $mimeType=$defaultMimeTypes[$ext]; } } header('Pragma: public'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header("Content-type: $mimeType"); header('Content-Length: '.strlen($content)); header("Content-Disposition: attachment; filename=\"$fileName\""); header('Content-Transfer-Encoding: binary'); echo $content; if($terminate) Yii::app()->end(); } } class CCookieCollection extends CMap { private $_request; private $_initialized=false; public function __construct(CHttpRequest $request) { $this->_request=$request; $this->copyfrom($this->getCookies()); $this->_initialized=true; } public function getRequest() { return $this->_request; } protected function getCookies() { $cookies=array(); if($this->_request->enableCookieValidation) { $sm=Yii::app()->getSecurityManager(); foreach($_COOKIE as $name=>$value) { if(($value=$sm->validateData($value))!==false) $cookies[$name]=new CHttpCookie($name,$value); } } else { foreach($_COOKIE as $name=>$value) $cookies[$name]=new CHttpCookie($name,$value); } return $cookies; } public function add($name,$cookie) { if($cookie instanceof CHttpCookie) { $this->remove($name); parent::add($name,$cookie); if($this->_initialized) $this->addCookie($cookie); } else throw new CException(Yii::t('yii#CHttpCookieCollection can only hold CHttpCookie objects.')); } public function remove($name) { if(($cookie=parent::remove($name))!==null) { if($this->_initialized) $this->removeCookie($cookie); } return $cookie; } protected function addCookie($cookie) { $value=$cookie->value; if($this->_request->enableCookieValidation) $value=Yii::app()->getSecurityManager()->hashData($value); setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure); } protected function removeCookie($cookie) { setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure); } } abstract class CBaseController extends CComponent { private $_widgetStack=array(); abstract public function getViewFile($viewName); public function renderFile($viewFile,$data=null,$return=false) { $widgetCount=count($this->_widgetStack); if(($renderer=Yii::app()->getViewRenderer())!==null) $content=$renderer->renderFile($this,$viewFile,$data,$return); else $content=$this->renderInternal($viewFile,$data,$return); if(count($this->_widgetStack)===$widgetCount) return $content; else { $widget=end($this->_widgetStack); throw new CException(Yii::t('yii#{controller} contains improperly nested widget tags in its view "{view}". A {widget} widget does not have an endWidget() call.', array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget)))); } } public function renderInternal($_viewFile_,$_data_=null,$_return_=false) { // we use special variable names here to avoid conflict when extracting data if(is_array($_data_)) extract($_data_,EXTR_PREFIX_SAME,'data'); else $data=$_data_; if($_return_) { ob_start(); ob_implicit_flush(false); require($_viewFile_); return ob_get_clean(); } else require($_viewFile_); } public function createWidget($className,$properties=array()) { $className=Yii::import($className,true); $widget=new $className($this); foreach($properties as $name=>$value) $widget->$name=$value; $widget->init(); return $widget; } public function widget($className,$properties=array()) { $widget=$this->createWidget($className,$properties); $widget->run(); } public function beginWidget($className,$properties=array()) { $widget=$this->createWidget($className,$properties); $this->_widgetStack[]=$widget; return $widget; } public function endWidget($id='') { if(($widget=array_pop($this->_widgetStack))!==null) { $widget->run(); return $widget; } else throw new CException(Yii::t('yii#{controller} has an extra endWidget({id}) call in its view.', array('{controller}'=>get_class($this),'{id}'=>$id))); } public function beginClip($id,$properties=array()) { $properties['id']=$id; $this->beginWidget('CClipWidget',$properties); } public function endClip() { $this->endWidget('CClipWidget'); } public function beginCache($id,$properties=array()) { $properties['id']=$id; $cache=$this->beginWidget('COutputCache',$properties); if($cache->getIsContentCached()) { $this->endCache(); return false; } else return true; } public function endCache() { $this->endWidget('COutputCache'); } public function beginContent($view,$properties=array()) { $properties['view']=$view; $this->beginWidget('CContentDecorator',$properties); } public function endContent() { $this->endWidget('CContentDecorator'); } } class CController extends CBaseController { public $layout; public $defaultAction='index'; private $_id; private $_action; private $_pageTitle; private $_clientScript; private $_cachingStack; private $_clips; private $_dynamicOutput; public function __construct($id) { $this->_id=$id; } public function filters() { return array(); } public function actions() { return array(); } public function accessRules() { return array(); } public function run($actionID) { if(($action=$this->createAction($actionID))!==null) $this->runActionWithFilters($action,$this->filters()); else $this->missingAction($actionID); } public function runActionWithFilters($action,$filters=array()) { if(!empty($filters)) { $priorAction=$this->_action; $this->_action=$action; CFilterChain::create($this,$action,$filters)->run(); $this->_action=$priorAction; } else $this->runAction($action); } public function runAction($action) { $priorAction=$this->_action; $this->_action=$action; if($this->beforeAction($action)) { $action->run(); $this->afterAction($action); } $this->_action=$priorAction; } protected function processOutput($output) { if($this->_clientScript) { $output=$this->_clientScript->render($output); $this->_clientScript=null; } if($this->_dynamicOutput) { $output=preg_replace_callback('/<###tmp(\d+)###>/',array($this,'replaceDynamicOutput'),$output); $this->_dynamicOutput=null; } return $output; } protected function replaceDynamicOutput($matches) { return isset($this->_dynamicOutput[$matches[1]]) ? $this->_dynamicOutput[$matches[1]] : $matches[0]; } public function createAction($actionID) { if($actionID==='') $actionID=$this->defaultAction; if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method return new CInlineAction($this,$actionID); $actionMap=$this->actions(); if(isset($actionMap[$actionID])) { $c=$actionMap[$actionID]; if(is_string($c)) { $className=Yii::import($c,true); return new $className($this,$actionID); } else return CConfiguration::createObject($c,$this,$actionID); } return null; } public function missingAction($actionID) { throw new CHttpException(404,Yii::t('yii#The system is unable to find the requested action "{action}".', array('{action}'=>$actionID==''?$this->defaultAction:$actionID))); } public function getAction() { return $this->_action; } public function setAction($value) { $this->_action=$value; } public function getId() { return $this->_id; } public function getViewPath() { return Yii::app()->getViewPath().DIRECTORY_SEPARATOR.$this->getId(); } public function getViewFile($viewName) { if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false) return $viewFile; if($viewName[0]==='/') $viewFile=Yii::app()->getViewPath().$viewName.'.php'; else $viewFile=$this->getViewPath().DIRECTORY_SEPARATOR.$viewName.'.php'; return is_file($viewFile) ? Yii::app()->findLocalizedFile($viewFile) : false; } public function getLayoutFile($layoutName) { if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false) return $layoutFile; if($layoutName[0]==='/') $layoutFile=Yii::app()->getViewPath().$layoutName.'.php'; else $layoutFile=Yii::app()->getLayoutPath().DIRECTORY_SEPARATOR.$layoutName.'.php'; return is_file($layoutFile) ? Yii::app()->findLocalizedFile($layoutFile) : false; } public function getClips() { if($this->_clips!==null) return $this->_clips; else return $this->_clips=new CMap; } public function render($view,$data=null,$return=false) { if(($layout=$this->layout)==null) $layout=Yii::app()->layout; $output=$this->renderPartial($view,$data,true); if(!empty($layout) && ($layoutFile=$this->getLayoutFile($layout))!==false) $output=$this->renderFile($layoutFile,array('content'=>$output),true); $output=$this->processOutput($output); if($return) return $output; else echo $output; } public function renderText($text,$return=false) { if(($layout=$this->layout)==null) $layout=Yii::app()->layout; if(!empty($layout) && ($layoutFile=$this->getLayoutFile($layout))!==false) $output=$this->renderFile($layoutFile,array('content'=>$text),true); $output=$this->processOutput($output); if($return) return $output; else echo $output; } public function renderPartial($view,$data=null,$return=false) { if(($viewFile=$this->getViewFile($view))!==false) return $this->renderFile($viewFile,$data,$return); else throw new CException(Yii::t('yii#{controller} cannot find the requested view "{view}".', array('{controller}'=>get_class($this), '{view}'=>$view))); } public function renderDynamic($callback) { $n=count($this->_dynamicOutput); echo "<###tmp$n###>"; $params=func_get_args(); array_shift($params); $this->renderDynamicInternal($callback,$params); } public function renderDynamicInternal($callback,$params) { if(is_string($callback) && method_exists($this,$callback)) $callback=array($this,$callback); $this->_dynamicOutput[]=call_user_func_array($callback,$params); $this->recordCachingAction('','renderDynamicInternal',array($callback,$params)); } public function getClientScript() { if($this->_clientScript) return $this->_clientScript; else return $this->_clientScript=new CClientScript($this); } public function createUrl($route,$params=array(),$ampersand='&') { if(strpos($route,'/')===false) $route=$this->getId().'/'.($route==='' ? $this->getAction()->getId() : $route); return Yii::app()->createUrl($route,$params,$ampersand); } public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&') { return Yii::app()->getRequest()->getHostInfo($schema).$this->createUrl($route,$params,$ampersand); } public function getPageTitle() { if($this->_pageTitle!==null) return $this->_pageTitle; else { if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction)) return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.ucfirst($this->getId()); else return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getId()); } } public function setPageTitle($value) { $this->_pageTitle=$value; } public function redirect($url,$terminate=true) { if(is_array($url)) { $route=isset($url[0]) ? $url[0] : ''; $url=$this->createUrl($route,array_splice($url,1)); } Yii::app()->getRequest()->redirect($url,$terminate); } public function refresh($terminate=true) { $this->redirect(Yii::app()->getRequest()->getUrl(),$terminate); } public function recordCachingAction($context,$method,$params) { if($this->_cachingStack) // record only when there is an active output cache { foreach($this->_cachingStack as $cache) $cache->recordAction($context,$method,$params); } } public function getCachingStack() { if(!$this->_cachingStack) $this->_cachingStack=new CStack; return $this->_cachingStack; } protected function beforeAction($action) { return true; } protected function afterAction($action) { } public function filterPostOnly($filterChain) { if(Yii::app()->getRequest()->getIsPostRequest()) $filterChain->run(); else throw new CHttpException(400,Yii::t('yii#Your request is not valid.')); } public function filterAjaxOnly($filterChain) { if(Yii::app()->getRequest()->getIsAjaxRequest()) $filterChain->run(); else throw new CHttpException(400,Yii::t('yii#Your request is not valid.')); } public function filterAccessControl($filterChain) { $filter=new CAccessControlFilter; $filter->setRules($this->accessRules()); $filter->filter($filterChain); } protected function paginate($itemCount,$pageSize=null,$pageVar=null) { $pages=new CPagination; $pages->setItemCount($itemCount); if($pageSize!==null) $pages->pageSize=$pageSize; if($pageVar!==null) $pages->pageVar=$pageVar; return $pages; } } abstract class CAction extends CComponent implements IAction { private $_id; private $_controller; public function __construct($controller,$id) { $this->_controller=$controller; $this->_id=$id; } public function getController() { return $this->_controller; } public function getId() { return $this->_id; } } class CInlineAction extends CAction { public function run() { $method='action'.$this->getId(); $this->getController()->$method(); } } class CWebUser extends CApplicationComponent implements IWebUser { const FLASH_KEY_PREFIX='Yii.CWebUser.flash.'; const FLASH_COUNTERS='Yii.CWebUser.flash.counters'; public $allowAutoLogin=false; public $guestName='Guest'; public $loginUrl=array('site/login'); private $_keyPrefix; public function init() { parent::init(); Yii::app()->getSession()->open(); if($this->getIsGuest() && $this->allowAutoLogin) $this->restoreFromCookie(); $this->updateFlash(); } public function login($identity,$duration=0) { $this->changeIdentity($identity->getId(),$identity->getName(),$identity->getPersistentStates()); if($duration>0) { if($this->allowAutoLogin) $this->saveToCookie($duration); else throw new CException(Yii::t('yii#{class}.allowAutoLogin must be set true in order to use cookie-based authentication.', array('{class}'=>get_class($this)))); } } public function logout() { if($this->allowAutoLogin) Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix()); $this->clearStates(); } public function getIsGuest() { return $this->getState('_id')===null; } public function getId() { return $this->getState('_id'); } public function setId($value) { $this->setState('_id',$value); } public function getName() { if(($name=$this->getState('_name'))!==null) return $name; else return $this->guestName; } public function setName($value) { $this->setState('_name',$value); } public function getReturnUrl() { return $this->getState('_returnUrl',Yii::app()->getRequest()->getScriptUrl()); } public function setReturnUrl($value) { $this->setState('_returnUrl',$value); } public function loginRequired() { $app=Yii::app(); $request=$app->getRequest(); $this->setReturnUrl($request->getUrl()); if(($url=$this->loginUrl)!==null) { if(is_array($url)) { $route=isset($url[0]) ? $url[0] : $app->defaultController; $url=$app->createUrl($route,array_splice($url,1)); } $request->redirect($url); } else throw new CHttpException(401,Yii::t('yii#Login Required')); } protected function restoreFromCookie() { $app=Yii::app(); $cookie=$app->getRequest()->getCookies()->itemAt($this->getStateKeyPrefix()); if($cookie && !empty($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false) { $data=unserialize($data); if(isset($data[0],$data[1],$data[2],$data[3])) { list($id,$name,$address,$states)=$data; if($address===$app->getRequest()->getUserHostAddress()) $this->changeIdentity($id,$name,$states); } } } protected function saveToCookie($duration) { $app=Yii::app(); $cookie=new CHttpCookie($this->getStateKeyPrefix(),''); $cookie->expire=time()+$duration; $data=array( $this->getId(), $this->getName(), $app->getRequest()->getUserHostAddress(), $this->saveIdentityStates(), ); $cookie->value=$app->getSecurityManager()->hashData(serialize($data)); $app->getRequest()->getCookies()->add($cookie->name,$cookie); } public function onRestoreFromCookie($event) { $this->raiseEvent('onRestoreFromCookie',$event); } protected function getStateKeyPrefix() { if($this->_keyPrefix!==null) return $this->_keyPrefix; else return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId()); } public function getState($key,$defaultValue=null) { $key=$this->getStateKeyPrefix().$key; return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue; } public function setState($key,$value,$defaultValue=null) { $key=$this->getStateKeyPrefix().$key; if($value===$defaultValue) unset($_SESSION[$key]); else $_SESSION[$key]=$value; } public function clearStates() { Yii::app()->getSession()->destroy(); } public function getFlash($key,$defaultValue=null) { return $this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue); } public function setFlash($key,$value,$defaultValue=null) { $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue); $counters=$this->getState(self::FLASH_COUNTERS,array()); if($value===$defaultValue) unset($counters[$key]); else $counters[$key]=0; $this->setState(self::FLASH_COUNTERS,$counters,array()); } public function hasFlash($key) { return $this->getFlash($key)!==null; } protected function changeIdentity($id,$name,$states) { $this->setId($id); $this->setName($name); $this->loadIdentityStates($states); } protected function saveIdentityStates() { $states=array(); foreach($this->getState('_states',array()) as $name) $states[$name]=$this->getState($name); return $states; } protected function loadIdentityStates($states) { if(is_array($states)) { foreach($states as $name=>$value) $this->setState($name,$value); $this->setState('_states',array_keys($states)); } else $this->setState('_states',array()); } protected function updateFlash() { $counters=$this->getState(self::FLASH_COUNTERS); if(!is_array($counters)) return; foreach($counters as $key=>$count) { if($count) { unset($counters[$key]); $this->setState(self::FLASH_KEY_PREFIX.$key,null); } else $counters[$key]++; } $this->setState(self::FLASH_COUNTERS,$counters,array()); } public function checkAccess($operation,$params=array()) { return Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params); } } class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable { public $autoStart=true; public $useCustomStorage=false; public function init() { parent::init(); if($this->autoStart) $this->open(); register_shutdown_function(array($this,'close')); } public function open() { if(session_id()==='') { if($this->useCustomStorage) session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession')); session_start(); } } public function close() { if(session_id()!=='') @session_write_close(); } public function destroy() { if(session_id()!=='') { @session_unset(); @session_destroy(); } } public function getIsStarted() { return session_id()!==''; } public function getSessionID() { return session_id(); } public function setSessionID($value) { session_id($value); } public function getSessionName() { return session_name(); } public function setSessionName($value) { session_name($value); } public function getSavePath() { return session_save_path(); } public function setSavePath($value) { if(is_dir($value)) session_save_path($value); else throw new CException(Yii::t('yii#CHttpSession.savePath "{path}" is not a valid directory.', array('{path}'=>$value))); } public function getCookieParams() { return session_get_cookie_params(); } public function setCookieParams($value) { $data=session_get_cookie_params(); extract($data); extract($value); session_set_cookie_params($lifetime,$path,$domain,$secure); } public function getCookieMode() { if(ini_get('session.use_cookies')==='0') return 'none'; else if(ini_get('session.use_only_cookies')==='0') return 'allow'; else return 'only'; } public function setCookieMode($value) { if($value==='none') ini_set('session.use_cookies','0'); else if($value==='allow') { ini_set('session.use_cookies','1'); ini_set('session.use_only_cookies','0'); } else if($value==='only') { ini_set('session.use_cookies','1'); ini_set('session.use_only_cookies','1'); } else throw new CException(Yii::t('yii#CHttpSession.cookieMode can only be "none", "allow" or "only".')); } public function getGCProbability() { return (int)ini_get('session.gc_probability'); } public function setGCProbability($value) { $value=(int)$value; if($value>=0 && $value<=100) { ini_set('session.gc_probability',$value); ini_set('session.gc_divisor','100'); } else throw new CException(Yii::t('yii#CHttpSession.gcProbability "{value}" is invalid. It must be an integer between 0 and 100.', array('{value}'=>$value))); } public function getUseTransparentSessionID() { return ini_get('session.use_trans_sid')==1; } public function setUseTransparentSessionID($value) { ini_set('session.use_trans_sid',$value?'1':'0'); } public function getTimeout() { return (int)ini_get('session.gc_maxlifetime'); } public function setTimeout($value) { ini_set('session.gc_maxlifetime',$value); } public function openSession($savePath,$sessionName) { return true; } public function closeSession() { return true; } public function readSession($id) { return ''; } public function writeSession($id,$data) { return true; } public function destroySession($id) { return true; } public function gcSession($maxLifetime) { return true; } //------ The following methods enable CHttpSession to be CMap-like ----- public function getIterator() { return new CHttpSessionIterator; } public function getCount() { return count($_SESSION); } public function count() { return $this->getCount(); } public function getKeys() { return array_keys($_SESSION); } public function itemAt($key) { return isset($_SESSION[$key]) ? $_SESSION[$key] : null; } public function add($key,$value) { $_SESSION[$key]=$value; } public function remove($key) { if(isset($_SESSION[$key])) { $value=$_SESSION[$key]; unset($_SESSION[$key]); return $value; } else return null; } public function clear() { foreach(array_keys($_SESSION) as $key) unset($_SESSION[$key]); } public function contains($key) { return isset($_SESSION[$key]); } public function toArray() { return $_SESSION; } public function offsetExists($offset) { return isset($_SESSION[$offset]); } public function offsetGet($offset) { return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null; } public function offsetSet($offset,$item) { $_SESSION[$offset]=$item; } public function offsetUnset($offset) { unset($_SESSION[$offset]); } } class CHttpSessionIterator implements Iterator { private $_keys; private $_key; public function __construct() { $this->_keys=array_keys($_SESSION); } public function rewind() { $this->_key=reset($this->_keys); } public function key() { return $this->_key; } public function current() { return isset($_SESSION[$this->_key])?$_SESSION[$this->_key]:null; } public function next() { do { $this->_key=next($this->_keys); } while(!isset($_SESSION[$this->_key]) && $this->_key!==false); } public function valid() { return $this->_key!==false; } } class CHtml { const ID_PREFIX='yt'; public static $errorSummaryCss='errorSummary'; public static $errorMessageCss='errorMessage'; public static $errorCss='error'; private static $_count=0; public static function encode($text) { return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset); } public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true) { $html='<' . $tag; foreach($htmlOptions as $name=>$value) $html .= ' ' . $name . '="' . self::encode($value) . '"'; if($content===false) return $closeTag ? $html.'/>' : $html.'>'; else return $closeTag ? $html.'>'.$content.''.$tag.'>' : $html.'>'.$content; } public static function cdata($text) { return ''; } public static function css($text,$media='') { if($media!=='') $media=' media="'.$media.'"'; return ""; } public static function cssFile($url,$media='') { if($media!=='') $media=' media="'.$media.'"'; return ''; } public static function script($text) { return ""; } public static function scriptFile($url) { return ''; } public static function form($action='',$method='post',$htmlOptions=array()) { $htmlOptions['action']=self::normalizeUrl($action); $htmlOptions['method']=$method; return self::tag('form',$htmlOptions,false,false); } public static function link($text,$url='#',$htmlOptions=array()) { $htmlOptions['href']=self::normalizeUrl($url); self::clientChange('click',$htmlOptions); return self::tag('a',$htmlOptions,$text); } public static function image($src,$alt='',$htmlOptions=array()) { $htmlOptions['src']=$src; $htmlOptions['alt']=$alt; return self::tag('img',$htmlOptions); } public static function button($label='button',$htmlOptions=array()) { if(!isset($htmlOptions['name'])) $htmlOptions['name']='button'; if(!isset($htmlOptions['type'])) $htmlOptions['type']='button'; if(!isset($htmlOptions['value'])) $htmlOptions['value']=$label; self::clientChange('click',$htmlOptions); return self::tag('input',$htmlOptions); } public static function submitButton($label='submit',$htmlOptions=array()) { $htmlOptions['type']='submit'; return self::button($label,$htmlOptions); } public static function resetButton($label='reset',$htmlOptions=array()) { $htmlOptions['type']='reset'; return self::button($label,$htmlOptions); } public static function imageButton($src,$htmlOptions=array()) { $htmlOptions['src']=$src; $htmlOptions['type']='image'; return self::button('submit',$htmlOptions); } public static function linkButton($label='submit',$htmlOptions=array()) { if(!isset($htmlOptions['submit'])) $htmlOptions['submit']=''; $url=isset($htmlOptions['href']) ? $htmlOptions['href'] : '#'; return self::link($label,$url,$htmlOptions); } public static function label($label,$for,$htmlOptions=array()) { $htmlOptions['for']=$for; return self::tag('label',$htmlOptions,$label); } public static function textField($name,$value='',$htmlOptions=array()) { self::clientChange('change',$htmlOptions); return self::inputField('text',$name,$value,$htmlOptions); } public static function hiddenField($name,$value='',$htmlOptions=array()) { return self::inputField('hidden',$name,$value,$htmlOptions); } public static function passwordField($name,$value='',$htmlOptions=array()) { self::clientChange('change',$htmlOptions); return self::inputField('password',$name,$value,$htmlOptions); } public static function fileField($name,$value='',$htmlOptions=array()) { return self::inputField('file',$name,$value,$htmlOptions); } public static function textArea($name,$value='',$htmlOptions=array()) { self::clientChange('change',$htmlOptions); if(is_object($name)) { $html=self::tag('textarea',$htmlOptions,self::encode($name->$value)); return $name->hasErrors($value) ? self::highlightField($html) : $html; } else return self::tag('textarea',$htmlOptions,self::encode($value)); } public static function radioButton($name,$checked=false,$htmlOptions=array()) { if(!isset($htmlOptions['value'])) $htmlOptions['value']=1; if($checked) $htmlOptions['checked']='checked'; self::clientChange('click',$htmlOptions); return self::inputField('radio',$name,$checked,$htmlOptions); } public static function checkBox($name,$checked=false,$htmlOptions=array()) { if(!isset($htmlOptions['value'])) $htmlOptions['value']=1; if($checked) $htmlOptions['checked']='checked'; self::clientChange('click',$htmlOptions); return self::inputField('checkbox',$name,$checked,$htmlOptions); } public static function dropDownList($name,$select,$data,$htmlOptions=array()) { $options="\n".self::listOptions($select,$data,$htmlOptions); self::clientChange('change',$htmlOptions); return self::tag('select',$htmlOptions,$options); } public static function listBox($name,$select,$data,$htmlOptions=array()) { if(!isset($htmlOptions['size'])) $htmlOptions['size']=4; return self::dropDownList($name,$select,$data,$htmlOptions); } public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array()) { if(!isset($htmlOptions['href'])) $htmlOptions['href']='#'; $ajaxOptions['url']=$url; $htmlOptions['ajax']=$ajaxOptions; self::clientChange('click',$htmlOptions); return self::tag('a',$htmlOptions,$text); } public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array()) { $ajaxOptions['url']=$url; $htmlOptions['ajax']=$ajaxOptions; return self::button($label,$htmlOptions); } public static function ajax($options) { self::getClientScript()->registerCoreScript('jquery'); if(!isset($options['url'])) $options['url']='js:location.href'; else $options['url']=self::normalizeUrl($options['url']); if(!isset($options['cache'])) $options['cache']=false; if(!isset($options['data']) && isset($options['type'])) $options['data']='js:jQuery(this).parents("form").serialize()'; foreach(array('beforeSend','complete','error','success') as $name) { if(isset($options[$name]) && strpos($options[$name],'js:')!==0) $options[$name]='js:'.$options[$name]; } if(isset($options['update'])) { if(!isset($options['success'])) $options['success']='js:function(html){jQuery("'.$options['update'].'").html(html)}'; unset($options['update']); } if(isset($options['replace'])) { if(!isset($options['success'])) $options['success']='js:function(html){jQuery("'.$options['replace'].'").replaceWith(html)}'; unset($options['replace']); } return 'jQuery.ajax('.CJavaScript::encode($options).');'; } public static function asset($path) { return Yii::app()->getAssetManager()->publish($path); } public static function coreScript($name) { return self::getClientScript()->renderCoreScript($name); } public static function normalizeUrl($url) { if(is_array($url)) $url=isset($url[0]) ? Yii::app()->getController()->createUrl($url[0],array_splice($url,1)) : ''; return $url==='' ? Yii::app()->getRequest()->getUrl() : $url; } protected static function inputField($type,$name,$value,$htmlOptions) { $htmlOptions['type']=$type; $htmlOptions['value']=$value; $htmlOptions['name']=$name; return self::tag('input',$htmlOptions); } public static function activeLabel($model,$attribute,$htmlOptions=array()) { if(($pos=strpos($attribute,'['))!==false) $name=get_class($model).substr($attribute,$pos).'['.($attribute=substr($attribute,0,$pos)).']'; else $name=get_class($model).'['.$attribute.']'; $label=CHtml::encode($model->getAttributeLabel($attribute)); $for=str_replace(array('[]', '][', '[', ']'), array('', '_', '_', ''), $name); if($model->hasErrors($attribute)) self::addErrorCss($htmlOptions); return self::label($label,$for,$htmlOptions); } public static function activeTextField($model,$attribute,$htmlOptions=array()) { self::resolveNameID($model,$attribute,$htmlOptions); self::clientChange('change',$htmlOptions); return self::activeInputField('text',$model,$attribute,$htmlOptions); } public static function activeHiddenField($model,$attribute,$htmlOptions=array()) { self::resolveNameID($model,$attribute,$htmlOptions); return self::activeInputField('hidden',$model,$attribute,$htmlOptions); } public static function activePasswordField($model,$attribute,$htmlOptions=array()) { self::resolveNameID($model,$attribute,$htmlOptions); self::clientChange('change',$htmlOptions); return self::activeInputField('password',$model,$attribute,$htmlOptions); } public static function activeTextArea($model,$attribute,$htmlOptions=array()) { self::resolveNameID($model,$attribute,$htmlOptions); self::clientChange('change',$htmlOptions); if($model->hasErrors($attribute)) self::addErrorCss($htmlOptions); return self::tag('textarea',$htmlOptions,self::encode($model->$attribute)); } public static function activeRadioButton($model,$attribute,$htmlOptions=array()) { if(!isset($htmlOptions['value'])) $htmlOptions['value']=1; if($model->$attribute) $htmlOptions['checked']='checked'; self::resolveNameID($model,$attribute,$htmlOptions); self::clientChange('click',$htmlOptions); return self::activeInputField('radio',$model,$attribute,$htmlOptions); } public static function activeCheckBox($model,$attribute,$htmlOptions=array()) { if(!isset($htmlOptions['value'])) $htmlOptions['value']=1; if($model->$attribute) $htmlOptions['checked']='checked'; self::resolveNameID($model,$attribute,$htmlOptions); self::clientChange('click',$htmlOptions); return self::activeInputField('checkbox',$model,$attribute,$htmlOptions); } public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array()) { $selection=$model->$attribute; $options="\n".self::listOptions($selection,$data,$htmlOptions); self::resolveNameID($model,$attribute,$htmlOptions); self::clientChange('change',$htmlOptions); if($model->hasErrors($attribute)) self::addErrorCss($htmlOptions); return self::tag('select',$htmlOptions,$options); } public static function activeListBox($model,$attribute,$data,$htmlOptions=array()) { if(!isset($htmlOptions['size'])) $htmlOptions['size']=4; return self::dropDownList($model,$attribute,$data,$htmlOptions); } public static function getActiveId($model,$attribute) { return get_class($model).'_'.$attribute; } public static function errorSummary($model,$header='',$footer='') { if($header==='') $header=''.Yii::t('yii#Please fix the following input errors:').'
'; $content=''; if(!is_array($model)) $model=array($model); foreach($model as $m) { foreach($m->getErrors() as $errors) { foreach($errors as $error) $content.="