PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/yiilite.php

https://bitbucket.org/dinhtrung/yiicorecms/
PHP | 2214 lines | 2171 code | 2 blank | 41 comment | 311 complexity | ee1a659813f3bd4cb4ecc6a5a44997d5 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, CC0-1.0, BSD-2-Clause, GPL-2.0, LGPL-2.1, LGPL-3.0
  1. <?php
  2. /**
  3. * Yii bootstrap file.
  4. *
  5. * This file is automatically generated using 'build lite' command.
  6. * It is the result of merging commonly used Yii class files with
  7. * comments and trace statements removed away.
  8. *
  9. * By using this file instead of yii.php, an Yii application may
  10. * improve performance due to the reduction of PHP parsing time.
  11. * The performance improvement is especially obvious when PHP APC extension
  12. * is enabled.
  13. *
  14. * DO NOT modify this file manually.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @link http://www.yiiframework.com/
  18. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  19. * @license http://www.yiiframework.com/license/
  20. * @version $Id: yiilite.php 3325 2011-06-26 18:01:42Z qiang.xue $
  21. * @since 1.0
  22. */
  23. defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME',microtime(true));
  24. defined('YII_DEBUG') or define('YII_DEBUG',false);
  25. defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',0);
  26. defined('YII_ENABLE_EXCEPTION_HANDLER') or define('YII_ENABLE_EXCEPTION_HANDLER',true);
  27. defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER',true);
  28. defined('YII_PATH') or define('YII_PATH',dirname(__FILE__));
  29. defined('YII_ZII_PATH') or define('YII_ZII_PATH',YII_PATH.DIRECTORY_SEPARATOR.'zii');
  30. class YiiBase
  31. {
  32. public static $classMap=array();
  33. public static $enableIncludePath=true;
  34. private static $_aliases=array('system'=>YII_PATH,'zii'=>YII_ZII_PATH); // alias => path
  35. private static $_imports=array(); // alias => class name or directory
  36. private static $_includePaths; // list of include paths
  37. private static $_app;
  38. private static $_logger;
  39. public static function getVersion()
  40. {
  41. return '1.1.9-dev';
  42. }
  43. public static function createWebApplication($config=null)
  44. {
  45. return self::createApplication('CWebApplication',$config);
  46. }
  47. public static function createConsoleApplication($config=null)
  48. {
  49. return self::createApplication('CConsoleApplication',$config);
  50. }
  51. public static function createApplication($class,$config=null)
  52. {
  53. return new $class($config);
  54. }
  55. public static function app()
  56. {
  57. return self::$_app;
  58. }
  59. public static function setApplication($app)
  60. {
  61. if(self::$_app===null || $app===null)
  62. self::$_app=$app;
  63. else
  64. throw new CException(Yii::t('yii','Yii application can only be created once.'));
  65. }
  66. public static function getFrameworkPath()
  67. {
  68. return YII_PATH;
  69. }
  70. public static function createComponent($config)
  71. {
  72. if(is_string($config))
  73. {
  74. $type=$config;
  75. $config=array();
  76. }
  77. else if(isset($config['class']))
  78. {
  79. $type=$config['class'];
  80. unset($config['class']);
  81. }
  82. else
  83. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  84. if(!class_exists($type,false))
  85. $type=Yii::import($type,true);
  86. if(($n=func_num_args())>1)
  87. {
  88. $args=func_get_args();
  89. if($n===2)
  90. $object=new $type($args[1]);
  91. else if($n===3)
  92. $object=new $type($args[1],$args[2]);
  93. else if($n===4)
  94. $object=new $type($args[1],$args[2],$args[3]);
  95. else
  96. {
  97. unset($args[0]);
  98. $class=new ReflectionClass($type);
  99. // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
  100. // $object=$class->newInstanceArgs($args);
  101. $object=call_user_func_array(array($class,'newInstance'),$args);
  102. }
  103. }
  104. else
  105. $object=new $type;
  106. foreach($config as $key=>$value)
  107. $object->$key=$value;
  108. return $object;
  109. }
  110. public static function import($alias,$forceInclude=false)
  111. {
  112. if(isset(self::$_imports[$alias])) // previously imported
  113. return self::$_imports[$alias];
  114. if(class_exists($alias,false) || interface_exists($alias,false))
  115. return self::$_imports[$alias]=$alias;
  116. if(($pos=strrpos($alias,'\\'))!==false) // a class name in PHP 5.3 namespace format
  117. {
  118. $namespace=str_replace('\\','.',ltrim(substr($alias,0,$pos),'\\'));
  119. if(($path=self::getPathOfAlias($namespace))!==false)
  120. {
  121. $classFile=$path.DIRECTORY_SEPARATOR.substr($alias,$pos+1).'.php';
  122. if($forceInclude)
  123. {
  124. if(is_file($classFile))
  125. require($classFile);
  126. else
  127. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file.',array('{alias}'=>$alias)));
  128. self::$_imports[$alias]=$alias;
  129. }
  130. else
  131. self::$classMap[$alias]=$classFile;
  132. return $alias;
  133. }
  134. else
  135. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory.',
  136. array('{alias}'=>$namespace)));
  137. }
  138. if(($pos=strrpos($alias,'.'))===false) // a simple class name
  139. {
  140. if($forceInclude && self::autoload($alias))
  141. self::$_imports[$alias]=$alias;
  142. return $alias;
  143. }
  144. $className=(string)substr($alias,$pos+1);
  145. $isClass=$className!=='*';
  146. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  147. return self::$_imports[$alias]=$className;
  148. if(($path=self::getPathOfAlias($alias))!==false)
  149. {
  150. if($isClass)
  151. {
  152. if($forceInclude)
  153. {
  154. if(is_file($path.'.php'))
  155. require($path.'.php');
  156. else
  157. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file.',array('{alias}'=>$alias)));
  158. self::$_imports[$alias]=$className;
  159. }
  160. else
  161. self::$classMap[$className]=$path.'.php';
  162. return $className;
  163. }
  164. else // a directory
  165. {
  166. if(self::$_includePaths===null)
  167. {
  168. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  169. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  170. unset(self::$_includePaths[$pos]);
  171. }
  172. array_unshift(self::$_includePaths,$path);
  173. if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  174. self::$enableIncludePath=false;
  175. return self::$_imports[$alias]=$path;
  176. }
  177. }
  178. else
  179. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  180. array('{alias}'=>$alias)));
  181. }
  182. public static function getPathOfAlias($alias)
  183. {
  184. if(isset(self::$_aliases[$alias]))
  185. return self::$_aliases[$alias];
  186. else if(($pos=strpos($alias,'.'))!==false)
  187. {
  188. $rootAlias=substr($alias,0,$pos);
  189. if(isset(self::$_aliases[$rootAlias]))
  190. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  191. else if(self::$_app instanceof CWebApplication)
  192. {
  193. if(self::$_app->findModule($rootAlias)!==null)
  194. return self::getPathOfAlias($alias);
  195. }
  196. }
  197. return false;
  198. }
  199. public static function setPathOfAlias($alias,$path)
  200. {
  201. if(empty($path))
  202. unset(self::$_aliases[$alias]);
  203. else
  204. self::$_aliases[$alias]=rtrim($path,'\\/');
  205. }
  206. public static function autoload($className)
  207. {
  208. // use include so that the error PHP file may appear
  209. if(isset(self::$_coreClasses[$className]))
  210. include(YII_PATH.self::$_coreClasses[$className]);
  211. else if(isset(self::$classMap[$className]))
  212. include(self::$classMap[$className]);
  213. else
  214. {
  215. // include class file relying on include_path
  216. if(strpos($className,'\\')===false) // class without namespace
  217. {
  218. if(self::$enableIncludePath===false)
  219. {
  220. foreach(self::$_includePaths as $path)
  221. {
  222. $classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
  223. if(is_file($classFile))
  224. {
  225. include($classFile);
  226. break;
  227. }
  228. }
  229. }
  230. else
  231. include($className.'.php');
  232. }
  233. else // class name with namespace in PHP 5.3
  234. {
  235. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  236. if(($path=self::getPathOfAlias($namespace))!==false)
  237. include($path.'.php');
  238. else
  239. return false;
  240. }
  241. return class_exists($className,false) || interface_exists($className,false);
  242. }
  243. return true;
  244. }
  245. public static function trace($msg,$category='application')
  246. {
  247. if(YII_DEBUG)
  248. self::log($msg,CLogger::LEVEL_TRACE,$category);
  249. }
  250. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  251. {
  252. if(self::$_logger===null)
  253. self::$_logger=new CLogger;
  254. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  255. {
  256. $traces=debug_backtrace();
  257. $count=0;
  258. foreach($traces as $trace)
  259. {
  260. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  261. {
  262. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  263. if(++$count>=YII_TRACE_LEVEL)
  264. break;
  265. }
  266. }
  267. }
  268. self::$_logger->log($msg,$level,$category);
  269. }
  270. public static function beginProfile($token,$category='application')
  271. {
  272. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  273. }
  274. public static function endProfile($token,$category='application')
  275. {
  276. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  277. }
  278. public static function getLogger()
  279. {
  280. if(self::$_logger!==null)
  281. return self::$_logger;
  282. else
  283. return self::$_logger=new CLogger;
  284. }
  285. public static function setLogger($logger)
  286. {
  287. self::$_logger=$logger;
  288. }
  289. public static function powered()
  290. {
  291. return 'Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>.';
  292. }
  293. public static function t($category,$message,$params=array(),$source=null,$language=null)
  294. {
  295. if(self::$_app!==null)
  296. {
  297. if($source===null)
  298. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  299. if(($source=self::$_app->getComponent($source))!==null)
  300. $message=$source->translate($category,$message,$language);
  301. }
  302. if($params===array())
  303. return $message;
  304. if(!is_array($params))
  305. $params=array($params);
  306. if(isset($params[0])) // number choice
  307. {
  308. if(strpos($message,'|')!==false)
  309. {
  310. if(strpos($message,'#')===false)
  311. {
  312. $chunks=explode('|',$message);
  313. $expressions=self::$_app->getLocale($language)->getPluralRules();
  314. if($n=min(count($chunks),count($expressions)))
  315. {
  316. for($i=0;$i<$n;$i++)
  317. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  318. $message=implode('|',$chunks);
  319. }
  320. }
  321. $message=CChoiceFormat::format($message,$params[0]);
  322. }
  323. if(!isset($params['{n}']))
  324. $params['{n}']=$params[0];
  325. unset($params[0]);
  326. }
  327. return $params!==array() ? strtr($message,$params) : $message;
  328. }
  329. public static function registerAutoloader($callback, $append=false)
  330. {
  331. if($append)
  332. {
  333. self::$enableIncludePath=false;
  334. spl_autoload_register($callback);
  335. }
  336. else
  337. {
  338. spl_autoload_unregister(array('YiiBase','autoload'));
  339. spl_autoload_register($callback);
  340. spl_autoload_register(array('YiiBase','autoload'));
  341. }
  342. }
  343. private static $_coreClasses=array(
  344. 'CApplication' => '/base/CApplication.php',
  345. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  346. 'CBehavior' => '/base/CBehavior.php',
  347. 'CComponent' => '/base/CComponent.php',
  348. 'CErrorEvent' => '/base/CErrorEvent.php',
  349. 'CErrorHandler' => '/base/CErrorHandler.php',
  350. 'CException' => '/base/CException.php',
  351. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  352. 'CHttpException' => '/base/CHttpException.php',
  353. 'CModel' => '/base/CModel.php',
  354. 'CModelBehavior' => '/base/CModelBehavior.php',
  355. 'CModelEvent' => '/base/CModelEvent.php',
  356. 'CModule' => '/base/CModule.php',
  357. 'CSecurityManager' => '/base/CSecurityManager.php',
  358. 'CStatePersister' => '/base/CStatePersister.php',
  359. 'CApcCache' => '/caching/CApcCache.php',
  360. 'CCache' => '/caching/CCache.php',
  361. 'CDbCache' => '/caching/CDbCache.php',
  362. 'CDummyCache' => '/caching/CDummyCache.php',
  363. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  364. 'CFileCache' => '/caching/CFileCache.php',
  365. 'CMemCache' => '/caching/CMemCache.php',
  366. 'CWinCache' => '/caching/CWinCache.php',
  367. 'CXCache' => '/caching/CXCache.php',
  368. 'CZendDataCache' => '/caching/CZendDataCache.php',
  369. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  370. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  371. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  372. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  373. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  374. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  375. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  376. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  377. 'CConfiguration' => '/collections/CConfiguration.php',
  378. 'CList' => '/collections/CList.php',
  379. 'CListIterator' => '/collections/CListIterator.php',
  380. 'CMap' => '/collections/CMap.php',
  381. 'CMapIterator' => '/collections/CMapIterator.php',
  382. 'CQueue' => '/collections/CQueue.php',
  383. 'CQueueIterator' => '/collections/CQueueIterator.php',
  384. 'CStack' => '/collections/CStack.php',
  385. 'CStackIterator' => '/collections/CStackIterator.php',
  386. 'CTypedList' => '/collections/CTypedList.php',
  387. 'CTypedMap' => '/collections/CTypedMap.php',
  388. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  389. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  390. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  391. 'CHelpCommand' => '/console/CHelpCommand.php',
  392. 'CDbCommand' => '/db/CDbCommand.php',
  393. 'CDbConnection' => '/db/CDbConnection.php',
  394. 'CDbDataReader' => '/db/CDbDataReader.php',
  395. 'CDbException' => '/db/CDbException.php',
  396. 'CDbMigration' => '/db/CDbMigration.php',
  397. 'CDbTransaction' => '/db/CDbTransaction.php',
  398. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  399. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  400. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  401. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  402. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  403. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  404. 'CDbExpression' => '/db/schema/CDbExpression.php',
  405. 'CDbSchema' => '/db/schema/CDbSchema.php',
  406. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  407. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  408. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  409. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  410. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  411. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  412. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  413. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  414. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  415. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  416. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  417. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  418. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  419. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  420. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  421. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  422. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  423. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  424. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  425. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  426. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  427. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  428. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  429. 'CLocale' => '/i18n/CLocale.php',
  430. 'CMessageSource' => '/i18n/CMessageSource.php',
  431. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  432. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  433. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  434. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  435. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  436. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  437. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  438. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  439. 'CLogFilter' => '/logging/CLogFilter.php',
  440. 'CLogRoute' => '/logging/CLogRoute.php',
  441. 'CLogRouter' => '/logging/CLogRouter.php',
  442. 'CLogger' => '/logging/CLogger.php',
  443. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  444. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  445. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  446. 'CFileHelper' => '/utils/CFileHelper.php',
  447. 'CFormatter' => '/utils/CFormatter.php',
  448. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  449. 'CPropertyValue' => '/utils/CPropertyValue.php',
  450. 'CTimestamp' => '/utils/CTimestamp.php',
  451. 'CVarDumper' => '/utils/CVarDumper.php',
  452. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  453. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  454. 'CCompareValidator' => '/validators/CCompareValidator.php',
  455. 'CDateValidator' => '/validators/CDateValidator.php',
  456. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  457. 'CEmailValidator' => '/validators/CEmailValidator.php',
  458. 'CExistValidator' => '/validators/CExistValidator.php',
  459. 'CFileValidator' => '/validators/CFileValidator.php',
  460. 'CFilterValidator' => '/validators/CFilterValidator.php',
  461. 'CInlineValidator' => '/validators/CInlineValidator.php',
  462. 'CNumberValidator' => '/validators/CNumberValidator.php',
  463. 'CRangeValidator' => '/validators/CRangeValidator.php',
  464. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  465. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  466. 'CSafeValidator' => '/validators/CSafeValidator.php',
  467. 'CStringValidator' => '/validators/CStringValidator.php',
  468. 'CTypeValidator' => '/validators/CTypeValidator.php',
  469. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  470. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  471. 'CUrlValidator' => '/validators/CUrlValidator.php',
  472. 'CValidator' => '/validators/CValidator.php',
  473. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  474. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  475. 'CAssetManager' => '/web/CAssetManager.php',
  476. 'CBaseController' => '/web/CBaseController.php',
  477. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  478. 'CClientScript' => '/web/CClientScript.php',
  479. 'CController' => '/web/CController.php',
  480. 'CDataProvider' => '/web/CDataProvider.php',
  481. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  482. 'CExtController' => '/web/CExtController.php',
  483. 'CFormModel' => '/web/CFormModel.php',
  484. 'CHttpCookie' => '/web/CHttpCookie.php',
  485. 'CHttpRequest' => '/web/CHttpRequest.php',
  486. 'CHttpSession' => '/web/CHttpSession.php',
  487. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  488. 'COutputEvent' => '/web/COutputEvent.php',
  489. 'CPagination' => '/web/CPagination.php',
  490. 'CSort' => '/web/CSort.php',
  491. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  492. 'CTheme' => '/web/CTheme.php',
  493. 'CThemeManager' => '/web/CThemeManager.php',
  494. 'CUploadedFile' => '/web/CUploadedFile.php',
  495. 'CUrlManager' => '/web/CUrlManager.php',
  496. 'CWebApplication' => '/web/CWebApplication.php',
  497. 'CWebModule' => '/web/CWebModule.php',
  498. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  499. 'CAction' => '/web/actions/CAction.php',
  500. 'CInlineAction' => '/web/actions/CInlineAction.php',
  501. 'CViewAction' => '/web/actions/CViewAction.php',
  502. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  503. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  504. 'CAuthItem' => '/web/auth/CAuthItem.php',
  505. 'CAuthManager' => '/web/auth/CAuthManager.php',
  506. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  507. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  508. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  509. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  510. 'CWebUser' => '/web/auth/CWebUser.php',
  511. 'CFilter' => '/web/filters/CFilter.php',
  512. 'CFilterChain' => '/web/filters/CFilterChain.php',
  513. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  514. 'CForm' => '/web/form/CForm.php',
  515. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  516. 'CFormElement' => '/web/form/CFormElement.php',
  517. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  518. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  519. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  520. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  521. 'CHtml' => '/web/helpers/CHtml.php',
  522. 'CJSON' => '/web/helpers/CJSON.php',
  523. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  524. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  525. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  526. 'CWebService' => '/web/services/CWebService.php',
  527. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  528. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  529. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  530. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  531. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  532. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  533. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  534. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  535. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  536. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  537. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  538. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  539. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  540. 'COutputCache' => '/web/widgets/COutputCache.php',
  541. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  542. 'CStarRating' => '/web/widgets/CStarRating.php',
  543. 'CTabView' => '/web/widgets/CTabView.php',
  544. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  545. 'CTreeView' => '/web/widgets/CTreeView.php',
  546. 'CWidget' => '/web/widgets/CWidget.php',
  547. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  548. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  549. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  550. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  551. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  552. );
  553. }
  554. spl_autoload_register(array('YiiBase','autoload'));
  555. class Yii extends YiiBase
  556. {
  557. }
  558. class CComponent
  559. {
  560. private $_e;
  561. private $_m;
  562. public function __get($name)
  563. {
  564. $getter='get'.$name;
  565. if(method_exists($this,$getter))
  566. return $this->$getter();
  567. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  568. {
  569. // duplicating getEventHandlers() here for performance
  570. $name=strtolower($name);
  571. if(!isset($this->_e[$name]))
  572. $this->_e[$name]=new CList;
  573. return $this->_e[$name];
  574. }
  575. else if(isset($this->_m[$name]))
  576. return $this->_m[$name];
  577. else if(is_array($this->_m))
  578. {
  579. foreach($this->_m as $object)
  580. {
  581. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  582. return $object->$name;
  583. }
  584. }
  585. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  586. array('{class}'=>get_class($this), '{property}'=>$name)));
  587. }
  588. public function __set($name,$value)
  589. {
  590. $setter='set'.$name;
  591. if(method_exists($this,$setter))
  592. return $this->$setter($value);
  593. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  594. {
  595. // duplicating getEventHandlers() here for performance
  596. $name=strtolower($name);
  597. if(!isset($this->_e[$name]))
  598. $this->_e[$name]=new CList;
  599. return $this->_e[$name]->add($value);
  600. }
  601. else if(is_array($this->_m))
  602. {
  603. foreach($this->_m as $object)
  604. {
  605. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  606. return $object->$name=$value;
  607. }
  608. }
  609. if(method_exists($this,'get'.$name))
  610. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  611. array('{class}'=>get_class($this), '{property}'=>$name)));
  612. else
  613. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  614. array('{class}'=>get_class($this), '{property}'=>$name)));
  615. }
  616. public function __isset($name)
  617. {
  618. $getter='get'.$name;
  619. if(method_exists($this,$getter))
  620. return $this->$getter()!==null;
  621. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  622. {
  623. $name=strtolower($name);
  624. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  625. }
  626. else if(is_array($this->_m))
  627. {
  628. if(isset($this->_m[$name]))
  629. return true;
  630. foreach($this->_m as $object)
  631. {
  632. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  633. return true;
  634. }
  635. }
  636. return false;
  637. }
  638. public function __unset($name)
  639. {
  640. $setter='set'.$name;
  641. if(method_exists($this,$setter))
  642. $this->$setter(null);
  643. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  644. unset($this->_e[strtolower($name)]);
  645. else if(is_array($this->_m))
  646. {
  647. if(isset($this->_m[$name]))
  648. $this->detachBehavior($name);
  649. else
  650. {
  651. foreach($this->_m as $object)
  652. {
  653. if($object->getEnabled())
  654. {
  655. if(property_exists($object,$name))
  656. return $object->$name=null;
  657. else if($object->canSetProperty($name))
  658. return $object->$setter(null);
  659. }
  660. }
  661. }
  662. }
  663. else if(method_exists($this,'get'.$name))
  664. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  665. array('{class}'=>get_class($this), '{property}'=>$name)));
  666. }
  667. public function __call($name,$parameters)
  668. {
  669. if($this->_m!==null)
  670. {
  671. foreach($this->_m as $object)
  672. {
  673. if($object->getEnabled() && method_exists($object,$name))
  674. return call_user_func_array(array($object,$name),$parameters);
  675. }
  676. }
  677. if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)
  678. return call_user_func_array($this->$name, $parameters);
  679. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  680. array('{class}'=>get_class($this), '{name}'=>$name)));
  681. }
  682. public function asa($behavior)
  683. {
  684. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  685. }
  686. public function attachBehaviors($behaviors)
  687. {
  688. foreach($behaviors as $name=>$behavior)
  689. $this->attachBehavior($name,$behavior);
  690. }
  691. public function detachBehaviors()
  692. {
  693. if($this->_m!==null)
  694. {
  695. foreach($this->_m as $name=>$behavior)
  696. $this->detachBehavior($name);
  697. $this->_m=null;
  698. }
  699. }
  700. public function attachBehavior($name,$behavior)
  701. {
  702. if(!($behavior instanceof IBehavior))
  703. $behavior=Yii::createComponent($behavior);
  704. $behavior->setEnabled(true);
  705. $behavior->attach($this);
  706. return $this->_m[$name]=$behavior;
  707. }
  708. public function detachBehavior($name)
  709. {
  710. if(isset($this->_m[$name]))
  711. {
  712. $this->_m[$name]->detach($this);
  713. $behavior=$this->_m[$name];
  714. unset($this->_m[$name]);
  715. return $behavior;
  716. }
  717. }
  718. public function enableBehaviors()
  719. {
  720. if($this->_m!==null)
  721. {
  722. foreach($this->_m as $behavior)
  723. $behavior->setEnabled(true);
  724. }
  725. }
  726. public function disableBehaviors()
  727. {
  728. if($this->_m!==null)
  729. {
  730. foreach($this->_m as $behavior)
  731. $behavior->setEnabled(false);
  732. }
  733. }
  734. public function enableBehavior($name)
  735. {
  736. if(isset($this->_m[$name]))
  737. $this->_m[$name]->setEnabled(true);
  738. }
  739. public function disableBehavior($name)
  740. {
  741. if(isset($this->_m[$name]))
  742. $this->_m[$name]->setEnabled(false);
  743. }
  744. public function hasProperty($name)
  745. {
  746. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  747. }
  748. public function canGetProperty($name)
  749. {
  750. return method_exists($this,'get'.$name);
  751. }
  752. public function canSetProperty($name)
  753. {
  754. return method_exists($this,'set'.$name);
  755. }
  756. public function hasEvent($name)
  757. {
  758. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  759. }
  760. public function hasEventHandler($name)
  761. {
  762. $name=strtolower($name);
  763. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  764. }
  765. public function getEventHandlers($name)
  766. {
  767. if($this->hasEvent($name))
  768. {
  769. $name=strtolower($name);
  770. if(!isset($this->_e[$name]))
  771. $this->_e[$name]=new CList;
  772. return $this->_e[$name];
  773. }
  774. else
  775. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  776. array('{class}'=>get_class($this), '{event}'=>$name)));
  777. }
  778. public function attachEventHandler($name,$handler)
  779. {
  780. $this->getEventHandlers($name)->add($handler);
  781. }
  782. public function detachEventHandler($name,$handler)
  783. {
  784. if($this->hasEventHandler($name))
  785. return $this->getEventHandlers($name)->remove($handler)!==false;
  786. else
  787. return false;
  788. }
  789. public function raiseEvent($name,$event)
  790. {
  791. $name=strtolower($name);
  792. if(isset($this->_e[$name]))
  793. {
  794. foreach($this->_e[$name] as $handler)
  795. {
  796. if(is_string($handler))
  797. call_user_func($handler,$event);
  798. else if(is_callable($handler,true))
  799. {
  800. if(is_array($handler))
  801. {
  802. // an array: 0 - object, 1 - method name
  803. list($object,$method)=$handler;
  804. if(is_string($object)) // static method call
  805. call_user_func($handler,$event);
  806. else if(method_exists($object,$method))
  807. $object->$method($event);
  808. else
  809. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  810. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  811. }
  812. else // PHP 5.3: anonymous function
  813. call_user_func($handler,$event);
  814. }
  815. else
  816. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  817. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  818. // stop further handling if param.handled is set true
  819. if(($event instanceof CEvent) && $event->handled)
  820. return;
  821. }
  822. }
  823. else if(YII_DEBUG && !$this->hasEvent($name))
  824. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  825. array('{class}'=>get_class($this), '{event}'=>$name)));
  826. }
  827. public function evaluateExpression($_expression_,$_data_=array())
  828. {
  829. if(is_string($_expression_))
  830. {
  831. extract($_data_);
  832. return eval('return '.$_expression_.';');
  833. }
  834. else
  835. {
  836. $_data_[]=$this;
  837. return call_user_func_array($_expression_, $_data_);
  838. }
  839. }
  840. }
  841. class CEvent extends CComponent
  842. {
  843. public $sender;
  844. public $handled=false;
  845. public $params;
  846. public function __construct($sender=null,$params=null)
  847. {
  848. $this->sender=$sender;
  849. $this->params=$params;
  850. }
  851. }
  852. class CEnumerable
  853. {
  854. }
  855. abstract class CModule extends CComponent
  856. {
  857. public $preload=array();
  858. public $behaviors=array();
  859. private $_id;
  860. private $_parentModule;
  861. private $_basePath;
  862. private $_modulePath;
  863. private $_params;
  864. private $_modules=array();
  865. private $_moduleConfig=array();
  866. private $_components=array();
  867. private $_componentConfig=array();
  868. public function __construct($id,$parent,$config=null)
  869. {
  870. $this->_id=$id;
  871. $this->_parentModule=$parent;
  872. // set basePath at early as possible to avoid trouble
  873. if(is_string($config))
  874. $config=require($config);
  875. if(isset($config['basePath']))
  876. {
  877. $this->setBasePath($config['basePath']);
  878. unset($config['basePath']);
  879. }
  880. Yii::setPathOfAlias($id,$this->getBasePath());
  881. $this->preinit();
  882. $this->configure($config);
  883. $this->attachBehaviors($this->behaviors);
  884. $this->preloadComponents();
  885. $this->init();
  886. }
  887. public function __get($name)
  888. {
  889. if($this->hasComponent($name))
  890. return $this->getComponent($name);
  891. else
  892. return parent::__get($name);
  893. }
  894. public function __isset($name)
  895. {
  896. if($this->hasComponent($name))
  897. return $this->getComponent($name)!==null;
  898. else
  899. return parent::__isset($name);
  900. }
  901. public function getId()
  902. {
  903. return $this->_id;
  904. }
  905. public function setId($id)
  906. {
  907. $this->_id=$id;
  908. }
  909. public function getBasePath()
  910. {
  911. if($this->_basePath===null)
  912. {
  913. $class=new ReflectionClass(get_class($this));
  914. $this->_basePath=dirname($class->getFileName());
  915. }
  916. return $this->_basePath;
  917. }
  918. public function setBasePath($path)
  919. {
  920. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  921. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  922. array('{path}'=>$path)));
  923. }
  924. public function getParams()
  925. {
  926. if($this->_params!==null)
  927. return $this->_params;
  928. else
  929. {
  930. $this->_params=new CAttributeCollection;
  931. $this->_params->caseSensitive=true;
  932. return $this->_params;
  933. }
  934. }
  935. public function setParams($value)
  936. {
  937. $params=$this->getParams();
  938. foreach($value as $k=>$v)
  939. $params->add($k,$v);
  940. }
  941. public function getModulePath()
  942. {
  943. if($this->_modulePath!==null)
  944. return $this->_modulePath;
  945. else
  946. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  947. }
  948. public function setModulePath($value)
  949. {
  950. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  951. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  952. array('{path}'=>$value)));
  953. }
  954. public function setImport($aliases)
  955. {
  956. foreach($aliases as $alias)
  957. Yii::import($alias);
  958. }
  959. public function setAliases($mappings)
  960. {
  961. foreach($mappings as $name=>$alias)
  962. {
  963. if(($path=Yii::getPathOfAlias($alias))!==false)
  964. Yii::setPathOfAlias($name,$path);
  965. else
  966. Yii::setPathOfAlias($name,$alias);
  967. }
  968. }
  969. public function getParentModule()
  970. {
  971. return $this->_parentModule;
  972. }
  973. public function getModule($id)
  974. {
  975. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  976. return $this->_modules[$id];
  977. else if(isset($this->_moduleConfig[$id]))
  978. {
  979. $config=$this->_moduleConfig[$id];
  980. if(!isset($config['enabled']) || $config['enabled'])
  981. {
  982. $class=$config['class'];
  983. unset($config['class'], $config['enabled']);
  984. if($this===Yii::app())
  985. $module=Yii::createComponent($class,$id,null,$config);
  986. else
  987. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  988. return $this->_modules[$id]=$module;
  989. }
  990. }
  991. }
  992. public function hasModule($id)
  993. {
  994. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  995. }
  996. public function getModules()
  997. {
  998. return $this->_moduleConfig;
  999. }
  1000. public function setModules($modules)
  1001. {
  1002. foreach($modules as $id=>$module)
  1003. {
  1004. if(is_int($id))
  1005. {
  1006. $id=$module;
  1007. $module=array();
  1008. }
  1009. if(!isset($module['class']))
  1010. {
  1011. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1012. $module['class']=$id.'.'.ucfirst($id).'Module';
  1013. }
  1014. if(isset($this->_moduleConfig[$id]))
  1015. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1016. else
  1017. $this->_moduleConfig[$id]=$module;
  1018. }
  1019. }
  1020. public function hasComponent($id)
  1021. {
  1022. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1023. }
  1024. public function getComponent($id,$createIfNull=true)
  1025. {
  1026. if(isset($this->_components[$id]))
  1027. return $this->_components[$id];
  1028. else if(isset($this->_componentConfig[$id]) && $createIfNull)
  1029. {
  1030. $config=$this->_componentConfig[$id];
  1031. if(!isset($config['enabled']) || $config['enabled'])
  1032. {
  1033. unset($config['enabled']);
  1034. $component=Yii::createComponent($config);
  1035. $component->init();
  1036. return $this->_components[$id]=$component;
  1037. }
  1038. }
  1039. }
  1040. public function setComponent($id,$component)
  1041. {
  1042. if($component===null)
  1043. unset($this->_components[$id]);
  1044. else
  1045. {
  1046. $this->_components[$id]=$component;
  1047. if(!$component->getIsInitialized())
  1048. $component->init();
  1049. }
  1050. }
  1051. public function getComponents($loadedOnly=true)
  1052. {
  1053. if($loadedOnly)
  1054. return $this->_components;
  1055. else
  1056. return array_merge($this->_componentConfig, $this->_components);
  1057. }
  1058. public function setComponents($components,$merge=true)
  1059. {
  1060. foreach($components as $id=>$component)
  1061. {
  1062. if($component instanceof IApplicationComponent)
  1063. $this->setComponent($id,$component);
  1064. else if(isset($this->_componentConfig[$id]) && $merge)
  1065. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1066. else
  1067. $this->_componentConfig[$id]=$component;
  1068. }
  1069. }
  1070. public function configure($config)
  1071. {
  1072. if(is_array($config))
  1073. {
  1074. foreach($config as $key=>$value)
  1075. $this->$key=$value;
  1076. }
  1077. }
  1078. protected function preloadComponents()
  1079. {
  1080. foreach($this->preload as $id)
  1081. $this->getComponent($id);
  1082. }
  1083. protected function preinit()
  1084. {
  1085. }
  1086. protected function init()
  1087. {
  1088. }
  1089. }
  1090. abstract class CApplication extends CModule
  1091. {
  1092. public $name='My Application';
  1093. public $charset='UTF-8';
  1094. public $sourceLanguage='en_us';
  1095. private $_id;
  1096. private $_basePath;
  1097. private $_runtimePath;
  1098. private $_extensionPath;
  1099. private $_globalState;
  1100. private $_stateChanged;
  1101. private $_ended=false;
  1102. private $_language;
  1103. private $_homeUrl;
  1104. abstract public function processRequest();
  1105. public function __construct($config=null)
  1106. {
  1107. Yii::setApplication($this);
  1108. // set basePath at early as possible to avoid trouble
  1109. if(is_string($config))
  1110. $config=require($config);
  1111. if(isset($config['basePath']))
  1112. {
  1113. $this->setBasePath($config['basePath']);
  1114. unset($config['basePath']);
  1115. }
  1116. else
  1117. $this->setBasePath('protected');
  1118. Yii::setPathOfAlias('application',$this->getBasePath());
  1119. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1120. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1121. $this->preinit();
  1122. $this->initSystemHandlers();
  1123. $this->registerCoreComponents();
  1124. $this->configure($config);
  1125. $this->attachBehaviors($this->behaviors);
  1126. $this->preloadComponents();
  1127. $this->init();
  1128. }
  1129. public function run()
  1130. {
  1131. if($this->hasEventHandler('onBeginRequest'))
  1132. $this->onBeginRequest(new CEvent($this));
  1133. $this->processRequest();
  1134. if($this->hasEventHandler('onEndRequest'))
  1135. $this->onEndRequest(new CEvent($this));
  1136. }
  1137. public function end($status=0, $exit=true)
  1138. {
  1139. if($this->hasEventHandler('onEndRequest'))
  1140. $this->onEndRequest(new CEvent($this));
  1141. if($exit)
  1142. exit($status);
  1143. }
  1144. public function onBeginRequest($event)
  1145. {
  1146. $this->raiseEvent('onBeginRequest',$event);
  1147. }
  1148. public function onEndRequest($event)
  1149. {
  1150. if(!$this->_ended)
  1151. {
  1152. $this->_ended=true;
  1153. $this->raiseEvent('onEndRequest',$event);
  1154. }
  1155. }
  1156. public function getId()
  1157. {
  1158. if($this->_id!==null)
  1159. return $this->_id;
  1160. else
  1161. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1162. }
  1163. public function setId($id)
  1164. {
  1165. $this->_id=$id;
  1166. }
  1167. public function getBasePath()
  1168. {
  1169. return $this->_basePath;
  1170. }
  1171. public function setBasePath($path)
  1172. {
  1173. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1174. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1175. array('{path}'=>$path)));
  1176. }
  1177. public function getRuntimePath()
  1178. {
  1179. if($this->_runtimePath!==null)
  1180. return $this->_runtimePath;
  1181. else
  1182. {
  1183. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1184. return $this->_runtimePath;
  1185. }
  1186. }
  1187. public function setRuntimePath($path)
  1188. {
  1189. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1190. 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.',
  1191. array('{path}'=>$path)));
  1192. $this->_runtimePath=$runtimePath;
  1193. }
  1194. public function getExtensionPath()
  1195. {
  1196. return Yii::getPathOfAlias('ext');
  1197. }
  1198. public function setExtensionPath($path)
  1199. {
  1200. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1201. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1202. array('{path}'=>$path)));
  1203. Yii::setPathOfAlias('ext',$extensionPath);
  1204. }
  1205. public function getLanguage()
  1206. {
  1207. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1208. }
  1209. public function setLanguage($language)
  1210. {
  1211. $this->_language=$language;
  1212. }
  1213. public function getTimeZone()
  1214. {
  1215. return date_default_timezone_get();
  1216. }
  1217. public function setTimeZone($value)
  1218. {
  1219. date_default_timezone_set($value);
  1220. }
  1221. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1222. {
  1223. if($srcLanguage===null)
  1224. $srcLanguage=$this->sourceLanguage;
  1225. if($language===null)
  1226. $language=$this->getLanguage();
  1227. if($language===$srcLanguage)
  1228. return $srcFile;
  1229. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1230. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1231. }
  1232. public function getLocale($localeID=null)
  1233. {
  1234. return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID);
  1235. }
  1236. public function getLocaleDataPath()
  1237. {
  1238. return CLocale::$dataPath===null ? Yii::getPathOfAlias('system.i18n.data') : CLocale::$dataPath;
  1239. }
  1240. public function setLocaleDataPath($value)
  1241. {
  1242. CLocale::$dataPath=$value;
  1243. }
  1244. public function getNumberFormatter()
  1245. {
  1246. return $this->getLocale()->getNumberFormatter();
  1247. }
  1248. public function getDateFormatter()
  1249. {
  1250. return $this->getLocale()->getDateFormatter();
  1251. }
  1252. public function getDb()
  1253. {
  1254. return $this->getComponent('db');
  1255. }
  1256. public function getErrorHandler()
  1257. {
  1258. return $this->getComponent('errorHandler');
  1259. }
  1260. public function getSecurityManager()
  1261. {
  1262. return $this->getComponent('securityManager');
  1263. }
  1264. public function getStatePersister()
  1265. {
  1266. return $this->getComponent('statePersister');
  1267. }
  1268. public function getCache()
  1269. {
  1270. return $this->getComponent('cache');
  1271. }
  1272. public function getCoreMessages()
  1273. {
  1274. return $this->getComponent('coreMessages');
  1275. }
  1276. public function getMessages()
  1277. {
  1278. return $this->getComponent('messages');
  1279. }
  1280. public function getRequest()
  1281. {
  1282. return $this->getComponent('request');
  1283. }
  1284. public function getUrlManager()
  1285. {
  1286. return $this->getComponent('urlManager');
  1287. }
  1288. public function getController()
  1289. {
  1290. return null;
  1291. }
  1292. public function createUrl($route,$params=array(),$ampersand='&')
  1293. {
  1294. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1295. }
  1296. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1297. {
  1298. $url=$this->createUrl($route,$params,$ampersand);
  1299. if(strpos($url,'http')===0)
  1300. return $url;
  1301. else
  1302. return $this->getRequest()->getHostInfo($schema).$url;
  1303. }
  1304. public function getBaseUrl($absolute=false)
  1305. {
  1306. return $this->getRequest()->getBaseUrl($absolute);
  1307. }
  1308. public function getHomeUrl()
  1309. {
  1310. if($this->_homeUrl===null)
  1311. {
  1312. if($this->getUrlManager()->showScriptName)
  1313. return $this->getRequest()->getScriptUrl();
  1314. else
  1315. return $this->getRequest()->getBaseUrl().'/';
  1316. }
  1317. else
  1318. return $this->_homeUrl;
  1319. }
  1320. public function setHomeUrl($value)
  1321. {
  1322. $this->_homeUrl=$value;
  1323. }
  1324. public function getGlobalState($key,$defaultValue=null)
  1325. {
  1326. if($this->_globalState===null)
  1327. $this->loadGlobalState();
  1328. if(isset($this->_globalState[$key]))
  1329. return $this->_globalState[$key];
  1330. else
  1331. return $defaultValue;
  1332. }
  1333. public function setGlobalState($key,$value,$defaultValue=null)
  1334. {
  1335. if($this->_globalState===null)
  1336. $this->loadGlobalState();
  1337. $changed=$this->_stateChanged;
  1338. if($value===$defaultValue)
  1339. {
  1340. if(isset($this->_globalState[$key]))
  1341. {
  1342. unset($this->_globalState[$key]);
  1343. $this->_stateChanged=true;
  1344. }
  1345. }
  1346. else if(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1347. {
  1348. $this->_globalState[$key]=$value;
  1349. $this->_stateChanged=true;
  1350. }
  1351. if($this->_stateChanged!==$changed)
  1352. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1353. }
  1354. public function clearGlobalState($key)
  1355. {
  1356. $this->setGlobalState($key,true,true);
  1357. }
  1358. public function loadGlobalState()
  1359. {
  1360. $persister=$this->getStatePersister();
  1361. if(($this->_globalState=$persister->load())===null)
  1362. $this->_globalState=array();
  1363. $this->_stateChanged=false;
  1364. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1365. }
  1366. public function saveGlobalState()
  1367. {
  1368. if($this->_stateChanged)
  1369. {
  1370. $this->_stateChanged=false;
  1371. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1372. $this->getStatePersister()->save($this->_globalState);
  1373. }
  1374. }
  1375. public function handleException($exception)
  1376. {
  1377. // disable error capturing to avoid recursive errors
  1378. restore_error_handler();
  1379. restore_exception_handler();
  1380. $category='exception.'.get_class($exception);
  1381. if($exception instanceof CHttpException)
  1382. $category.='.'.$exception->statusCode;
  1383. // php <5.2 doesn't support string conversion auto-magically
  1384. $message=$exception->__toString();
  1385. if(isset($_SERVER['REQUEST_URI']))
  1386. $message.=' REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1387. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1388. try
  1389. {
  1390. $event=new CExceptionEvent($this,$exception);
  1391. $this->onException($event);
  1392. if(!$event->handled)
  1393. {
  1394. // try an error handler
  1395. if(($handler=$this->getErrorHandler())!==null)
  1396. $handler->handle($event);
  1397. else
  1398. $this->displayException($exception);
  1399. }
  1400. }
  1401. catch(Exception $e)
  1402. {
  1403. $this->displayException($e);
  1404. }
  1405. try
  1406. {
  1407. $this->end(1);
  1408. }
  1409. catch(Exception $e)
  1410. {
  1411. // use the most primitive way to log error
  1412. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1413. $msg .= $e->getTraceAsString()."\n";
  1414. $msg .= "Previous exception:\n";
  1415. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1416. $msg .= $exception->getTraceAsString()."\n";
  1417. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1418. error_log($msg);
  1419. exit(1);
  1420. }
  1421. }
  1422. public function handleError($code,$message,$file,$line)
  1423. {
  1424. if($code & error_reporting())
  1425. {
  1426. // disable error capturing to avoid recursive errors
  1427. restore_error_handler();
  1428. restore_exception_handler();
  1429. $log="$message ($file:$line)\nStack trace:\n";
  1430. $trace=debug_backtrace();
  1431. // skip the first 3 stacks as they do not tell the error position
  1432. if(count($trace)>3)
  1433. $trace=array_slice($trace,3);
  1434. foreach($trace as $i=>$t)
  1435. {
  1436. if(!isset($t['file']))
  1437. $t['file']='unknown';
  1438. if(!isset($t['line']))
  1439. $t['line']=0;
  1440. if(!isset($t['function']))
  1441. $t['function']='unknown';
  1442. $log.="#$i {$t['file']}({$t['line']}): ";
  1443. if(isset($t['object']) && is_object($t['object']))
  1444. $log.=get_class($t['object']).'->';
  1445. $log.="{$t['function']}()\n";
  1446. }
  1447. if(isset($_SERVER['REQUEST_URI']))
  1448. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1449. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1450. try
  1451. {
  1452. Yii::import('CErrorEvent',true);
  1453. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1454. $this->onError($event);
  1455. if(!$event->handled)
  1456. {
  1457. // try an error handler
  1458. if(($handler=$this->getErrorHandler())!==null)
  1459. $handler->handle($event);
  1460. else
  1461. $this->displayError($code,$message,$file,$line);
  1462. }
  1463. }
  1464. catch(Exception $e)
  1465. {
  1466. $this->displayException($e);
  1467. }
  1468. try
  1469. {
  1470. $this->end(1);
  1471. }
  1472. catch(Exception $e)
  1473. {
  1474. // use the most primitive way to log error
  1475. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1476. $msg .= $e->getTraceAsString()."\n";
  1477. $msg .= "Previous error:\n";
  1478. $msg .= $log."\n";
  1479. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1480. error_log($msg);
  1481. exit(1);
  1482. }
  1483. }
  1484. }
  1485. public function onException($event)
  1486. {
  1487. $this->raiseEvent('onException',$event);
  1488. }
  1489. public function onError($event)
  1490. {
  1491. $this->raiseEvent('onError',$event);
  1492. }
  1493. public function displayError($code,$message,$file,$line)
  1494. {
  1495. if(YII_DEBUG)
  1496. {
  1497. echo "<h1>PHP Error [$code]</h1>\n";
  1498. echo "<p>$message ($file:$line)</p>\n";
  1499. echo '<pre>';
  1500. $trace=debug_backtrace();
  1501. // skip the first 3 stacks as they do not tell the error position
  1502. if(count($trace)>3)
  1503. $trace=array_slice($trace,3);
  1504. foreach($trace as $i=>$t)
  1505. {
  1506. if(!isset($t['file']))
  1507. $t['file']='unknown';
  1508. if(!isset($t['line']))
  1509. $t['line']=0;
  1510. if(!isset($t['function']))
  1511. $t['function']='unknown';
  1512. echo "#$i {$t['file']}({$t['line']}): ";
  1513. if(isset($t['object']) && is_object($t['object']))
  1514. echo get_class($t['object']).'->';
  1515. echo "{$t['function']}()\n";
  1516. }
  1517. echo '</pre>';
  1518. }
  1519. else
  1520. {
  1521. echo "<h1>PHP Error [$code]</h1>\n";
  1522. echo "<p>$message</p>\n";
  1523. }
  1524. }
  1525. public function displayException($exception)
  1526. {
  1527. if(YII_DEBUG)
  1528. {
  1529. echo '<h1>'.get_class($exception)."</h1>\n";
  1530. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1531. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1532. }
  1533. else
  1534. {
  1535. echo '<h1>'.get_class($exception)."</h1>\n";
  1536. echo '<p>'.$exception->getMessage().'</p>';
  1537. }
  1538. }
  1539. protected function initSystemHandlers()
  1540. {
  1541. if(YII_ENABLE_EXCEPTION_HANDLER)
  1542. set_exception_handler(array($this,'handleException'));
  1543. if(YII_ENABLE_ERROR_HANDLER)
  1544. set_error_handler(array($this,'handleError'),error_reporting());
  1545. }
  1546. protected function registerCoreComponents()
  1547. {
  1548. $components=array(
  1549. 'coreMessages'=>array(
  1550. 'class'=>'CPhpMessageSource',
  1551. 'language'=>'en_us',
  1552. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1553. ),
  1554. 'db'=>array(
  1555. 'class'=>'CDbConnection',
  1556. ),
  1557. 'messages'=>array(
  1558. 'class'=>'CPhpMessageSource',
  1559. ),
  1560. 'errorHandler'=>array(
  1561. 'class'=>'CErrorHandler',
  1562. ),
  1563. 'securityManager'=>array(
  1564. 'class'=>'CSecurityManager',
  1565. ),
  1566. 'statePersister'=>array(
  1567. 'class'=>'CStatePersister',
  1568. ),
  1569. 'urlManager'=>array(
  1570. 'class'=>'CUrlManager',
  1571. ),
  1572. 'request'=>array(
  1573. 'class'=>'CHttpRequest',
  1574. ),
  1575. 'format'=>array(
  1576. 'class'=>'CFormatter',
  1577. ),
  1578. );
  1579. $this->setComponents($components);
  1580. }
  1581. }
  1582. class CWebApplication extends CApplication
  1583. {
  1584. public $defaultController='site';
  1585. public $layout='main';
  1586. public $controllerMap=array();
  1587. public $catchAllRequest;
  1588. private $_controllerPath;
  1589. private $_viewPath;
  1590. private $_systemViewPath;
  1591. private $_layoutPath;
  1592. private $_controller;
  1593. private $_theme;
  1594. public function processRequest()
  1595. {
  1596. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1597. {
  1598. $route=$this->catchAllRequest[0];
  1599. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1600. $_GET[$name]=$value;
  1601. }
  1602. else
  1603. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1604. $this->runController($route);
  1605. }
  1606. protected function registerCoreComponents()
  1607. {
  1608. parent::registerCoreComponents();
  1609. $components=array(
  1610. 'session'=>array(
  1611. 'class'=>'CHttpSession',
  1612. ),
  1613. 'assetManager'=>array(
  1614. 'class'=>'CAssetManager',
  1615. ),
  1616. 'user'=>array(
  1617. 'class'=>'CWebUser',
  1618. ),
  1619. 'themeManager'=>array(
  1620. 'class'=>'CThemeManager',
  1621. ),
  1622. 'authManager'=>array(
  1623. 'class'=>'CPhpAuthManager',
  1624. ),
  1625. 'clientScript'=>array(
  1626. 'class'=>'CClientScript',
  1627. ),
  1628. 'widgetFactory'=>array(
  1629. 'class'=>'CWidgetFactory',
  1630. ),
  1631. );
  1632. $this->setComponents($components);
  1633. }
  1634. public function getAuthManager()
  1635. {
  1636. return $this->getComponent('authManager');
  1637. }
  1638. public function getAssetManager()
  1639. {
  1640. return $this->getComponent('assetManager');
  1641. }
  1642. public function getSession()
  1643. {
  1644. return $this->getComponent('session');
  1645. }
  1646. public function getUser()
  1647. {
  1648. return $this->getComponent('user');
  1649. }
  1650. public function getViewRenderer()
  1651. {
  1652. return $this->getComponent('viewRenderer');
  1653. }
  1654. public function getClientScript()
  1655. {
  1656. return $this->getComponent('clientScript');
  1657. }
  1658. public function getWidgetFactory()
  1659. {
  1660. return $this->getComponent('widgetFactory');
  1661. }
  1662. public function getThemeManager()
  1663. {
  1664. return $this->getComponent('themeManager');
  1665. }
  1666. public function getTheme()
  1667. {
  1668. if(is_string($this->_theme))
  1669. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1670. return $this->_theme;
  1671. }
  1672. public function setTheme($value)
  1673. {
  1674. $this->_theme=$value;
  1675. }
  1676. public function runController($route)
  1677. {
  1678. if(($ca=$this->createController($route))!==null)
  1679. {
  1680. list($controller,$actionID)=$ca;
  1681. $oldController=$this->_controller;
  1682. $this->_controller=$controller;
  1683. $controller->init();
  1684. $controller->run($actionID);
  1685. $this->_controller=$oldController;
  1686. }
  1687. else
  1688. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1689. array('{route}'=>$route===''?$this->defaultController:$route)));
  1690. }
  1691. public function createController($route,$owner=null)
  1692. {
  1693. if($owner===null)
  1694. $owner=$this;
  1695. if(($route=trim($route,'/'))==='')
  1696. $route=$owner->defaultController;
  1697. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1698. $route.='/';
  1699. while(($pos=strpos($route,'/'))!==false)
  1700. {
  1701. $id=substr($route,0,$pos);
  1702. if(!preg_match('/^\w+$/',$id))
  1703. return null;
  1704. if(!$caseSensitive)
  1705. $id=strtolower($id);
  1706. $route=(string)substr($route,$pos+1);
  1707. if(!isset($basePath)) // first segment
  1708. {
  1709. if(isset($owner->controllerMap[$id]))
  1710. {
  1711. return array(
  1712. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1713. $this->parseActionParams($route),
  1714. );
  1715. }
  1716. if(($module=$owner->getModule($id))!==null)
  1717. return $this->createController($route,$module);
  1718. $basePath=$owner->getControllerPath();
  1719. $controllerID='';
  1720. }
  1721. else
  1722. $controllerID.='/';
  1723. $className=ucfirst($id).'Controller';
  1724. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1725. if(is_file($classFile))
  1726. {
  1727. if(!class_exists($className,false))
  1728. require($classFile);
  1729. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1730. {
  1731. $id[0]=strtolower($id[0]);
  1732. return array(
  1733. new $className($controllerID.$id,$owner===$this?null:$owner),
  1734. $this->parseActionParams($route),
  1735. );
  1736. }
  1737. return null;
  1738. }
  1739. $controllerID.=$id;
  1740. $basePath.=DIRECTORY_SEPARATOR.$id;
  1741. }
  1742. }
  1743. protected function parseActionParams($pathInfo)
  1744. {
  1745. if(($pos=strpos($pathInfo,'/'))!==false)
  1746. {
  1747. $manager=$this->getUrlManager();
  1748. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1749. $actionID=substr($pathInfo,0,$pos);
  1750. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1751. }
  1752. else
  1753. return $pathInfo;
  1754. }
  1755. public function getController()
  1756. {
  1757. return $this->_controller;
  1758. }
  1759. public function setController($value)
  1760. {
  1761. $this->_controller=$value;
  1762. }
  1763. public function getControllerPath()
  1764. {
  1765. if($this->_controllerPath!==null)
  1766. return $this->_controllerPath;
  1767. else
  1768. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1769. }
  1770. public function setControllerPath($value)
  1771. {
  1772. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1773. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1774. array('{path}'=>$value)));
  1775. }
  1776. public function getViewPath()
  1777. {
  1778. if($this->_viewPath!==null)
  1779. return $this->_viewPath;
  1780. else
  1781. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1782. }
  1783. public function setViewPath($path)
  1784. {
  1785. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1786. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1787. array('{path}'=>$path)));
  1788. }
  1789. public function getSystemViewPath()
  1790. {
  1791. if($this->_systemViewPath!==null)
  1792. return $this->_systemViewPath;
  1793. else
  1794. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1795. }
  1796. public function setSystemViewPath($path)
  1797. {
  1798. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1799. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1800. array('{path}'=>$path)));
  1801. }
  1802. public function getLayoutPath()
  1803. {
  1804. if($this->_layoutPath!==null)
  1805. return $this->_layoutPath;
  1806. else
  1807. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1808. }
  1809. public function setLayoutPath($path)
  1810. {
  1811. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1812. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1813. array('{path}'=>$path)));
  1814. }
  1815. public function beforeControllerAction($controller,$action)
  1816. {
  1817. return true;
  1818. }
  1819. public function afterControllerAction($controller,$action)
  1820. {
  1821. }
  1822. public function findModule($id)
  1823. {
  1824. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1825. {
  1826. do
  1827. {
  1828. if(($m=$module->getModule($id))!==null)
  1829. return $m;
  1830. } while(($module=$module->getParentModule())!==null);
  1831. }
  1832. if(($m=$this->getModule($id))!==null)
  1833. return $m;
  1834. }
  1835. protected function init()
  1836. {
  1837. parent::init();
  1838. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1839. $this->getRequest();
  1840. }
  1841. }
  1842. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1843. {
  1844. private $_d=array();
  1845. private $_r=false;
  1846. public function __construct($data=null,$readOnly=false)
  1847. {
  1848. if($data!==null)
  1849. $this->copyFrom($data);
  1850. $this->setReadOnly($readOnly);
  1851. }
  1852. public function getReadOnly()
  1853. {
  1854. return $this->_r;
  1855. }
  1856. protected function setReadOnly($value)
  1857. {
  1858. $this->_r=$value;
  1859. }
  1860. public function getIterator()
  1861. {
  1862. return new CMapIterator($this->_d);
  1863. }
  1864. public function count()
  1865. {
  1866. return $this->getCount();
  1867. }
  1868. public function getCount()
  1869. {
  1870. return count($this->_d);
  1871. }
  1872. public function getKeys()
  1873. {
  1874. return array_keys($this->_d);
  1875. }
  1876. public function itemAt($key)
  1877. {
  1878. if(isset($this->_d[$key]))
  1879. return $this->_d[$key];
  1880. else
  1881. return null;
  1882. }
  1883. public function add($key,$value)
  1884. {
  1885. if(!$this->_r)
  1886. {
  1887. if($key===null)
  1888. $this->_d[]=$value;
  1889. else
  1890. $this->_d[$key]=$value;
  1891. }
  1892. else
  1893. throw new CException(Yii::t('yii','The map is read only.'));
  1894. }
  1895. public function remove($key)
  1896. {
  1897. if(!$this->_r)
  1898. {
  1899. if(isset($this->_d[$key]))
  1900. {
  1901. $value=$this->_d[$key];
  1902. unset($this->_d[$key]);
  1903. return $value;
  1904. }
  1905. else
  1906. {
  1907. // it is possible the value is null, which is not detected by isset
  1908. unset($this->_d[$key]);
  1909. return null;
  1910. }
  1911. }
  1912. else
  1913. throw new CException(Yii::t('yii','The map is read only.'));
  1914. }
  1915. public function clear()
  1916. {
  1917. foreach(array_keys($this->_d) as $key)
  1918. $this->remove($key);
  1919. }
  1920. public function contains($key)
  1921. {
  1922. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  1923. }
  1924. public function toArray()
  1925. {
  1926. return $this->_d;
  1927. }
  1928. public function copyFrom($data)
  1929. {
  1930. if(is_array($data) || $data instanceof Traversable)
  1931. {
  1932. if($this->getCount()>0)
  1933. $this->clear();
  1934. if($data instanceof CMap)
  1935. $data=$data->_d;
  1936. foreach($data as $key=>$value)
  1937. $this->add($key,$value);
  1938. }
  1939. else if($data!==null)
  1940. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1941. }
  1942. public function mergeWith($data,$recursive=true)
  1943. {
  1944. if(is_array($data) || $data instanceof Traversable)
  1945. {
  1946. if($data instanceof CMap)
  1947. $data=$data->_d;
  1948. if($recursive)
  1949. {
  1950. if($data instanceof Traversable)
  1951. {
  1952. $d=array();
  1953. foreach($data as $key=>$value)
  1954. $d[$key]=$value;
  1955. $this->_d=self::mergeArray($this->_d,$d);
  1956. }
  1957. else
  1958. $this->_d=self::mergeArray($this->_d,$data);
  1959. }
  1960. else
  1961. {
  1962. foreach($data as $key=>$value)
  1963. $this->add($key,$value);
  1964. }
  1965. }
  1966. else if($data!==null)
  1967. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1968. }
  1969. public static function mergeArray($a,$b)
  1970. {
  1971. foreach($b as $k=>$v)
  1972. {
  1973. if(is_integer($k))
  1974. isset($a[$k]) ? $a[]=$v : $a[$k]=$v;
  1975. else if(is_array($v) && isset($a[$k]) && is_array($a[$k]))
  1976. $a[$k]=self::mergeArray($a[$k],$v);
  1977. else
  1978. $a[$k]=$v;
  1979. }
  1980. return $a;
  1981. }
  1982. public function offsetExists($offset)
  1983. {
  1984. return $this->contains($offset);
  1985. }
  1986. public function offsetGet($offset)
  1987. {
  1988. return $this->itemAt($offset);
  1989. }
  1990. public function offsetSet($offset,$item)
  1991. {
  1992. $this->add($offset,$item);
  1993. }
  1994. public function offsetUnset($offset)
  1995. {
  1996. $this->remove($offset);
  1997. }
  1998. }
  1999. class CLogger extends CComponent
  2000. {
  2001. const LEVEL_TRACE='trace';
  2002. const LEVEL_WARNING='warning';
  2003. const LEVEL_ERROR='error';
  2004. const LEVEL_INFO='info';
  2005. const LEVEL_PROFILE='profile';
  2006. public $autoFlush=10000;
  2007. public $autoDump=false;
  2008. private $_logs=array();
  2009. private $_logCount=0;
  2010. private $_levels;
  2011. private $_categories;
  2012. private $_timings;
  2013. public function log($message,$level='info',$category='application')
  2014. {
  2015. $this->_logs[]=array($message,$level,$category,microtime(true));
  2016. $this->_logCount++;
  2017. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush)
  2018. $this->flush($this->autoDump);
  2019. }
  2020. public function getLogs($levels='',$categories='')
  2021. {
  2022. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2023. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2024. if(empty($levels) && empty($categories))
  2025. return $this->_logs;
  2026. else if(empty($levels))
  2027. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByCategory'))));
  2028. else if(empty($categories))
  2029. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  2030. else
  2031. {
  2032. $ret=array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  2033. return array_values(array_filter(array_filter($ret,array($this,'filterByCategory'))));
  2034. }
  2035. }
  2036. private function filterByCategory($value)
  2037. {
  2038. foreach($this->_categories as $category)
  2039. {
  2040. $cat=strtolower($value[2]);
  2041. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2042. return $value;
  2043. }
  2044. return false;
  2045. }
  2046. private function filterByLevel($value)
  2047. {
  2048. return in_array(strtolower($value[1]),$this->_levels)?$value:false;
  2049. }
  2050. public function getExecutionTime()
  2051. {
  2052. return microtime(true)-YII_BEGIN_TIME;
  2053. }
  2054. public function getMemoryUsage()
  2055. {
  2056. if(function_exists('memory_get_usage'))
  2057. return memory_get_usage();
  2058. else
  2059. {
  2060. $output=array();
  2061. if(strncmp(PHP_OS,'WIN',3)===0)
  2062. {
  2063. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2064. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2065. }
  2066. else
  2067. {
  2068. $pid=getmypid();
  2069. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2070. $output=explode(" ",$output[0]);
  2071. return isset($output[1]) ? $output[1]*1024 : 0;
  2072. }
  2073. }
  2074. }
  2075. public function getProfilingResults($token=null,$category=null,$refresh=false)
  2076. {
  2077. if($this->_timings===null || $refresh)
  2078. $this->calculateTimings();
  2079. if($token===null && $category===null)
  2080. return $this->_timings;
  2081. $results=array();
  2082. foreach($this->_timings as $timing)
  2083. {
  2084. if(($category===null || $timing[1]===$category) && ($token===null || $timing[0]===$token))
  2085. $results[]=$timing[2];
  2086. }
  2087. return $results;
  2088. }
  2089. private function calculateTimings()
  2090. {
  2091. $this->_timings=array();
  2092. $stack=array();
  2093. foreach($this->_logs as $log)
  2094. {
  2095. if($log[1]!==CLogger::LEVEL_PROFILE)
  2096. continue;
  2097. list($message,$level,$category,$timestamp)=$log;
  2098. if(!strncasecmp($message,'begin:',6))
  2099. {
  2100. $log[0]=substr($message,6);
  2101. $stack[]=$log;
  2102. }
  2103. else if(!strncasecmp($message,'end:',4))
  2104. {
  2105. $token=substr($message,4);
  2106. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2107. {
  2108. $delta=$log[3]-$last[3];
  2109. $this->_timings[]=array($message,$category,$delta);
  2110. }
  2111. else
  2112. throw new CException(Yii::t('yii','CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.',
  2113. array('{token}'=>$token)));
  2114. }
  2115. }
  2116. $now=microtime(true);
  2117. while(($last=array_pop($stack))!==null)
  2118. {
  2119. $delta=$now-$last[3];
  2120. $this->_timings[]=array($last[0],$last[2],$delta);
  2121. }
  2122. }
  2123. public function flush($dumpLogs=false)
  2124. {
  2125. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2126. $this->_logs=array();
  2127. $this->_logCount=0;
  2128. }
  2129. public function onFlush($event)
  2130. {
  2131. $this->raiseEvent('onFlush', $event);
  2132. }
  2133. }
  2134. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2135. {
  2136. public $behaviors=array();
  2137. private $_initialized=false;
  2138. public function init()
  2139. {
  2140. $this->attachBehaviors($this->behaviors);
  2141. $this->_initialized=true;
  2142. }
  2143. public function getIsInitialized()
  2144. {
  2145. return $this->_initialized;
  2146. }
  2147. }
  2148. class CHttpRequest extends CApplicationComponent
  2149. {
  2150. public $enableCookieValidation=false;
  2151. public $enableCsrfValidation=false;
  2152. public $csrfTokenName='YII_CSRF_TOKEN';
  2153. public $csrfCookie;
  2154. private $_requestUri;
  2155. private $_pathInfo;
  2156. private $_scriptFile;
  2157. private $_scriptUrl;
  2158. private $_hostInfo;
  2159. private $_baseUrl;
  2160. private $_cookies;
  2161. private $_preferredLanguage;
  2162. private $_csrfToken;
  2163. private $_deleteParams;
  2164. private $_putParams;
  2165. public function init()
  2166. {
  2167. parent::init();
  2168. $this->normalizeRequest();
  2169. }
  2170. protected function normalizeRequest()
  2171. {
  2172. // normalize request
  2173. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2174. {
  2175. if(isset($_GET))
  2176. $_GET=$this->stripSlashes($_GET);
  2177. if(isset($_POST))
  2178. $_POST=$this->stripSlashes($_POST);
  2179. if(isset($_REQUEST))
  2180. $_REQUEST=$this->stripSlashes($_REQUEST);
  2181. if(isset($_COOKIE))
  2182. $_COOKIE=$this->stripSlashes($_COOKIE);
  2183. }
  2184. if($this->enableCsrfValidation)
  2185. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2186. }
  2187. public function stripSlashes(&$data)
  2188. {
  2189. return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
  2190. }
  2191. public function getParam($name,$defaultValue=null)
  2192. {
  2193. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2194. }
  2195. public function getQuery($name,$defaultValue=null)
  2196. {
  2197. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2198. }
  2199. public function getPost($name,$defaultValue=null)
  2200. {
  2201. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2202. }
  2203. public function getDelete($name,$defaultValue=null)
  2204. {
  2205. if($this->_deleteParams===null)
  2206. $this->_deleteParams=$this->getIsDeleteRequest() ? $this->getRestParams() : array();
  2207. return isset($this->_deleteParams[$name]) ? $this->_deleteParams[$name] : $defaultValue;
  2208. }
  2209. public function getPut($name,$defaultValue=null)
  2210. {
  2211. if($this->_putParams===null)
  2212. $this->_putParams=$this->getIsPutRequest() ? $this->getRestParams() : ar