PageRenderTime 133ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 1ms

/htdocs/yii/1.1.5/framework/yiilite.php

http://github.com/pmjones/php-framework-benchmarks
PHP | 8430 lines | 8376 code | 2 blank | 52 comment | 747 complexity | 144f4d961afd3275323903e9bd527175 MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0, BSD-3-Clause, ISC, AGPL-3.0, LGPL-2.1
  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-2010 Yii Software LLC
  19. * @license http://www.yiiframework.com/license/
  20. * @version $Id: yiilite.php 2653 2010-11-14 14:23:12Z 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. private static $_aliases=array('system'=>YII_PATH,'zii'=>YII_ZII_PATH); // alias => path
  34. private static $_imports=array(); // alias => class name or directory
  35. private static $_includePaths; // list of include paths
  36. private static $_app;
  37. private static $_logger;
  38. public static function getVersion()
  39. {
  40. return '1.1.5';
  41. }
  42. public static function createWebApplication($config=null)
  43. {
  44. return self::createApplication('CWebApplication',$config);
  45. }
  46. public static function createConsoleApplication($config=null)
  47. {
  48. return self::createApplication('CConsoleApplication',$config);
  49. }
  50. public static function createApplication($class,$config=null)
  51. {
  52. return new $class($config);
  53. }
  54. public static function app()
  55. {
  56. return self::$_app;
  57. }
  58. public static function setApplication($app)
  59. {
  60. if(self::$_app===null || $app===null)
  61. self::$_app=$app;
  62. else
  63. throw new CException(Yii::t('yii','Yii application can only be created once.'));
  64. }
  65. public static function getFrameworkPath()
  66. {
  67. return YII_PATH;
  68. }
  69. public static function createComponent($config)
  70. {
  71. if(is_string($config))
  72. {
  73. $type=$config;
  74. $config=array();
  75. }
  76. else if(isset($config['class']))
  77. {
  78. $type=$config['class'];
  79. unset($config['class']);
  80. }
  81. else
  82. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  83. if(!class_exists($type,false))
  84. $type=Yii::import($type,true);
  85. if(($n=func_num_args())>1)
  86. {
  87. $args=func_get_args();
  88. if($n===2)
  89. $object=new $type($args[1]);
  90. else if($n===3)
  91. $object=new $type($args[1],$args[2]);
  92. else if($n===4)
  93. $object=new $type($args[1],$args[2],$args[3]);
  94. else
  95. {
  96. unset($args[0]);
  97. $class=new ReflectionClass($type);
  98. // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
  99. // $object=$class->newInstanceArgs($args);
  100. $object=call_user_func_array(array($class,'newInstance'),$args);
  101. }
  102. }
  103. else
  104. $object=new $type;
  105. foreach($config as $key=>$value)
  106. $object->$key=$value;
  107. return $object;
  108. }
  109. public static function import($alias,$forceInclude=false)
  110. {
  111. if(isset(self::$_imports[$alias])) // previously imported
  112. return self::$_imports[$alias];
  113. if(class_exists($alias,false) || interface_exists($alias,false))
  114. return self::$_imports[$alias]=$alias;
  115. if(($pos=strrpos($alias,'\\'))!==false) // a class name in PHP 5.3 namespace format
  116. {
  117. $namespace=str_replace('\\','.',ltrim(substr($alias,0,$pos),'\\'));
  118. if(($path=self::getPathOfAlias($namespace))!==false)
  119. {
  120. $classFile=$path.DIRECTORY_SEPARATOR.substr($alias,$pos+1).'.php';
  121. if($forceInclude)
  122. {
  123. if(is_file($classFile))
  124. require($classFile);
  125. else
  126. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file.',array('{alias}'=>$alias)));
  127. self::$_imports[$alias]=$alias;
  128. }
  129. else
  130. self::$classMap[$alias]=$classFile;
  131. return $alias;
  132. }
  133. else
  134. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory.',
  135. array('{alias}'=>$namespace)));
  136. }
  137. if(($pos=strrpos($alias,'.'))===false) // a simple class name
  138. {
  139. if($forceInclude && self::autoload($alias))
  140. self::$_imports[$alias]=$alias;
  141. return $alias;
  142. }
  143. $className=(string)substr($alias,$pos+1);
  144. $isClass=$className!=='*';
  145. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  146. return self::$_imports[$alias]=$className;
  147. if(($path=self::getPathOfAlias($alias))!==false)
  148. {
  149. if($isClass)
  150. {
  151. if($forceInclude)
  152. {
  153. if(is_file($path.'.php'))
  154. require($path.'.php');
  155. else
  156. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file.',array('{alias}'=>$alias)));
  157. self::$_imports[$alias]=$className;
  158. }
  159. else
  160. self::$classMap[$className]=$path.'.php';
  161. return $className;
  162. }
  163. else // a directory
  164. {
  165. if(self::$_includePaths===null)
  166. {
  167. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  168. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  169. unset(self::$_includePaths[$pos]);
  170. }
  171. array_unshift(self::$_includePaths,$path);
  172. if(set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  173. throw new CException(Yii::t('yii','Unable to import "{alias}". Please check your server configuration to make sure you are allowed to change PHP include_path.',array('{alias}'=>$alias)));
  174. return self::$_imports[$alias]=$path;
  175. }
  176. }
  177. else
  178. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  179. array('{alias}'=>$alias)));
  180. }
  181. public static function getPathOfAlias($alias)
  182. {
  183. if(isset(self::$_aliases[$alias]))
  184. return self::$_aliases[$alias];
  185. else if(($pos=strpos($alias,'.'))!==false)
  186. {
  187. $rootAlias=substr($alias,0,$pos);
  188. if(isset(self::$_aliases[$rootAlias]))
  189. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  190. else if(self::$_app instanceof CWebApplication)
  191. {
  192. if(self::$_app->findModule($rootAlias)!==null)
  193. return self::getPathOfAlias($alias);
  194. }
  195. }
  196. return false;
  197. }
  198. public static function setPathOfAlias($alias,$path)
  199. {
  200. if(empty($path))
  201. unset(self::$_aliases[$alias]);
  202. else
  203. self::$_aliases[$alias]=rtrim($path,'\\/');
  204. }
  205. public static function autoload($className)
  206. {
  207. // use include so that the error PHP file may appear
  208. if(isset(self::$_coreClasses[$className]))
  209. include(YII_PATH.self::$_coreClasses[$className]);
  210. else if(isset(self::$classMap[$className]))
  211. include(self::$classMap[$className]);
  212. else
  213. {
  214. if(strpos($className,'\\')===false)
  215. include($className.'.php');
  216. else // class name with namespace in PHP 5.3
  217. {
  218. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  219. if(($path=self::getPathOfAlias($namespace))!==false)
  220. include($path.'.php');
  221. else
  222. return false;
  223. }
  224. return class_exists($className,false) || interface_exists($className,false);
  225. }
  226. return true;
  227. }
  228. public static function trace($msg,$category='application')
  229. {
  230. if(YII_DEBUG)
  231. self::log($msg,CLogger::LEVEL_TRACE,$category);
  232. }
  233. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  234. {
  235. if(self::$_logger===null)
  236. self::$_logger=new CLogger;
  237. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  238. {
  239. $traces=debug_backtrace();
  240. $count=0;
  241. foreach($traces as $trace)
  242. {
  243. if(isset($trace['file'],$trace['line']))
  244. {
  245. $className=substr(basename($trace['file']),0,-4);
  246. if(!isset(self::$_coreClasses[$className]) && $className!=='YiiBase')
  247. {
  248. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  249. if(++$count>=YII_TRACE_LEVEL)
  250. break;
  251. }
  252. }
  253. }
  254. }
  255. self::$_logger->log($msg,$level,$category);
  256. }
  257. public static function beginProfile($token,$category='application')
  258. {
  259. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  260. }
  261. public static function endProfile($token,$category='application')
  262. {
  263. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  264. }
  265. public static function getLogger()
  266. {
  267. if(self::$_logger!==null)
  268. return self::$_logger;
  269. else
  270. return self::$_logger=new CLogger;
  271. }
  272. public static function powered()
  273. {
  274. return 'Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>.';
  275. }
  276. public static function t($category,$message,$params=array(),$source=null,$language=null)
  277. {
  278. if(self::$_app!==null)
  279. {
  280. if($source===null)
  281. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  282. if(($source=self::$_app->getComponent($source))!==null)
  283. $message=$source->translate($category,$message,$language);
  284. }
  285. if($params===array())
  286. return $message;
  287. if(isset($params[0])) // number choice
  288. {
  289. $message=CChoiceFormat::format($message,$params[0]);
  290. unset($params[0]);
  291. }
  292. return $params!==array() ? strtr($message,$params) : $message;
  293. }
  294. public static function registerAutoloader($callback)
  295. {
  296. spl_autoload_unregister(array('YiiBase','autoload'));
  297. spl_autoload_register($callback);
  298. spl_autoload_register(array('YiiBase','autoload'));
  299. }
  300. private static $_coreClasses=array(
  301. 'CApplication' => '/base/CApplication.php',
  302. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  303. 'CBehavior' => '/base/CBehavior.php',
  304. 'CComponent' => '/base/CComponent.php',
  305. 'CErrorEvent' => '/base/CErrorEvent.php',
  306. 'CErrorHandler' => '/base/CErrorHandler.php',
  307. 'CException' => '/base/CException.php',
  308. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  309. 'CHttpException' => '/base/CHttpException.php',
  310. 'CModel' => '/base/CModel.php',
  311. 'CModelBehavior' => '/base/CModelBehavior.php',
  312. 'CModelEvent' => '/base/CModelEvent.php',
  313. 'CModule' => '/base/CModule.php',
  314. 'CSecurityManager' => '/base/CSecurityManager.php',
  315. 'CStatePersister' => '/base/CStatePersister.php',
  316. 'CApcCache' => '/caching/CApcCache.php',
  317. 'CCache' => '/caching/CCache.php',
  318. 'CDbCache' => '/caching/CDbCache.php',
  319. 'CDummyCache' => '/caching/CDummyCache.php',
  320. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  321. 'CFileCache' => '/caching/CFileCache.php',
  322. 'CMemCache' => '/caching/CMemCache.php',
  323. 'CWinCache' => '/caching/CWinCache.php',
  324. 'CXCache' => '/caching/CXCache.php',
  325. 'CZendDataCache' => '/caching/CZendDataCache.php',
  326. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  327. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  328. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  329. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  330. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  331. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  332. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  333. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  334. 'CConfiguration' => '/collections/CConfiguration.php',
  335. 'CList' => '/collections/CList.php',
  336. 'CListIterator' => '/collections/CListIterator.php',
  337. 'CMap' => '/collections/CMap.php',
  338. 'CMapIterator' => '/collections/CMapIterator.php',
  339. 'CQueue' => '/collections/CQueue.php',
  340. 'CQueueIterator' => '/collections/CQueueIterator.php',
  341. 'CStack' => '/collections/CStack.php',
  342. 'CStackIterator' => '/collections/CStackIterator.php',
  343. 'CTypedList' => '/collections/CTypedList.php',
  344. 'CTypedMap' => '/collections/CTypedMap.php',
  345. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  346. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  347. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  348. 'CHelpCommand' => '/console/CHelpCommand.php',
  349. 'CDbCommand' => '/db/CDbCommand.php',
  350. 'CDbConnection' => '/db/CDbConnection.php',
  351. 'CDbDataReader' => '/db/CDbDataReader.php',
  352. 'CDbException' => '/db/CDbException.php',
  353. 'CDbTransaction' => '/db/CDbTransaction.php',
  354. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  355. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  356. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  357. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  358. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  359. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  360. 'CDbExpression' => '/db/schema/CDbExpression.php',
  361. 'CDbSchema' => '/db/schema/CDbSchema.php',
  362. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  363. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  364. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  365. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  366. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  367. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  368. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  369. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  370. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  371. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  372. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  373. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  374. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  375. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  376. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  377. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  378. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  379. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  380. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  381. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  382. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  383. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  384. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  385. 'CLocale' => '/i18n/CLocale.php',
  386. 'CMessageSource' => '/i18n/CMessageSource.php',
  387. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  388. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  389. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  390. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  391. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  392. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  393. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  394. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  395. 'CLogFilter' => '/logging/CLogFilter.php',
  396. 'CLogRoute' => '/logging/CLogRoute.php',
  397. 'CLogRouter' => '/logging/CLogRouter.php',
  398. 'CLogger' => '/logging/CLogger.php',
  399. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  400. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  401. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  402. 'CFileHelper' => '/utils/CFileHelper.php',
  403. 'CFormatter' => '/utils/CFormatter.php',
  404. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  405. 'CPropertyValue' => '/utils/CPropertyValue.php',
  406. 'CTimestamp' => '/utils/CTimestamp.php',
  407. 'CVarDumper' => '/utils/CVarDumper.php',
  408. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  409. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  410. 'CCompareValidator' => '/validators/CCompareValidator.php',
  411. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  412. 'CEmailValidator' => '/validators/CEmailValidator.php',
  413. 'CExistValidator' => '/validators/CExistValidator.php',
  414. 'CFileValidator' => '/validators/CFileValidator.php',
  415. 'CFilterValidator' => '/validators/CFilterValidator.php',
  416. 'CInlineValidator' => '/validators/CInlineValidator.php',
  417. 'CNumberValidator' => '/validators/CNumberValidator.php',
  418. 'CRangeValidator' => '/validators/CRangeValidator.php',
  419. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  420. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  421. 'CSafeValidator' => '/validators/CSafeValidator.php',
  422. 'CStringValidator' => '/validators/CStringValidator.php',
  423. 'CTypeValidator' => '/validators/CTypeValidator.php',
  424. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  425. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  426. 'CUrlValidator' => '/validators/CUrlValidator.php',
  427. 'CValidator' => '/validators/CValidator.php',
  428. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  429. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  430. 'CAssetManager' => '/web/CAssetManager.php',
  431. 'CBaseController' => '/web/CBaseController.php',
  432. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  433. 'CClientScript' => '/web/CClientScript.php',
  434. 'CController' => '/web/CController.php',
  435. 'CDataProvider' => '/web/CDataProvider.php',
  436. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  437. 'CExtController' => '/web/CExtController.php',
  438. 'CFormModel' => '/web/CFormModel.php',
  439. 'CHttpCookie' => '/web/CHttpCookie.php',
  440. 'CHttpRequest' => '/web/CHttpRequest.php',
  441. 'CHttpSession' => '/web/CHttpSession.php',
  442. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  443. 'COutputEvent' => '/web/COutputEvent.php',
  444. 'CPagination' => '/web/CPagination.php',
  445. 'CSort' => '/web/CSort.php',
  446. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  447. 'CTheme' => '/web/CTheme.php',
  448. 'CThemeManager' => '/web/CThemeManager.php',
  449. 'CUploadedFile' => '/web/CUploadedFile.php',
  450. 'CUrlManager' => '/web/CUrlManager.php',
  451. 'CWebApplication' => '/web/CWebApplication.php',
  452. 'CWebModule' => '/web/CWebModule.php',
  453. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  454. 'CAction' => '/web/actions/CAction.php',
  455. 'CInlineAction' => '/web/actions/CInlineAction.php',
  456. 'CViewAction' => '/web/actions/CViewAction.php',
  457. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  458. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  459. 'CAuthItem' => '/web/auth/CAuthItem.php',
  460. 'CAuthManager' => '/web/auth/CAuthManager.php',
  461. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  462. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  463. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  464. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  465. 'CWebUser' => '/web/auth/CWebUser.php',
  466. 'CFilter' => '/web/filters/CFilter.php',
  467. 'CFilterChain' => '/web/filters/CFilterChain.php',
  468. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  469. 'CForm' => '/web/form/CForm.php',
  470. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  471. 'CFormElement' => '/web/form/CFormElement.php',
  472. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  473. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  474. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  475. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  476. 'CHtml' => '/web/helpers/CHtml.php',
  477. 'CJSON' => '/web/helpers/CJSON.php',
  478. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  479. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  480. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  481. 'CWebService' => '/web/services/CWebService.php',
  482. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  483. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  484. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  485. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  486. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  487. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  488. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  489. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  490. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  491. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  492. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  493. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  494. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  495. 'COutputCache' => '/web/widgets/COutputCache.php',
  496. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  497. 'CStarRating' => '/web/widgets/CStarRating.php',
  498. 'CTabView' => '/web/widgets/CTabView.php',
  499. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  500. 'CTreeView' => '/web/widgets/CTreeView.php',
  501. 'CWidget' => '/web/widgets/CWidget.php',
  502. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  503. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  504. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  505. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  506. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  507. );
  508. }
  509. spl_autoload_register(array('YiiBase','autoload'));
  510. class Yii extends YiiBase
  511. {
  512. }
  513. class CComponent
  514. {
  515. private $_e;
  516. private $_m;
  517. public function __get($name)
  518. {
  519. $getter='get'.$name;
  520. if(method_exists($this,$getter))
  521. return $this->$getter();
  522. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  523. {
  524. // duplicating getEventHandlers() here for performance
  525. $name=strtolower($name);
  526. if(!isset($this->_e[$name]))
  527. $this->_e[$name]=new CList;
  528. return $this->_e[$name];
  529. }
  530. else if(isset($this->_m[$name]))
  531. return $this->_m[$name];
  532. else if(is_array($this->_m))
  533. {
  534. foreach($this->_m as $object)
  535. {
  536. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  537. return $object->$name;
  538. }
  539. }
  540. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  541. array('{class}'=>get_class($this), '{property}'=>$name)));
  542. }
  543. public function __set($name,$value)
  544. {
  545. $setter='set'.$name;
  546. if(method_exists($this,$setter))
  547. return $this->$setter($value);
  548. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  549. {
  550. // duplicating getEventHandlers() here for performance
  551. $name=strtolower($name);
  552. if(!isset($this->_e[$name]))
  553. $this->_e[$name]=new CList;
  554. return $this->_e[$name]->add($value);
  555. }
  556. else if(is_array($this->_m))
  557. {
  558. foreach($this->_m as $object)
  559. {
  560. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  561. return $object->$name=$value;
  562. }
  563. }
  564. if(method_exists($this,'get'.$name))
  565. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  566. array('{class}'=>get_class($this), '{property}'=>$name)));
  567. else
  568. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  569. array('{class}'=>get_class($this), '{property}'=>$name)));
  570. }
  571. public function __isset($name)
  572. {
  573. $getter='get'.$name;
  574. if(method_exists($this,$getter))
  575. return $this->$getter()!==null;
  576. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  577. {
  578. $name=strtolower($name);
  579. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  580. }
  581. else if(is_array($this->_m))
  582. {
  583. if(isset($this->_m[$name]))
  584. return true;
  585. foreach($this->_m as $object)
  586. {
  587. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  588. return true;
  589. }
  590. }
  591. return false;
  592. }
  593. public function __unset($name)
  594. {
  595. $setter='set'.$name;
  596. if(method_exists($this,$setter))
  597. $this->$setter(null);
  598. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  599. unset($this->_e[strtolower($name)]);
  600. else if(is_array($this->_m))
  601. {
  602. if(isset($this->_m[$name]))
  603. $this->detachBehavior($name);
  604. else
  605. {
  606. foreach($this->_m as $object)
  607. {
  608. if($object->getEnabled())
  609. {
  610. if(property_exists($object,$name))
  611. return $object->$name=null;
  612. else if($object->canSetProperty($name))
  613. return $object->$setter(null);
  614. }
  615. }
  616. }
  617. }
  618. else if(method_exists($this,'get'.$name))
  619. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  620. array('{class}'=>get_class($this), '{property}'=>$name)));
  621. }
  622. public function __call($name,$parameters)
  623. {
  624. if($this->_m!==null)
  625. {
  626. foreach($this->_m as $object)
  627. {
  628. if($object->getEnabled() && method_exists($object,$name))
  629. return call_user_func_array(array($object,$name),$parameters);
  630. }
  631. }
  632. if(class_exists('Closure', false) && $this->$name instanceof Closure)
  633. return call_user_func_array($this->$name, $parameters);
  634. throw new CException(Yii::t('yii','{class} does not have a method named "{name}".',
  635. array('{class}'=>get_class($this), '{name}'=>$name)));
  636. }
  637. public function asa($behavior)
  638. {
  639. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  640. }
  641. public function attachBehaviors($behaviors)
  642. {
  643. foreach($behaviors as $name=>$behavior)
  644. $this->attachBehavior($name,$behavior);
  645. }
  646. public function detachBehaviors()
  647. {
  648. if($this->_m!==null)
  649. {
  650. foreach($this->_m as $name=>$behavior)
  651. $this->detachBehavior($name);
  652. $this->_m=null;
  653. }
  654. }
  655. public function attachBehavior($name,$behavior)
  656. {
  657. if(!($behavior instanceof IBehavior))
  658. $behavior=Yii::createComponent($behavior);
  659. $behavior->setEnabled(true);
  660. $behavior->attach($this);
  661. return $this->_m[$name]=$behavior;
  662. }
  663. public function detachBehavior($name)
  664. {
  665. if(isset($this->_m[$name]))
  666. {
  667. $this->_m[$name]->detach($this);
  668. $behavior=$this->_m[$name];
  669. unset($this->_m[$name]);
  670. return $behavior;
  671. }
  672. }
  673. public function enableBehaviors()
  674. {
  675. if($this->_m!==null)
  676. {
  677. foreach($this->_m as $behavior)
  678. $behavior->setEnabled(true);
  679. }
  680. }
  681. public function disableBehaviors()
  682. {
  683. if($this->_m!==null)
  684. {
  685. foreach($this->_m as $behavior)
  686. $behavior->setEnabled(false);
  687. }
  688. }
  689. public function enableBehavior($name)
  690. {
  691. if(isset($this->_m[$name]))
  692. $this->_m[$name]->setEnabled(true);
  693. }
  694. public function disableBehavior($name)
  695. {
  696. if(isset($this->_m[$name]))
  697. $this->_m[$name]->setEnabled(false);
  698. }
  699. public function hasProperty($name)
  700. {
  701. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  702. }
  703. public function canGetProperty($name)
  704. {
  705. return method_exists($this,'get'.$name);
  706. }
  707. public function canSetProperty($name)
  708. {
  709. return method_exists($this,'set'.$name);
  710. }
  711. public function hasEvent($name)
  712. {
  713. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  714. }
  715. public function hasEventHandler($name)
  716. {
  717. $name=strtolower($name);
  718. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  719. }
  720. public function getEventHandlers($name)
  721. {
  722. if($this->hasEvent($name))
  723. {
  724. $name=strtolower($name);
  725. if(!isset($this->_e[$name]))
  726. $this->_e[$name]=new CList;
  727. return $this->_e[$name];
  728. }
  729. else
  730. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  731. array('{class}'=>get_class($this), '{event}'=>$name)));
  732. }
  733. public function attachEventHandler($name,$handler)
  734. {
  735. $this->getEventHandlers($name)->add($handler);
  736. }
  737. public function detachEventHandler($name,$handler)
  738. {
  739. if($this->hasEventHandler($name))
  740. return $this->getEventHandlers($name)->remove($handler)!==false;
  741. else
  742. return false;
  743. }
  744. public function raiseEvent($name,$event)
  745. {
  746. $name=strtolower($name);
  747. if(isset($this->_e[$name]))
  748. {
  749. foreach($this->_e[$name] as $handler)
  750. {
  751. if(is_string($handler))
  752. call_user_func($handler,$event);
  753. else if(is_callable($handler,true))
  754. {
  755. if(is_array($handler))
  756. {
  757. // an array: 0 - object, 1 - method name
  758. list($object,$method)=$handler;
  759. if(is_string($object)) // static method call
  760. call_user_func($handler,$event);
  761. else if(method_exists($object,$method))
  762. $object->$method($event);
  763. else
  764. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  765. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  766. }
  767. else // PHP 5.3: anonymous function
  768. call_user_func($handler,$event);
  769. }
  770. else
  771. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  772. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  773. // stop further handling if param.handled is set true
  774. if(($event instanceof CEvent) && $event->handled)
  775. return;
  776. }
  777. }
  778. else if(YII_DEBUG && !$this->hasEvent($name))
  779. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  780. array('{class}'=>get_class($this), '{event}'=>$name)));
  781. }
  782. public function evaluateExpression($_expression_,$_data_=array())
  783. {
  784. if(is_string($_expression_))
  785. {
  786. extract($_data_);
  787. return eval('return '.$_expression_.';');
  788. }
  789. else
  790. {
  791. $_data_[]=$this;
  792. return call_user_func_array($_expression_, $_data_);
  793. }
  794. }
  795. }
  796. class CEvent extends CComponent
  797. {
  798. public $sender;
  799. public $handled=false;
  800. public function __construct($sender=null)
  801. {
  802. $this->sender=$sender;
  803. }
  804. }
  805. class CEnumerable
  806. {
  807. }
  808. abstract class CModule extends CComponent
  809. {
  810. public $preload=array();
  811. public $behaviors=array();
  812. private $_id;
  813. private $_parentModule;
  814. private $_basePath;
  815. private $_modulePath;
  816. private $_params;
  817. private $_modules=array();
  818. private $_moduleConfig=array();
  819. private $_components=array();
  820. private $_componentConfig=array();
  821. public function __construct($id,$parent,$config=null)
  822. {
  823. $this->_id=$id;
  824. $this->_parentModule=$parent;
  825. // set basePath at early as possible to avoid trouble
  826. if(is_string($config))
  827. $config=require($config);
  828. if(isset($config['basePath']))
  829. {
  830. $this->setBasePath($config['basePath']);
  831. unset($config['basePath']);
  832. }
  833. Yii::setPathOfAlias($id,$this->getBasePath());
  834. $this->preinit();
  835. $this->configure($config);
  836. $this->attachBehaviors($this->behaviors);
  837. $this->preloadComponents();
  838. $this->init();
  839. }
  840. public function __get($name)
  841. {
  842. if($this->hasComponent($name))
  843. return $this->getComponent($name);
  844. else
  845. return parent::__get($name);
  846. }
  847. public function __isset($name)
  848. {
  849. if($this->hasComponent($name))
  850. return $this->getComponent($name)!==null;
  851. else
  852. return parent::__isset($name);
  853. }
  854. public function getId()
  855. {
  856. return $this->_id;
  857. }
  858. public function setId($id)
  859. {
  860. $this->_id=$id;
  861. }
  862. public function getBasePath()
  863. {
  864. if($this->_basePath===null)
  865. {
  866. $class=new ReflectionClass(get_class($this));
  867. $this->_basePath=dirname($class->getFileName());
  868. }
  869. return $this->_basePath;
  870. }
  871. public function setBasePath($path)
  872. {
  873. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  874. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  875. array('{path}'=>$path)));
  876. }
  877. public function getParams()
  878. {
  879. if($this->_params!==null)
  880. return $this->_params;
  881. else
  882. {
  883. $this->_params=new CAttributeCollection;
  884. $this->_params->caseSensitive=true;
  885. return $this->_params;
  886. }
  887. }
  888. public function setParams($value)
  889. {
  890. $params=$this->getParams();
  891. foreach($value as $k=>$v)
  892. $params->add($k,$v);
  893. }
  894. public function getModulePath()
  895. {
  896. if($this->_modulePath!==null)
  897. return $this->_modulePath;
  898. else
  899. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  900. }
  901. public function setModulePath($value)
  902. {
  903. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  904. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  905. array('{path}'=>$value)));
  906. }
  907. public function setImport($aliases)
  908. {
  909. foreach($aliases as $alias)
  910. Yii::import($alias);
  911. }
  912. public function setAliases($mappings)
  913. {
  914. foreach($mappings as $name=>$alias)
  915. {
  916. if(($path=Yii::getPathOfAlias($alias))!==false)
  917. Yii::setPathOfAlias($name,$path);
  918. else
  919. Yii::setPathOfAlias($name,$alias);
  920. }
  921. }
  922. public function getParentModule()
  923. {
  924. return $this->_parentModule;
  925. }
  926. public function getModule($id)
  927. {
  928. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  929. return $this->_modules[$id];
  930. else if(isset($this->_moduleConfig[$id]))
  931. {
  932. $config=$this->_moduleConfig[$id];
  933. if(!isset($config['enabled']) || $config['enabled'])
  934. {
  935. $class=$config['class'];
  936. unset($config['class'], $config['enabled']);
  937. if($this===Yii::app())
  938. $module=Yii::createComponent($class,$id,null,$config);
  939. else
  940. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  941. return $this->_modules[$id]=$module;
  942. }
  943. }
  944. }
  945. public function hasModule($id)
  946. {
  947. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  948. }
  949. public function getModules()
  950. {
  951. return $this->_moduleConfig;
  952. }
  953. public function setModules($modules)
  954. {
  955. foreach($modules as $id=>$module)
  956. {
  957. if(is_int($id))
  958. {
  959. $id=$module;
  960. $module=array();
  961. }
  962. if(!isset($module['class']))
  963. {
  964. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  965. $module['class']=$id.'.'.ucfirst($id).'Module';
  966. }
  967. if(isset($this->_moduleConfig[$id]))
  968. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  969. else
  970. $this->_moduleConfig[$id]=$module;
  971. }
  972. }
  973. public function hasComponent($id)
  974. {
  975. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  976. }
  977. public function getComponent($id,$createIfNull=true)
  978. {
  979. if(isset($this->_components[$id]))
  980. return $this->_components[$id];
  981. else if(isset($this->_componentConfig[$id]) && $createIfNull)
  982. {
  983. $config=$this->_componentConfig[$id];
  984. if(!isset($config['enabled']) || $config['enabled'])
  985. {
  986. unset($config['enabled']);
  987. $component=Yii::createComponent($config);
  988. $component->init();
  989. return $this->_components[$id]=$component;
  990. }
  991. }
  992. }
  993. public function setComponent($id,$component)
  994. {
  995. if($component===null)
  996. unset($this->_components[$id]);
  997. else
  998. {
  999. $this->_components[$id]=$component;
  1000. if(!$component->getIsInitialized())
  1001. $component->init();
  1002. }
  1003. }
  1004. public function getComponents($loadedOnly=true)
  1005. {
  1006. if($loadedOnly)
  1007. return $this->_components;
  1008. else
  1009. return array_merge($this->_componentConfig, $this->_components);
  1010. }
  1011. public function setComponents($components,$merge=true)
  1012. {
  1013. foreach($components as $id=>$component)
  1014. {
  1015. if($component instanceof IApplicationComponent)
  1016. $this->setComponent($id,$component);
  1017. else if(isset($this->_componentConfig[$id]) && $merge)
  1018. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1019. else
  1020. $this->_componentConfig[$id]=$component;
  1021. }
  1022. }
  1023. public function configure($config)
  1024. {
  1025. if(is_array($config))
  1026. {
  1027. foreach($config as $key=>$value)
  1028. $this->$key=$value;
  1029. }
  1030. }
  1031. protected function preloadComponents()
  1032. {
  1033. foreach($this->preload as $id)
  1034. $this->getComponent($id);
  1035. }
  1036. protected function preinit()
  1037. {
  1038. }
  1039. protected function init()
  1040. {
  1041. }
  1042. }
  1043. abstract class CApplication extends CModule
  1044. {
  1045. public $name='My Application';
  1046. public $charset='UTF-8';
  1047. public $sourceLanguage='en_us';
  1048. private $_id;
  1049. private $_basePath;
  1050. private $_runtimePath;
  1051. private $_extensionPath;
  1052. private $_globalState;
  1053. private $_stateChanged;
  1054. private $_ended=false;
  1055. private $_language;
  1056. abstract public function processRequest();
  1057. public function __construct($config=null)
  1058. {
  1059. Yii::setApplication($this);
  1060. // set basePath at early as possible to avoid trouble
  1061. if(is_string($config))
  1062. $config=require($config);
  1063. if(isset($config['basePath']))
  1064. {
  1065. $this->setBasePath($config['basePath']);
  1066. unset($config['basePath']);
  1067. }
  1068. else
  1069. $this->setBasePath('protected');
  1070. Yii::setPathOfAlias('application',$this->getBasePath());
  1071. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1072. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1073. $this->preinit();
  1074. $this->initSystemHandlers();
  1075. $this->registerCoreComponents();
  1076. $this->configure($config);
  1077. $this->attachBehaviors($this->behaviors);
  1078. $this->preloadComponents();
  1079. $this->init();
  1080. }
  1081. public function run()
  1082. {
  1083. if($this->hasEventHandler('onBeginRequest'))
  1084. $this->onBeginRequest(new CEvent($this));
  1085. $this->processRequest();
  1086. if($this->hasEventHandler('onEndRequest'))
  1087. $this->onEndRequest(new CEvent($this));
  1088. }
  1089. public function end($status=0, $exit=true)
  1090. {
  1091. if($this->hasEventHandler('onEndRequest'))
  1092. $this->onEndRequest(new CEvent($this));
  1093. if($exit)
  1094. exit($status);
  1095. }
  1096. public function onBeginRequest($event)
  1097. {
  1098. $this->raiseEvent('onBeginRequest',$event);
  1099. }
  1100. public function onEndRequest($event)
  1101. {
  1102. if(!$this->_ended)
  1103. {
  1104. $this->_ended=true;
  1105. $this->raiseEvent('onEndRequest',$event);
  1106. }
  1107. }
  1108. public function getId()
  1109. {
  1110. if($this->_id!==null)
  1111. return $this->_id;
  1112. else
  1113. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1114. }
  1115. public function setId($id)
  1116. {
  1117. $this->_id=$id;
  1118. }
  1119. public function getBasePath()
  1120. {
  1121. return $this->_basePath;
  1122. }
  1123. public function setBasePath($path)
  1124. {
  1125. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1126. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1127. array('{path}'=>$path)));
  1128. }
  1129. public function getRuntimePath()
  1130. {
  1131. if($this->_runtimePath!==null)
  1132. return $this->_runtimePath;
  1133. else
  1134. {
  1135. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1136. return $this->_runtimePath;
  1137. }
  1138. }
  1139. public function setRuntimePath($path)
  1140. {
  1141. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1142. 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.',
  1143. array('{path}'=>$path)));
  1144. $this->_runtimePath=$runtimePath;
  1145. }
  1146. public function getExtensionPath()
  1147. {
  1148. return Yii::getPathOfAlias('ext');
  1149. }
  1150. public function setExtensionPath($path)
  1151. {
  1152. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1153. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1154. array('{path}'=>$path)));
  1155. Yii::setPathOfAlias('ext',$extensionPath);
  1156. }
  1157. public function getLanguage()
  1158. {
  1159. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1160. }
  1161. public function setLanguage($language)
  1162. {
  1163. $this->_language=$language;
  1164. }
  1165. public function getTimeZone()
  1166. {
  1167. return date_default_timezone_get();
  1168. }
  1169. public function setTimeZone($value)
  1170. {
  1171. date_default_timezone_set($value);
  1172. }
  1173. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1174. {
  1175. if($srcLanguage===null)
  1176. $srcLanguage=$this->sourceLanguage;
  1177. if($language===null)
  1178. $language=$this->getLanguage();
  1179. if($language===$srcLanguage)
  1180. return $srcFile;
  1181. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1182. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1183. }
  1184. public function getLocale($localeID=null)
  1185. {
  1186. return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID);
  1187. }
  1188. public function getLocaleDataPath()
  1189. {
  1190. return CLocale::$dataPath===null ? Yii::getPathOfAlias('system.i18n.data') : CLocale::$dataPath;
  1191. }
  1192. public function setLocaleDataPath($value)
  1193. {
  1194. CLocale::$dataPath=$value;
  1195. }
  1196. public function getNumberFormatter()
  1197. {
  1198. return $this->getLocale()->getNumberFormatter();
  1199. }
  1200. public function getDateFormatter()
  1201. {
  1202. return $this->getLocale()->getDateFormatter();
  1203. }
  1204. public function getDb()
  1205. {
  1206. return $this->getComponent('db');
  1207. }
  1208. public function getErrorHandler()
  1209. {
  1210. return $this->getComponent('errorHandler');
  1211. }
  1212. public function getSecurityManager()
  1213. {
  1214. return $this->getComponent('securityManager');
  1215. }
  1216. public function getStatePersister()
  1217. {
  1218. return $this->getComponent('statePersister');
  1219. }
  1220. public function getCache()
  1221. {
  1222. return $this->getComponent('cache');
  1223. }
  1224. public function getCoreMessages()
  1225. {
  1226. return $this->getComponent('coreMessages');
  1227. }
  1228. public function getMessages()
  1229. {
  1230. return $this->getComponent('messages');
  1231. }
  1232. public function getRequest()
  1233. {
  1234. return $this->getComponent('request');
  1235. }
  1236. public function getUrlManager()
  1237. {
  1238. return $this->getComponent('urlManager');
  1239. }
  1240. public function getGlobalState($key,$defaultValue=null)
  1241. {
  1242. if($this->_globalState===null)
  1243. $this->loadGlobalState();
  1244. if(isset($this->_globalState[$key]))
  1245. return $this->_globalState[$key];
  1246. else
  1247. return $defaultValue;
  1248. }
  1249. public function setGlobalState($key,$value,$defaultValue=null)
  1250. {
  1251. if($this->_globalState===null)
  1252. $this->loadGlobalState();
  1253. $changed=$this->_stateChanged;
  1254. if($value===$defaultValue)
  1255. {
  1256. if(isset($this->_globalState[$key]))
  1257. {
  1258. unset($this->_globalState[$key]);
  1259. $this->_stateChanged=true;
  1260. }
  1261. }
  1262. else if(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1263. {
  1264. $this->_globalState[$key]=$value;
  1265. $this->_stateChanged=true;
  1266. }
  1267. if($this->_stateChanged!==$changed)
  1268. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1269. }
  1270. public function clearGlobalState($key)
  1271. {
  1272. $this->setGlobalState($key,true,true);
  1273. }
  1274. public function loadGlobalState()
  1275. {
  1276. $persister=$this->getStatePersister();
  1277. if(($this->_globalState=$persister->load())===null)
  1278. $this->_globalState=array();
  1279. $this->_stateChanged=false;
  1280. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1281. }
  1282. public function saveGlobalState()
  1283. {
  1284. if($this->_stateChanged)
  1285. {
  1286. $this->_stateChanged=false;
  1287. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1288. $this->getStatePersister()->save($this->_globalState);
  1289. }
  1290. }
  1291. public function handleException($exception)
  1292. {
  1293. // disable error capturing to avoid recursive errors
  1294. restore_error_handler();
  1295. restore_exception_handler();
  1296. $category='exception.'.get_class($exception);
  1297. if($exception instanceof CHttpException)
  1298. $category.='.'.$exception->statusCode;
  1299. // php <5.2 doesn't support string conversion auto-magically
  1300. $message=$exception->__toString();
  1301. if(isset($_SERVER['REQUEST_URI']))
  1302. $message.=' REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1303. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1304. try
  1305. {
  1306. $event=new CExceptionEvent($this,$exception);
  1307. $this->onException($event);
  1308. if(!$event->handled)
  1309. {
  1310. // try an error handler
  1311. if(($handler=$this->getErrorHandler())!==null)
  1312. $handler->handle($event);
  1313. else
  1314. $this->displayException($exception);
  1315. }
  1316. }
  1317. catch(Exception $e)
  1318. {
  1319. $this->displayException($e);
  1320. }
  1321. try
  1322. {
  1323. $this->end(1);
  1324. }
  1325. catch(Exception $e)
  1326. {
  1327. // use the most primitive way to log error
  1328. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1329. $msg .= $e->getTraceAsString()."\n";
  1330. $msg .= "Previous exception:\n";
  1331. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1332. $msg .= $exception->getTraceAsString()."\n";
  1333. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1334. error_log($msg);
  1335. exit(1);
  1336. }
  1337. }
  1338. public function handleError($code,$message,$file,$line)
  1339. {
  1340. if($code & error_reporting())
  1341. {
  1342. // disable error capturing to avoid recursive errors
  1343. restore_error_handler();
  1344. restore_exception_handler();
  1345. $log="$message ($file:$line)\nStack trace:\n";
  1346. $trace=debug_backtrace();
  1347. // skip the first 3 stacks as they do not tell the error position
  1348. if(count($trace)>3)
  1349. $trace=array_slice($trace,3);
  1350. foreach($trace as $i=>$t)
  1351. {
  1352. if(!isset($t['file']))
  1353. $t['file']='unknown';
  1354. if(!isset($t['line']))
  1355. $t['line']=0;
  1356. if(!isset($t['function']))
  1357. $t['function']='unknown';
  1358. $log.="#$i {$t['file']}({$t['line']}): ";
  1359. if(isset($t['object']) && is_object($t['object']))
  1360. $log.=get_class($t['object']).'->';
  1361. $log.="{$t['function']}()\n";
  1362. }
  1363. if(isset($_SERVER['REQUEST_URI']))
  1364. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1365. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1366. try
  1367. {
  1368. Yii::import('CErrorEvent',true);
  1369. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1370. $this->onError($event);
  1371. if(!$event->handled)
  1372. {
  1373. // try an error handler
  1374. if(($handler=$this->getErrorHandler())!==null)
  1375. $handler->handle($event);
  1376. else
  1377. $this->displayError($code,$message,$file,$line);
  1378. }
  1379. }
  1380. catch(Exception $e)
  1381. {
  1382. $this->displayException($e);
  1383. }
  1384. try
  1385. {
  1386. $this->end(1);
  1387. }
  1388. catch(Exception $e)
  1389. {
  1390. // use the most primitive way to log error
  1391. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1392. $msg .= $e->getTraceAsString()."\n";
  1393. $msg .= "Previous error:\n";
  1394. $msg .= $log."\n";
  1395. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1396. error_log($msg);
  1397. exit(1);
  1398. }
  1399. }
  1400. }
  1401. public function onException($event)
  1402. {
  1403. $this->raiseEvent('onException',$event);
  1404. }
  1405. public function onError($event)
  1406. {
  1407. $this->raiseEvent('onError',$event);
  1408. }
  1409. public function displayError($code,$message,$file,$line)
  1410. {
  1411. if(YII_DEBUG)
  1412. {
  1413. echo "<h1>PHP Error [$code]</h1>\n";
  1414. echo "<p>$message ($file:$line)</p>\n";
  1415. echo '<pre>';
  1416. debug_print_backtrace();
  1417. echo '</pre>';
  1418. }
  1419. else
  1420. {
  1421. echo "<h1>PHP Error [$code]</h1>\n";
  1422. echo "<p>$message</p>\n";
  1423. }
  1424. }
  1425. public function displayException($exception)
  1426. {
  1427. if(YII_DEBUG)
  1428. {
  1429. echo '<h1>'.get_class($exception)."</h1>\n";
  1430. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1431. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1432. }
  1433. else
  1434. {
  1435. echo '<h1>'.get_class($exception)."</h1>\n";
  1436. echo '<p>'.$exception->getMessage().'</p>';
  1437. }
  1438. }
  1439. protected function initSystemHandlers()
  1440. {
  1441. if(YII_ENABLE_EXCEPTION_HANDLER)
  1442. set_exception_handler(array($this,'handleException'));
  1443. if(YII_ENABLE_ERROR_HANDLER)
  1444. set_error_handler(array($this,'handleError'),error_reporting());
  1445. }
  1446. protected function registerCoreComponents()
  1447. {
  1448. $components=array(
  1449. 'coreMessages'=>array(
  1450. 'class'=>'CPhpMessageSource',
  1451. 'language'=>'en_us',
  1452. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1453. ),
  1454. 'db'=>array(
  1455. 'class'=>'CDbConnection',
  1456. ),
  1457. 'messages'=>array(
  1458. 'class'=>'CPhpMessageSource',
  1459. ),
  1460. 'errorHandler'=>array(
  1461. 'class'=>'CErrorHandler',
  1462. ),
  1463. 'securityManager'=>array(
  1464. 'class'=>'CSecurityManager',
  1465. ),
  1466. 'statePersister'=>array(
  1467. 'class'=>'CStatePersister',
  1468. ),
  1469. 'urlManager'=>array(
  1470. 'class'=>'CUrlManager',
  1471. ),
  1472. 'request'=>array(
  1473. 'class'=>'CHttpRequest',
  1474. ),
  1475. 'format'=>array(
  1476. 'class'=>'CFormatter',
  1477. ),
  1478. );
  1479. $this->setComponents($components);
  1480. }
  1481. }
  1482. class CWebApplication extends CApplication
  1483. {
  1484. public $defaultController='site';
  1485. public $layout='main';
  1486. public $controllerMap=array();
  1487. public $catchAllRequest;
  1488. private $_controllerPath;
  1489. private $_viewPath;
  1490. private $_systemViewPath;
  1491. private $_layoutPath;
  1492. private $_controller;
  1493. private $_homeUrl;
  1494. private $_theme;
  1495. public function processRequest()
  1496. {
  1497. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1498. {
  1499. $route=$this->catchAllRequest[0];
  1500. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1501. $_GET[$name]=$value;
  1502. }
  1503. else
  1504. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1505. $this->runController($route);
  1506. }
  1507. protected function registerCoreComponents()
  1508. {
  1509. parent::registerCoreComponents();
  1510. $components=array(
  1511. 'session'=>array(
  1512. 'class'=>'CHttpSession',
  1513. ),
  1514. 'assetManager'=>array(
  1515. 'class'=>'CAssetManager',
  1516. ),
  1517. 'user'=>array(
  1518. 'class'=>'CWebUser',
  1519. ),
  1520. 'themeManager'=>array(
  1521. 'class'=>'CThemeManager',
  1522. ),
  1523. 'authManager'=>array(
  1524. 'class'=>'CPhpAuthManager',
  1525. ),
  1526. 'clientScript'=>array(
  1527. 'class'=>'CClientScript',
  1528. ),
  1529. 'widgetFactory'=>array(
  1530. 'class'=>'CWidgetFactory',
  1531. ),
  1532. );
  1533. $this->setComponents($components);
  1534. }
  1535. public function getAuthManager()
  1536. {
  1537. return $this->getComponent('authManager');
  1538. }
  1539. public function getAssetManager()
  1540. {
  1541. return $this->getComponent('assetManager');
  1542. }
  1543. public function getSession()
  1544. {
  1545. return $this->getComponent('session');
  1546. }
  1547. public function getUser()
  1548. {
  1549. return $this->getComponent('user');
  1550. }
  1551. public function getViewRenderer()
  1552. {
  1553. return $this->getComponent('viewRenderer');
  1554. }
  1555. public function getClientScript()
  1556. {
  1557. return $this->getComponent('clientScript');
  1558. }
  1559. public function getWidgetFactory()
  1560. {
  1561. return $this->getComponent('widgetFactory');
  1562. }
  1563. public function getThemeManager()
  1564. {
  1565. return $this->getComponent('themeManager');
  1566. }
  1567. public function getTheme()
  1568. {
  1569. if(is_string($this->_theme))
  1570. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1571. return $this->_theme;
  1572. }
  1573. public function setTheme($value)
  1574. {
  1575. $this->_theme=$value;
  1576. }
  1577. public function createUrl($route,$params=array(),$ampersand='&')
  1578. {
  1579. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1580. }
  1581. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1582. {
  1583. return $this->getRequest()->getHostInfo($schema).$this->createUrl($route,$params,$ampersand);
  1584. }
  1585. public function getBaseUrl($absolute=false)
  1586. {
  1587. return $this->getRequest()->getBaseUrl($absolute);
  1588. }
  1589. public function getHomeUrl()
  1590. {
  1591. if($this->_homeUrl===null)
  1592. {
  1593. if($this->getUrlManager()->showScriptName)
  1594. return $this->getRequest()->getScriptUrl();
  1595. else
  1596. return $this->getRequest()->getBaseUrl().'/';
  1597. }
  1598. else
  1599. return $this->_homeUrl;
  1600. }
  1601. public function setHomeUrl($value)
  1602. {
  1603. $this->_homeUrl=$value;
  1604. }
  1605. public function runController($route)
  1606. {
  1607. if(($ca=$this->createController($route))!==null)
  1608. {
  1609. list($controller,$actionID)=$ca;
  1610. $oldController=$this->_controller;
  1611. $this->_controller=$controller;
  1612. $controller->init();
  1613. $controller->run($actionID);
  1614. $this->_controller=$oldController;
  1615. }
  1616. else
  1617. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1618. array('{route}'=>$route===''?$this->defaultController:$route)));
  1619. }
  1620. public function createController($route,$owner=null)
  1621. {
  1622. if($owner===null)
  1623. $owner=$this;
  1624. if(($route=trim($route,'/'))==='')
  1625. $route=$owner->defaultController;
  1626. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1627. $route.='/';
  1628. while(($pos=strpos($route,'/'))!==false)
  1629. {
  1630. $id=substr($route,0,$pos);
  1631. if(!preg_match('/^\w+$/',$id))
  1632. return null;
  1633. if(!$caseSensitive)
  1634. $id=strtolower($id);
  1635. $route=(string)substr($route,$pos+1);
  1636. if(!isset($basePath)) // first segment
  1637. {
  1638. if(isset($owner->controllerMap[$id]))
  1639. {
  1640. return array(
  1641. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1642. $this->parseActionParams($route),
  1643. );
  1644. }
  1645. if(($module=$owner->getModule($id))!==null)
  1646. return $this->createController($route,$module);
  1647. $basePath=$owner->getControllerPath();
  1648. $controllerID='';
  1649. }
  1650. else
  1651. $controllerID.='/';
  1652. $className=ucfirst($id).'Controller';
  1653. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1654. if(is_file($classFile))
  1655. {
  1656. if(!class_exists($className,false))
  1657. require($classFile);
  1658. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1659. {
  1660. $id[0]=strtolower($id[0]);
  1661. return array(
  1662. new $className($controllerID.$id,$owner===$this?null:$owner),
  1663. $this->parseActionParams($route),
  1664. );
  1665. }
  1666. return null;
  1667. }
  1668. $controllerID.=$id;
  1669. $basePath.=DIRECTORY_SEPARATOR.$id;
  1670. }
  1671. }
  1672. protected function parseActionParams($pathInfo)
  1673. {
  1674. if(($pos=strpos($pathInfo,'/'))!==false)
  1675. {
  1676. $manager=$this->getUrlManager();
  1677. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1678. $actionID=substr($pathInfo,0,$pos);
  1679. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1680. }
  1681. else
  1682. return $pathInfo;
  1683. }
  1684. public function getController()
  1685. {
  1686. return $this->_controller;
  1687. }
  1688. public function setController($value)
  1689. {
  1690. $this->_controller=$value;
  1691. }
  1692. public function getControllerPath()
  1693. {
  1694. if($this->_controllerPath!==null)
  1695. return $this->_controllerPath;
  1696. else
  1697. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1698. }
  1699. public function setControllerPath($value)
  1700. {
  1701. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1702. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1703. array('{path}'=>$value)));
  1704. }
  1705. public function getViewPath()
  1706. {
  1707. if($this->_viewPath!==null)
  1708. return $this->_viewPath;
  1709. else
  1710. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1711. }
  1712. public function setViewPath($path)
  1713. {
  1714. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1715. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1716. array('{path}'=>$path)));
  1717. }
  1718. public function getSystemViewPath()
  1719. {
  1720. if($this->_systemViewPath!==null)
  1721. return $this->_systemViewPath;
  1722. else
  1723. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1724. }
  1725. public function setSystemViewPath($path)
  1726. {
  1727. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1728. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1729. array('{path}'=>$path)));
  1730. }
  1731. public function getLayoutPath()
  1732. {
  1733. if($this->_layoutPath!==null)
  1734. return $this->_layoutPath;
  1735. else
  1736. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1737. }
  1738. public function setLayoutPath($path)
  1739. {
  1740. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1741. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1742. array('{path}'=>$path)));
  1743. }
  1744. public function beforeControllerAction($controller,$action)
  1745. {
  1746. return true;
  1747. }
  1748. public function afterControllerAction($controller,$action)
  1749. {
  1750. }
  1751. public function findModule($id)
  1752. {
  1753. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1754. {
  1755. do
  1756. {
  1757. if(($m=$module->getModule($id))!==null)
  1758. return $m;
  1759. } while(($module=$module->getParentModule())!==null);
  1760. }
  1761. if(($m=$this->getModule($id))!==null)
  1762. return $m;
  1763. }
  1764. protected function init()
  1765. {
  1766. parent::init();
  1767. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1768. $this->getRequest();
  1769. }
  1770. }
  1771. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1772. {
  1773. private $_d=array();
  1774. private $_r=false;
  1775. public function __construct($data=null,$readOnly=false)
  1776. {
  1777. if($data!==null)
  1778. $this->copyFrom($data);
  1779. $this->setReadOnly($readOnly);
  1780. }
  1781. public function getReadOnly()
  1782. {
  1783. return $this->_r;
  1784. }
  1785. protected function setReadOnly($value)
  1786. {
  1787. $this->_r=$value;
  1788. }
  1789. public function getIterator()
  1790. {
  1791. return new CMapIterator($this->_d);
  1792. }
  1793. public function count()
  1794. {
  1795. return $this->getCount();
  1796. }
  1797. public function getCount()
  1798. {
  1799. return count($this->_d);
  1800. }
  1801. public function getKeys()
  1802. {
  1803. return array_keys($this->_d);
  1804. }
  1805. public function itemAt($key)
  1806. {
  1807. if(isset($this->_d[$key]))
  1808. return $this->_d[$key];
  1809. else
  1810. return null;
  1811. }
  1812. public function add($key,$value)
  1813. {
  1814. if(!$this->_r)
  1815. {
  1816. if($key===null)
  1817. $this->_d[]=$value;
  1818. else
  1819. $this->_d[$key]=$value;
  1820. }
  1821. else
  1822. throw new CException(Yii::t('yii','The map is read only.'));
  1823. }
  1824. public function remove($key)
  1825. {
  1826. if(!$this->_r)
  1827. {
  1828. if(isset($this->_d[$key]))
  1829. {
  1830. $value=$this->_d[$key];
  1831. unset($this->_d[$key]);
  1832. return $value;
  1833. }
  1834. else
  1835. {
  1836. // it is possible the value is null, which is not detected by isset
  1837. unset($this->_d[$key]);
  1838. return null;
  1839. }
  1840. }
  1841. else
  1842. throw new CException(Yii::t('yii','The map is read only.'));
  1843. }
  1844. public function clear()
  1845. {
  1846. foreach(array_keys($this->_d) as $key)
  1847. $this->remove($key);
  1848. }
  1849. public function contains($key)
  1850. {
  1851. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  1852. }
  1853. public function toArray()
  1854. {
  1855. return $this->_d;
  1856. }
  1857. public function copyFrom($data)
  1858. {
  1859. if(is_array($data) || $data instanceof Traversable)
  1860. {
  1861. if($this->getCount()>0)
  1862. $this->clear();
  1863. if($data instanceof CMap)
  1864. $data=$data->_d;
  1865. foreach($data as $key=>$value)
  1866. $this->add($key,$value);
  1867. }
  1868. else if($data!==null)
  1869. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1870. }
  1871. public function mergeWith($data,$recursive=true)
  1872. {
  1873. if(is_array($data) || $data instanceof Traversable)
  1874. {
  1875. if($data instanceof CMap)
  1876. $data=$data->_d;
  1877. if($recursive)
  1878. {
  1879. if($data instanceof Traversable)
  1880. {
  1881. $d=array();
  1882. foreach($data as $key=>$value)
  1883. $d[$key]=$value;
  1884. $this->_d=self::mergeArray($this->_d,$d);
  1885. }
  1886. else
  1887. $this->_d=self::mergeArray($this->_d,$data);
  1888. }
  1889. else
  1890. {
  1891. foreach($data as $key=>$value)
  1892. $this->add($key,$value);
  1893. }
  1894. }
  1895. else if($data!==null)
  1896. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1897. }
  1898. public static function mergeArray($a,$b)
  1899. {
  1900. foreach($b as $k=>$v)
  1901. {
  1902. if(is_integer($k))
  1903. $a[]=$v;
  1904. else if(is_array($v) && isset($a[$k]) && is_array($a[$k]))
  1905. $a[$k]=self::mergeArray($a[$k],$v);
  1906. else
  1907. $a[$k]=$v;
  1908. }
  1909. return $a;
  1910. }
  1911. public function offsetExists($offset)
  1912. {
  1913. return $this->contains($offset);
  1914. }
  1915. public function offsetGet($offset)
  1916. {
  1917. return $this->itemAt($offset);
  1918. }
  1919. public function offsetSet($offset,$item)
  1920. {
  1921. $this->add($offset,$item);
  1922. }
  1923. public function offsetUnset($offset)
  1924. {
  1925. $this->remove($offset);
  1926. }
  1927. }
  1928. class CLogger extends CComponent
  1929. {
  1930. const LEVEL_TRACE='trace';
  1931. const LEVEL_WARNING='warning';
  1932. const LEVEL_ERROR='error';
  1933. const LEVEL_INFO='info';
  1934. const LEVEL_PROFILE='profile';
  1935. public $autoFlush=10000;
  1936. private $_logs=array();
  1937. private $_logCount=0;
  1938. private $_levels;
  1939. private $_categories;
  1940. private $_timings;
  1941. public function log($message,$level='info',$category='application')
  1942. {
  1943. $this->_logs[]=array($message,$level,$category,microtime(true));
  1944. $this->_logCount++;
  1945. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush)
  1946. $this->flush();
  1947. }
  1948. public function getLogs($levels='',$categories='')
  1949. {
  1950. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  1951. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  1952. if(empty($levels) && empty($categories))
  1953. return $this->_logs;
  1954. else if(empty($levels))
  1955. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByCategory'))));
  1956. else if(empty($categories))
  1957. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  1958. else
  1959. {
  1960. $ret=array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  1961. return array_values(array_filter(array_filter($ret,array($this,'filterByCategory'))));
  1962. }
  1963. }
  1964. private function filterByCategory($value)
  1965. {
  1966. foreach($this->_categories as $category)
  1967. {
  1968. $cat=strtolower($value[2]);
  1969. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  1970. return $value;
  1971. }
  1972. return false;
  1973. }
  1974. private function filterByLevel($value)
  1975. {
  1976. return in_array(strtolower($value[1]),$this->_levels)?$value:false;
  1977. }
  1978. public function getExecutionTime()
  1979. {
  1980. return microtime(true)-YII_BEGIN_TIME;
  1981. }
  1982. public function getMemoryUsage()
  1983. {
  1984. if(function_exists('memory_get_usage'))
  1985. return memory_get_usage();
  1986. else
  1987. {
  1988. $output=array();
  1989. if(strncmp(PHP_OS,'WIN',3)===0)
  1990. {
  1991. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  1992. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  1993. }
  1994. else
  1995. {
  1996. $pid=getmypid();
  1997. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  1998. $output=explode(" ",$output[0]);
  1999. return isset($output[1]) ? $output[1]*1024 : 0;
  2000. }
  2001. }
  2002. }
  2003. public function getProfilingResults($token=null,$category=null,$refresh=false)
  2004. {
  2005. if($this->_timings===null || $refresh)
  2006. $this->calculateTimings();
  2007. if($token===null && $category===null)
  2008. return $this->_timings;
  2009. $results=array();
  2010. foreach($this->_timings as $timing)
  2011. {
  2012. if(($category===null || $timing[1]===$category) && ($token===null || $timing[0]===$token))
  2013. $results[]=$timing[2];
  2014. }
  2015. return $results;
  2016. }
  2017. private function calculateTimings()
  2018. {
  2019. $this->_timings=array();
  2020. $stack=array();
  2021. foreach($this->_logs as $log)
  2022. {
  2023. if($log[1]!==CLogger::LEVEL_PROFILE)
  2024. continue;
  2025. list($message,$level,$category,$timestamp)=$log;
  2026. if(!strncasecmp($message,'begin:',6))
  2027. {
  2028. $log[0]=substr($message,6);
  2029. $stack[]=$log;
  2030. }
  2031. else if(!strncasecmp($message,'end:',4))
  2032. {
  2033. $token=substr($message,4);
  2034. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2035. {
  2036. $delta=$log[3]-$last[3];
  2037. $this->_timings[]=array($message,$category,$delta);
  2038. }
  2039. else
  2040. 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.',
  2041. array('{token}'=>$token)));
  2042. }
  2043. }
  2044. $now=microtime(true);
  2045. while(($last=array_pop($stack))!==null)
  2046. {
  2047. $delta=$now-$last[3];
  2048. $this->_timings[]=array($last[0],$last[2],$delta);
  2049. }
  2050. }
  2051. public function flush()
  2052. {
  2053. $this->onFlush(new CEvent($this));
  2054. $this->_logs=array();
  2055. $this->_logCount=0;
  2056. }
  2057. public function onFlush($event)
  2058. {
  2059. $this->raiseEvent('onFlush', $event);
  2060. }
  2061. }
  2062. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2063. {
  2064. public $behaviors=array();
  2065. private $_initialized=false;
  2066. public function init()
  2067. {
  2068. $this->attachBehaviors($this->behaviors);
  2069. $this->_initialized=true;
  2070. }
  2071. public function getIsInitialized()
  2072. {
  2073. return $this->_initialized;
  2074. }
  2075. }
  2076. class CHttpRequest extends CApplicationComponent
  2077. {
  2078. public $enableCookieValidation=false;
  2079. public $enableCsrfValidation=false;
  2080. public $csrfTokenName='YII_CSRF_TOKEN';
  2081. public $csrfCookie;
  2082. private $_requestUri;
  2083. private $_pathInfo;
  2084. private $_scriptFile;
  2085. private $_scriptUrl;
  2086. private $_hostInfo;
  2087. private $_url;
  2088. private $_baseUrl;
  2089. private $_cookies;
  2090. private $_preferredLanguage;
  2091. private $_csrfToken;
  2092. public function init()
  2093. {
  2094. parent::init();
  2095. $this->normalizeRequest();
  2096. }
  2097. protected function normalizeRequest()
  2098. {
  2099. // normalize request
  2100. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2101. {
  2102. if(isset($_GET))
  2103. $_GET=$this->stripSlashes($_GET);
  2104. if(isset($_POST))
  2105. $_POST=$this->stripSlashes($_POST);
  2106. if(isset($_REQUEST))
  2107. $_REQUEST=$this->stripSlashes($_REQUEST);
  2108. if(isset($_COOKIE))
  2109. $_COOKIE=$this->stripSlashes($_COOKIE);
  2110. }
  2111. if($this->enableCsrfValidation)
  2112. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2113. }
  2114. public function stripSlashes(&$data)
  2115. {
  2116. return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
  2117. }
  2118. public function getParam($name,$defaultValue=null)
  2119. {
  2120. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2121. }
  2122. public function getQuery($name,$defaultValue=null)
  2123. {
  2124. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2125. }
  2126. public function getPost($name,$defaultValue=null)
  2127. {
  2128. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2129. }
  2130. public function getUrl()
  2131. {
  2132. if($this->_url!==null)
  2133. return $this->_url;
  2134. else
  2135. {
  2136. if(isset($_SERVER['REQUEST_URI']))
  2137. $this->_url=$_SERVER['REQUEST_URI'];
  2138. else
  2139. {
  2140. $this->_url=$this->getScriptUrl();
  2141. if(($pathInfo=$this->getPathInfo())!=='')
  2142. $this->_url.='/'.$pathInfo;
  2143. if(($queryString=$this->getQueryString())!=='')
  2144. $this->_url.='?'.$queryString;
  2145. }
  2146. return $this->_url;
  2147. }
  2148. }
  2149. public function getHostInfo($schema='')
  2150. {
  2151. if($this->_hostInfo===null)
  2152. {
  2153. if($secure=$this->getIsSecureConnection())
  2154. $http='https';
  2155. else
  2156. $http='http';
  2157. if(isset($_SERVER['HTTP_HOST']))
  2158. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2159. else
  2160. {
  2161. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2162. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2163. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2164. $this->_hostInfo.=':'.$port;
  2165. }
  2166. }
  2167. if($schema!=='')
  2168. {
  2169. $secure=$this->getIsSecureConnection();
  2170. if($secure && $schema==='https' || !$secure && $schema==='http')
  2171. return $this->_hostInfo;
  2172. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2173. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2174. $port=':'.$port;
  2175. else
  2176. $port='';
  2177. $pos=strpos($this->_hostInfo,':');
  2178. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2179. }
  2180. else
  2181. return $this->_hostInfo;
  2182. }
  2183. public function setHostInfo($value)
  2184. {
  2185. $this->_hostInfo=rtrim($value,'/');
  2186. }
  2187. public function getBaseUrl($absolute=false)
  2188. {
  2189. if($this->_baseUrl===null)
  2190. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2191. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2192. }
  2193. public function setBaseUrl($value)
  2194. {
  2195. $this->_baseUrl=$value;
  2196. }
  2197. public function getScriptUrl()
  2198. {
  2199. if($this->_scriptUrl===null)
  2200. {
  2201. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2202. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2203. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2204. else if(basename($_SERVER['PHP_SELF'])===$scriptName)
  2205. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2206. else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2207. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2208. else if(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2209. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2210. else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2211. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2212. else
  2213. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2214. }
  2215. return $this->_scriptUrl;
  2216. }
  2217. public function setScriptUrl($value)
  2218. {
  2219. $this->_scriptUrl='/'.trim($value,'/');
  2220. }
  2221. public function getPathInfo()
  2222. {
  2223. if($this->_pathInfo===null)
  2224. {
  2225. $requestUri=urldecode($this->getRequestUri());
  2226. $scriptUrl=$this->getScriptUrl();
  2227. $baseUrl=$this->getBaseUrl();
  2228. if(strpos($requestUri,$scriptUrl)===0)
  2229. $pathInfo=substr($requestUri,strlen($scriptUrl));
  2230. else if($baseUrl==='' || strpos($requestUri,$baseUrl)===0)
  2231. $pathInfo=substr($requestUri,strlen($baseUrl));
  2232. else if(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2233. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2234. else
  2235. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2236. if(($pos=strpos($pathInfo,'?'))!==false)
  2237. $pathInfo=substr($pathInfo,0,$pos);
  2238. $this->_pathInfo=trim($pathInfo,'/');
  2239. }
  2240. return $this->_pathInfo;
  2241. }
  2242. public function getRequestUri()
  2243. {
  2244. if($this->_requestUri===null)
  2245. {
  2246. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2247. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2248. else if(isset($_SERVER['REQUEST_URI']))
  2249. {
  2250. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2251. if(isset($_SERVER['HTTP_HOST']))
  2252. {
  2253. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2254. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2255. }
  2256. else
  2257. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2258. }
  2259. else if(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2260. {
  2261. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2262. if(!empty($_SERVER['QUERY_STRING']))
  2263. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2264. }
  2265. else
  2266. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2267. }
  2268. return $this->_requestUri;
  2269. }
  2270. public function getQueryString()
  2271. {
  2272. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2273. }
  2274. public function getIsSecureConnection()
  2275. {
  2276. return isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'],'on');
  2277. }
  2278. public function getRequestType()
  2279. {
  2280. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2281. }
  2282. public function getIsPostRequest()
  2283. {
  2284. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2285. }
  2286. public function getIsAjaxRequest()
  2287. {
  2288. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2289. }
  2290. public function getServerName()
  2291. {
  2292. return $_SERVER['SERVER_NAME'];
  2293. }
  2294. public function getServerPort()
  2295. {
  2296. return $_SERVER['SERVER_PORT'];
  2297. }
  2298. public function getUrlReferrer()
  2299. {
  2300. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2301. }
  2302. public function getUserAgent()
  2303. {
  2304. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2305. }
  2306. public function getUserHostAddress()
  2307. {
  2308. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2309. }
  2310. public function getUserHost()
  2311. {
  2312. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2313. }
  2314. public function getScriptFile()
  2315. {
  2316. if($this->_scriptFile!==null)
  2317. return $this->_scriptFile;
  2318. else
  2319. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2320. }
  2321. public function getBrowser($userAgent=null)
  2322. {
  2323. return get_browser($userAgent,true);
  2324. }
  2325. public function getAcceptTypes()
  2326. {
  2327. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2328. }
  2329. private $_port;
  2330. public function getPort()
  2331. {
  2332. if($this->_port===null)
  2333. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2334. return $this->_port;
  2335. }
  2336. public function setPort($value)
  2337. {
  2338. $this->_port=(int)$value;
  2339. $this->_hostInfo=null;
  2340. }
  2341. private $_securePort;
  2342. public function getSecurePort()
  2343. {
  2344. if($this->_securePort===null)
  2345. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2346. return $this->_securePort;
  2347. }
  2348. public function setSecurePort($value)
  2349. {
  2350. $this->_securePort=(int)$value;
  2351. $this->_hostInfo=null;
  2352. }
  2353. public function getCookies()
  2354. {
  2355. if($this->_cookies!==null)
  2356. return $this->_cookies;
  2357. else
  2358. return $this->_cookies=new CCookieCollection($this);
  2359. }
  2360. public function redirect($url,$terminate=true,$statusCode=302)
  2361. {
  2362. if(strpos($url,'/')===0)
  2363. $url=$this->getHostInfo().$url;
  2364. header('Location: '.$url, true, $statusCode);
  2365. if($terminate)
  2366. Yii::app()->end();
  2367. }
  2368. public function getPreferredLanguage()
  2369. {
  2370. if($this->_preferredLanguage===null)
  2371. {
  2372. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && ($n=preg_match_all('/([\w\-_]+)\s*(;\s*q\s*=\s*(\d*\.\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))>0)
  2373. {
  2374. $languages=array();
  2375. for($i=0;$i<$n;++$i)
  2376. $languages[$matches[1][$i]]=empty($matches[3][$i]) ? 1.0 : floatval($matches[3][$i]);
  2377. arsort($languages);
  2378. foreach($languages as $language=>$pref)
  2379. return $this->_preferredLanguage=CLocale::getCanonicalID($language);
  2380. }
  2381. return $this->_preferredLanguage=false;
  2382. }
  2383. return $this->_preferredLanguage;
  2384. }
  2385. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2386. {
  2387. if($mimeType===null)
  2388. {
  2389. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2390. $mimeType='text/plain';
  2391. }
  2392. header('Pragma: public');
  2393. header('Expires: 0');
  2394. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2395. header("Content-type: $mimeType");
  2396. if(ini_get("output_handler")=='')
  2397. header('Content-Length: '.(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content)));
  2398. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2399. header('Content-Transfer-Encoding: binary');
  2400. if($terminate)
  2401. {
  2402. // clean up the application first because the file downloading could take long time
  2403. // which may cause timeout of some resources (such as DB connection)
  2404. Yii::app()->end(0,false);
  2405. echo $content;
  2406. exit(0);
  2407. }
  2408. else
  2409. echo $content;
  2410. }
  2411. public function getCsrfToken()
  2412. {
  2413. if($this->_csrfToken===null)
  2414. {
  2415. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2416. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2417. {
  2418. $cookie=$this->createCsrfCookie();
  2419. $this->_csrfToken=$cookie->value;
  2420. $this->getCookies()->add($cookie->name,$cookie);
  2421. }
  2422. }
  2423. return $this->_csrfToken;
  2424. }
  2425. protected function createCsrfCookie()
  2426. {
  2427. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2428. if(is_array($this->csrfCookie))
  2429. {
  2430. foreach($this->csrfCookie as $name=>$value)
  2431. $cookie->$name=$value;
  2432. }
  2433. return $cookie;
  2434. }
  2435. public function validateCsrfToken($event)
  2436. {
  2437. if($this->getIsPostRequest())
  2438. {
  2439. // only validate POST requests
  2440. $cookies=$this->getCookies();
  2441. if($cookies->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName]))
  2442. {
  2443. $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value;
  2444. $tokenFromPost=$_POST[$this->csrfTokenName];
  2445. $valid=$tokenFromCookie===$tokenFromPost;
  2446. }
  2447. else
  2448. $valid=false;
  2449. if(!$valid)
  2450. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2451. }
  2452. }
  2453. }
  2454. class CCookieCollection extends CMap
  2455. {
  2456. private $_request;
  2457. private $_initialized=false;
  2458. public function __construct(CHttpRequest $request)
  2459. {
  2460. $this->_request=$request;
  2461. $this->copyfrom($this->getCookies());
  2462. $this->_initialized=true;
  2463. }
  2464. public function getRequest()
  2465. {
  2466. return $this->_request;
  2467. }
  2468. protected function getCookies()
  2469. {
  2470. $cookies=array();
  2471. if($this->_request->enableCookieValidation)
  2472. {
  2473. $sm=Yii::app()->getSecurityManager();
  2474. foreach($_COOKIE as $name=>$value)
  2475. {
  2476. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  2477. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  2478. }
  2479. }
  2480. else
  2481. {
  2482. foreach($_COOKIE as $name=>$value)
  2483. $cookies[$name]=new CHttpCookie($name,$value);
  2484. }
  2485. return $cookies;
  2486. }
  2487. public function add($name,$cookie)
  2488. {
  2489. if($cookie instanceof CHttpCookie)
  2490. {
  2491. $this->remove($name);
  2492. parent::add($name,$cookie);
  2493. if($this->_initialized)
  2494. $this->addCookie($cookie);
  2495. }
  2496. else
  2497. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  2498. }
  2499. public function remove($name)
  2500. {
  2501. if(($cookie=parent::remove($name))!==null)
  2502. {
  2503. if($this->_initialized)
  2504. $this->removeCookie($cookie);
  2505. }
  2506. return $cookie;
  2507. }
  2508. protected function addCookie($cookie)
  2509. {
  2510. $value=$cookie->value;
  2511. if($this->_request->enableCookieValidation)
  2512. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  2513. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2514. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2515. else
  2516. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  2517. }
  2518. protected function removeCookie($cookie)
  2519. {
  2520. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2521. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2522. else
  2523. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure);
  2524. }
  2525. }
  2526. class CUrlManager extends CApplicationComponent
  2527. {
  2528. const CACHE_KEY='Yii.CUrlManager.rules';
  2529. const GET_FORMAT='get';
  2530. const PATH_FORMAT='path';
  2531. public $rules=array();
  2532. public $urlSuffix='';
  2533. public $showScriptName=true;
  2534. public $appendParams=true;
  2535. public $routeVar='r';
  2536. public $caseSensitive=true;
  2537. public $matchValue=false;
  2538. public $cacheID='cache';
  2539. public $useStrictParsing=false;
  2540. private $_urlFormat=self::GET_FORMAT;
  2541. private $_rules=array();
  2542. private $_baseUrl;
  2543. public function init()
  2544. {
  2545. parent::init();
  2546. $this->processRules();
  2547. }
  2548. protected function processRules()
  2549. {
  2550. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  2551. return;
  2552. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  2553. {
  2554. $hash=md5(serialize($this->rules));
  2555. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  2556. {
  2557. $this->_rules=$data[0];
  2558. return;
  2559. }
  2560. }
  2561. foreach($this->rules as $pattern=>$route)
  2562. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2563. if(isset($cache))
  2564. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  2565. }
  2566. public function addRules($rules)
  2567. {
  2568. foreach($rules as $pattern=>$route)
  2569. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2570. }
  2571. protected function createUrlRule($route,$pattern)
  2572. {
  2573. return new CUrlRule($route,$pattern);
  2574. }
  2575. public function createUrl($route,$params=array(),$ampersand='&')
  2576. {
  2577. unset($params[$this->routeVar]);
  2578. foreach($params as &$param)
  2579. if($param===null)
  2580. $param='';
  2581. if(isset($params['#']))
  2582. {
  2583. $anchor='#'.$params['#'];
  2584. unset($params['#']);
  2585. }
  2586. else
  2587. $anchor='';
  2588. $route=trim($route,'/');
  2589. foreach($this->_rules as $rule)
  2590. {
  2591. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  2592. return $rule->hasHostInfo ? $url.$anchor : $this->getBaseUrl().'/'.$url.$anchor;
  2593. }
  2594. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  2595. }
  2596. protected function createUrlDefault($route,$params,$ampersand)
  2597. {
  2598. if($this->getUrlFormat()===self::PATH_FORMAT)
  2599. {
  2600. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  2601. if($this->appendParams)
  2602. {
  2603. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  2604. return $route==='' ? $url : $url.$this->urlSuffix;
  2605. }
  2606. else
  2607. {
  2608. if($route!=='')
  2609. $url.=$this->urlSuffix;
  2610. $query=$this->createPathInfo($params,'=',$ampersand);
  2611. return $query==='' ? $url : $url.'?'.$query;
  2612. }
  2613. }
  2614. else
  2615. {
  2616. $url=$this->getBaseUrl();
  2617. if(!$this->showScriptName)
  2618. $url.='/';
  2619. if($route!=='')
  2620. {
  2621. $url.='?'.$this->routeVar.'='.$route;
  2622. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2623. $url.=$ampersand.$query;
  2624. }
  2625. else if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2626. $url.='?'.$query;
  2627. return $url;
  2628. }
  2629. }
  2630. public function parseUrl($request)
  2631. {
  2632. if($this->getUrlFormat()===self::PATH_FORMAT)
  2633. {
  2634. $rawPathInfo=$request->getPathInfo();
  2635. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  2636. foreach($this->_rules as $rule)
  2637. {
  2638. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  2639. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  2640. }
  2641. if($this->useStrictParsing)
  2642. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  2643. array('{route}'=>$pathInfo)));
  2644. else
  2645. return $pathInfo;
  2646. }
  2647. else if(isset($_GET[$this->routeVar]))
  2648. return $_GET[$this->routeVar];
  2649. else if(isset($_POST[$this->routeVar]))
  2650. return $_POST[$this->routeVar];
  2651. else
  2652. return '';
  2653. }
  2654. public function parsePathInfo($pathInfo)
  2655. {
  2656. if($pathInfo==='')
  2657. return;
  2658. $segs=explode('/',$pathInfo.'/');
  2659. $n=count($segs);
  2660. for($i=0;$i<$n-1;$i+=2)
  2661. {
  2662. $key=$segs[$i];
  2663. if($key==='') continue;
  2664. $value=$segs[$i+1];
  2665. if(($pos=strpos($key,'['))!==false && ($pos2=strpos($key,']',$pos+1))!==false)
  2666. {
  2667. $name=substr($key,0,$pos);
  2668. if($pos2===$pos+1)
  2669. $_REQUEST[$name][]=$_GET[$name][]=$value;
  2670. else
  2671. {
  2672. $key=substr($key,$pos+1,$pos2-$pos-1);
  2673. $_REQUEST[$name][$key]=$_GET[$name][$key]=$value;
  2674. }
  2675. }
  2676. else
  2677. $_REQUEST[$key]=$_GET[$key]=$value;
  2678. }
  2679. }
  2680. public function createPathInfo($params,$equal,$ampersand, $key=null)
  2681. {
  2682. $pairs = array();
  2683. foreach($params as $k => $v)
  2684. {
  2685. if ($key!==null)
  2686. $k = $key.'['.$k.']';
  2687. if (is_array($v))
  2688. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  2689. else
  2690. $pairs[]=urlencode($k).$equal.urlencode($v);
  2691. }
  2692. return implode($ampersand,$pairs);
  2693. }
  2694. public function removeUrlSuffix($pathInfo,$urlSuffix)
  2695. {
  2696. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  2697. return substr($pathInfo,0,-strlen($urlSuffix));
  2698. else
  2699. return $pathInfo;
  2700. }
  2701. public function getBaseUrl()
  2702. {
  2703. if($this->_baseUrl!==null)
  2704. return $this->_baseUrl;
  2705. else
  2706. {
  2707. if($this->showScriptName)
  2708. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  2709. else
  2710. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  2711. return $this->_baseUrl;
  2712. }
  2713. }
  2714. public function setBaseUrl($value)
  2715. {
  2716. $this->_baseUrl=$value;
  2717. }
  2718. public function getUrlFormat()
  2719. {
  2720. return $this->_urlFormat;
  2721. }
  2722. public function setUrlFormat($value)
  2723. {
  2724. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  2725. $this->_urlFormat=$value;
  2726. else
  2727. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  2728. }
  2729. }
  2730. class CUrlRule extends CComponent
  2731. {
  2732. public $urlSuffix;
  2733. public $caseSensitive;
  2734. public $defaultParams=array();
  2735. public $matchValue;
  2736. public $route;
  2737. public $references=array();
  2738. public $routePattern;
  2739. public $pattern;
  2740. public $template;
  2741. public $params=array();
  2742. public $append;
  2743. public $hasHostInfo;
  2744. public function __construct($route,$pattern)
  2745. {
  2746. if(is_array($route))
  2747. {
  2748. if(isset($route['urlSuffix']))
  2749. $this->urlSuffix=$route['urlSuffix'];
  2750. if(isset($route['caseSensitive']))
  2751. $this->caseSensitive=$route['caseSensitive'];
  2752. if(isset($route['defaultParams']))
  2753. $this->defaultParams=$route['defaultParams'];
  2754. if(isset($route['matchValue']))
  2755. $this->matchValue=$route['matchValue'];
  2756. $route=$this->route=$route[0];
  2757. }
  2758. else
  2759. $this->route=$route;
  2760. $tr2['/']=$tr['/']='\\/';
  2761. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  2762. {
  2763. foreach($matches2[1] as $name)
  2764. $this->references[$name]="<$name>";
  2765. }
  2766. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  2767. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  2768. {
  2769. $tokens=array_combine($matches[1],$matches[2]);
  2770. foreach($tokens as $name=>$value)
  2771. {
  2772. if($value==='')
  2773. $value='[^\/]+';
  2774. $tr["<$name>"]="(?P<$name>$value)";
  2775. if(isset($this->references[$name]))
  2776. $tr2["<$name>"]=$tr["<$name>"];
  2777. else
  2778. $this->params[$name]=$value;
  2779. }
  2780. }
  2781. $p=rtrim($pattern,'*');
  2782. $this->append=$p!==$pattern;
  2783. $p=trim($p,'/');
  2784. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  2785. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  2786. if($this->append)
  2787. $this->pattern.='/u';
  2788. else
  2789. $this->pattern.='$/u';
  2790. if($this->references!==array())
  2791. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  2792. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  2793. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  2794. array('{route}'=>$route,'{pattern}'=>$pattern)));
  2795. }
  2796. public function createUrl($manager,$route,$params,$ampersand)
  2797. {
  2798. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  2799. $case='';
  2800. else
  2801. $case='i';
  2802. $tr=array();
  2803. if($route!==$this->route)
  2804. {
  2805. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  2806. {
  2807. foreach($this->references as $key=>$name)
  2808. $tr[$name]=$matches[$key];
  2809. }
  2810. else
  2811. return false;
  2812. }
  2813. foreach($this->defaultParams as $key=>$value)
  2814. {
  2815. if(isset($params[$key]))
  2816. {
  2817. if($params[$key]==$value)
  2818. unset($params[$key]);
  2819. else
  2820. return false;
  2821. }
  2822. }
  2823. foreach($this->params as $key=>$value)
  2824. if(!isset($params[$key]))
  2825. return false;
  2826. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  2827. {
  2828. foreach($this->params as $key=>$value)
  2829. {
  2830. if(!preg_match('/'.$value.'/'.$case,$params[$key]))
  2831. return false;
  2832. }
  2833. }
  2834. foreach($this->params as $key=>$value)
  2835. {
  2836. $tr["<$key>"]=urlencode($params[$key]);
  2837. unset($params[$key]);
  2838. }
  2839. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  2840. $url=strtr($this->template,$tr);
  2841. if($this->hasHostInfo)
  2842. {
  2843. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  2844. if(strpos($url,$hostInfo)===0)
  2845. $url=substr($url,strlen($hostInfo));
  2846. }
  2847. if(empty($params))
  2848. return $url!=='' ? $url.$suffix : $url;
  2849. if($this->append)
  2850. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  2851. else
  2852. {
  2853. if($url!=='')
  2854. $url.=$suffix;
  2855. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  2856. }
  2857. return $url;
  2858. }
  2859. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  2860. {
  2861. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  2862. $case='';
  2863. else
  2864. $case='i';
  2865. if($this->urlSuffix!==null)
  2866. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  2867. // URL suffix required, but not found in the requested URL
  2868. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  2869. {
  2870. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  2871. if($urlSuffix!='' && $urlSuffix!=='/')
  2872. return false;
  2873. }
  2874. if($this->hasHostInfo)
  2875. $pathInfo=$request->getHostInfo().rtrim('/'.$pathInfo,'/');
  2876. $pathInfo.='/';
  2877. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  2878. {
  2879. foreach($this->defaultParams as $name=>$value)
  2880. {
  2881. if(!isset($_GET[$name]))
  2882. $_REQUEST[$name]=$_GET[$name]=$value;
  2883. }
  2884. $tr=array();
  2885. foreach($matches as $key=>$value)
  2886. {
  2887. if(isset($this->references[$key]))
  2888. $tr[$this->references[$key]]=$value;
  2889. else if(isset($this->params[$key]))
  2890. $_REQUEST[$key]=$_GET[$key]=$value;
  2891. }
  2892. if($pathInfo!==$matches[0]) // there're additional GET params
  2893. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  2894. if($this->routePattern!==null)
  2895. return strtr($this->route,$tr);
  2896. else
  2897. return $this->route;
  2898. }
  2899. else
  2900. return false;
  2901. }
  2902. }
  2903. abstract class CBaseController extends CComponent
  2904. {
  2905. private $_widgetStack=array();
  2906. abstract public function getViewFile($viewName);
  2907. public function renderFile($viewFile,$data=null,$return=false)
  2908. {
  2909. $widgetCount=count($this->_widgetStack);
  2910. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  2911. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  2912. else
  2913. $content=$this->renderInternal($viewFile,$data,$return);
  2914. if(count($this->_widgetStack)===$widgetCount)
  2915. return $content;
  2916. else
  2917. {
  2918. $widget=end($this->_widgetStack);
  2919. 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.',
  2920. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  2921. }
  2922. }
  2923. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  2924. {
  2925. // we use special variable names here to avoid conflict when extracting data
  2926. if(is_array($_data_))
  2927. extract($_data_,EXTR_PREFIX_SAME,'data');
  2928. else
  2929. $data=$_data_;
  2930. if($_return_)
  2931. {
  2932. ob_start();
  2933. ob_implicit_flush(false);
  2934. require($_viewFile_);
  2935. return ob_get_clean();
  2936. }
  2937. else
  2938. require($_viewFile_);
  2939. }
  2940. public function createWidget($className,$properties=array())
  2941. {
  2942. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  2943. $widget->init();
  2944. return $widget;
  2945. }
  2946. public function widget($className,$properties=array(),$captureOutput=false)
  2947. {
  2948. if($captureOutput)
  2949. {
  2950. ob_start();
  2951. ob_implicit_flush(false);
  2952. $widget=$this->createWidget($className,$properties);
  2953. $widget->run();
  2954. return ob_get_clean();
  2955. }
  2956. else
  2957. {
  2958. $widget=$this->createWidget($className,$properties);
  2959. $widget->run();
  2960. return $widget;
  2961. }
  2962. }
  2963. public function beginWidget($className,$properties=array())
  2964. {
  2965. $widget=$this->createWidget($className,$properties);
  2966. $this->_widgetStack[]=$widget;
  2967. return $widget;
  2968. }
  2969. public function endWidget($id='')
  2970. {
  2971. if(($widget=array_pop($this->_widgetStack))!==null)
  2972. {
  2973. $widget->run();
  2974. return $widget;
  2975. }
  2976. else
  2977. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  2978. array('{controller}'=>get_class($this),'{id}'=>$id)));
  2979. }
  2980. public function beginClip($id,$properties=array())
  2981. {
  2982. $properties['id']=$id;
  2983. $this->beginWidget('CClipWidget',$properties);
  2984. }
  2985. public function endClip()
  2986. {
  2987. $this->endWidget('CClipWidget');
  2988. }
  2989. public function beginCache($id,$properties=array())
  2990. {
  2991. $properties['id']=$id;
  2992. $cache=$this->beginWidget('COutputCache',$properties);
  2993. if($cache->getIsContentCached())
  2994. {
  2995. $this->endCache();
  2996. return false;
  2997. }
  2998. else
  2999. return true;
  3000. }
  3001. public function endCache()
  3002. {
  3003. $this->endWidget('COutputCache');
  3004. }
  3005. public function beginContent($view=null,$data=array())
  3006. {
  3007. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3008. }
  3009. public function endContent()
  3010. {
  3011. $this->endWidget('CContentDecorator');
  3012. }
  3013. }
  3014. class CController extends CBaseController
  3015. {
  3016. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3017. public $layout;
  3018. public $defaultAction='index';
  3019. private $_id;
  3020. private $_action;
  3021. private $_pageTitle;
  3022. private $_cachingStack;
  3023. private $_clips;
  3024. private $_dynamicOutput;
  3025. private $_pageStates;
  3026. private $_module;
  3027. public function __construct($id,$module=null)
  3028. {
  3029. $this->_id=$id;
  3030. $this->_module=$module;
  3031. $this->attachBehaviors($this->behaviors());
  3032. }
  3033. public function init()
  3034. {
  3035. }
  3036. public function filters()
  3037. {
  3038. return array();
  3039. }
  3040. public function actions()
  3041. {
  3042. return array();
  3043. }
  3044. public function behaviors()
  3045. {
  3046. return array();
  3047. }
  3048. public function accessRules()
  3049. {
  3050. return array();
  3051. }
  3052. public function run($actionID)
  3053. {
  3054. if(($action=$this->createAction($actionID))!==null)
  3055. {
  3056. if(($parent=$this->getModule())===null)
  3057. $parent=Yii::app();
  3058. if($parent->beforeControllerAction($this,$action))
  3059. {
  3060. $this->runActionWithFilters($action,$this->filters());
  3061. $parent->afterControllerAction($this,$action);
  3062. }
  3063. }
  3064. else
  3065. $this->missingAction($actionID);
  3066. }
  3067. public function runActionWithFilters($action,$filters)
  3068. {
  3069. if(empty($filters))
  3070. $this->runAction($action);
  3071. else
  3072. {
  3073. $priorAction=$this->_action;
  3074. $this->_action=$action;
  3075. CFilterChain::create($this,$action,$filters)->run();
  3076. $this->_action=$priorAction;
  3077. }
  3078. }
  3079. public function runAction($action)
  3080. {
  3081. $priorAction=$this->_action;
  3082. $this->_action=$action;
  3083. if($this->beforeAction($action))
  3084. {
  3085. $action->run();
  3086. $this->afterAction($action);
  3087. }
  3088. $this->_action=$priorAction;
  3089. }
  3090. public function processOutput($output)
  3091. {
  3092. Yii::app()->getClientScript()->render($output);
  3093. // if using page caching, we should delay dynamic output replacement
  3094. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3095. $output=$this->processDynamicOutput($output);
  3096. if($this->_pageStates===null)
  3097. $this->_pageStates=$this->loadPageStates();
  3098. if(!empty($this->_pageStates))
  3099. $this->savePageStates($this->_pageStates,$output);
  3100. return $output;
  3101. }
  3102. public function processDynamicOutput($output)
  3103. {
  3104. if($this->_dynamicOutput)
  3105. {
  3106. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3107. }
  3108. return $output;
  3109. }
  3110. protected function replaceDynamicOutput($matches)
  3111. {
  3112. $content=$matches[0];
  3113. if(isset($this->_dynamicOutput[$matches[1]]))
  3114. {
  3115. $content=$this->_dynamicOutput[$matches[1]];
  3116. unset($this->_dynamicOutput[$matches[1]]);
  3117. }
  3118. return $content;
  3119. }
  3120. public function createAction($actionID)
  3121. {
  3122. if($actionID==='')
  3123. $actionID=$this->defaultAction;
  3124. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3125. return new CInlineAction($this,$actionID);
  3126. else
  3127. return $this->createActionFromMap($this->actions(),$actionID,$actionID);
  3128. }
  3129. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3130. {
  3131. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3132. {
  3133. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3134. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3135. }
  3136. else if($pos===false)
  3137. return null;
  3138. // the action is defined in a provider
  3139. $prefix=substr($actionID,0,$pos+1);
  3140. if(!isset($actionMap[$prefix]))
  3141. return null;
  3142. $actionID=(string)substr($actionID,$pos+1);
  3143. $provider=$actionMap[$prefix];
  3144. if(is_string($provider))
  3145. $providerType=$provider;
  3146. else if(is_array($provider) && isset($provider['class']))
  3147. {
  3148. $providerType=$provider['class'];
  3149. if(isset($provider[$actionID]))
  3150. {
  3151. if(is_string($provider[$actionID]))
  3152. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3153. else
  3154. $config=array_merge($provider[$actionID],$config);
  3155. }
  3156. }
  3157. else
  3158. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3159. $class=Yii::import($providerType,true);
  3160. $map=call_user_func(array($class,'actions'));
  3161. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3162. }
  3163. public function missingAction($actionID)
  3164. {
  3165. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3166. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3167. }
  3168. public function getAction()
  3169. {
  3170. return $this->_action;
  3171. }
  3172. public function setAction($value)
  3173. {
  3174. $this->_action=$value;
  3175. }
  3176. public function getId()
  3177. {
  3178. return $this->_id;
  3179. }
  3180. public function getUniqueId()
  3181. {
  3182. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3183. }
  3184. public function getRoute()
  3185. {
  3186. if(($action=$this->getAction())!==null)
  3187. return $this->getUniqueId().'/'.$action->getId();
  3188. else
  3189. return $this->getUniqueId();
  3190. }
  3191. public function getModule()
  3192. {
  3193. return $this->_module;
  3194. }
  3195. public function getViewPath()
  3196. {
  3197. if(($module=$this->getModule())===null)
  3198. $module=Yii::app();
  3199. return $module->getViewPath().'/'.$this->getId();
  3200. }
  3201. public function getViewFile($viewName)
  3202. {
  3203. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3204. return $viewFile;
  3205. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3206. if(($module=$this->getModule())!==null)
  3207. $moduleViewPath=$module->getViewPath();
  3208. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3209. }
  3210. public function getLayoutFile($layoutName)
  3211. {
  3212. if($layoutName===false)
  3213. return false;
  3214. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3215. return $layoutFile;
  3216. if(empty($layoutName))
  3217. {
  3218. $module=$this->getModule();
  3219. while($module!==null)
  3220. {
  3221. if($module->layout===false)
  3222. return false;
  3223. if(!empty($module->layout))
  3224. break;
  3225. $module=$module->getParentModule();
  3226. }
  3227. if($module===null)
  3228. $module=Yii::app();
  3229. $layoutName=$module->layout;
  3230. }
  3231. else if(($module=$this->getModule())===null)
  3232. $module=Yii::app();
  3233. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3234. }
  3235. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3236. {
  3237. if(empty($viewName))
  3238. return false;
  3239. if($moduleViewPath===null)
  3240. $moduleViewPath=$basePath;
  3241. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3242. $extension=$renderer->fileExtension;
  3243. else
  3244. $extension='.php';
  3245. if($viewName[0]==='/')
  3246. {
  3247. if(strncmp($viewName,'//',2)===0)
  3248. $viewFile=$basePath.$viewName;
  3249. else
  3250. $viewFile=$moduleViewPath.$viewName;
  3251. }
  3252. else if(strpos($viewName,'.'))
  3253. $viewFile=Yii::getPathOfAlias($viewName);
  3254. else
  3255. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3256. if(is_file($viewFile.$extension))
  3257. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3258. else if($extension!=='.php' && is_file($viewFile.'.php'))
  3259. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3260. else
  3261. return false;
  3262. }
  3263. public function getClips()
  3264. {
  3265. if($this->_clips!==null)
  3266. return $this->_clips;
  3267. else
  3268. return $this->_clips=new CMap;
  3269. }
  3270. public function forward($route,$exit=true)
  3271. {
  3272. if(strpos($route,'/')===false)
  3273. $this->run($route);
  3274. else
  3275. {
  3276. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3277. $route=$module->getId().'/'.$route;
  3278. Yii::app()->runController($route);
  3279. }
  3280. if($exit)
  3281. Yii::app()->end();
  3282. }
  3283. public function render($view,$data=null,$return=false)
  3284. {
  3285. if($this->beforeRender($view))
  3286. {
  3287. $output=$this->renderPartial($view,$data,true);
  3288. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3289. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3290. $this->afterRender($view,$output);
  3291. $output=$this->processOutput($output);
  3292. if($return)
  3293. return $output;
  3294. else
  3295. echo $output;
  3296. }
  3297. }
  3298. protected function beforeRender($view)
  3299. {
  3300. return true;
  3301. }
  3302. protected function afterRender($view, &$output)
  3303. {
  3304. }
  3305. public function renderText($text,$return=false)
  3306. {
  3307. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3308. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3309. $text=$this->processOutput($text);
  3310. if($return)
  3311. return $text;
  3312. else
  3313. echo $text;
  3314. }
  3315. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3316. {
  3317. if(($viewFile=$this->getViewFile($view))!==false)
  3318. {
  3319. $output=$this->renderFile($viewFile,$data,true);
  3320. if($processOutput)
  3321. $output=$this->processOutput($output);
  3322. if($return)
  3323. return $output;
  3324. else
  3325. echo $output;
  3326. }
  3327. else
  3328. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3329. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3330. }
  3331. public function renderDynamic($callback)
  3332. {
  3333. $n=count($this->_dynamicOutput);
  3334. echo "<###dynamic-$n###>";
  3335. $params=func_get_args();
  3336. array_shift($params);
  3337. $this->renderDynamicInternal($callback,$params);
  3338. }
  3339. public function renderDynamicInternal($callback,$params)
  3340. {
  3341. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3342. if(is_string($callback) && method_exists($this,$callback))
  3343. $callback=array($this,$callback);
  3344. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3345. }
  3346. public function createUrl($route,$params=array(),$ampersand='&')
  3347. {
  3348. if($route==='')
  3349. $route=$this->getId().'/'.$this->getAction()->getId();
  3350. else if(strpos($route,'/')===false)
  3351. $route=$this->getId().'/'.$route;
  3352. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3353. $route=$module->getId().'/'.$route;
  3354. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3355. }
  3356. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3357. {
  3358. return Yii::app()->getRequest()->getHostInfo($schema).$this->createUrl($route,$params,$ampersand);
  3359. }
  3360. public function getPageTitle()
  3361. {
  3362. if($this->_pageTitle!==null)
  3363. return $this->_pageTitle;
  3364. else
  3365. {
  3366. $name=ucfirst(basename($this->getId()));
  3367. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3368. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3369. else
  3370. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3371. }
  3372. }
  3373. public function setPageTitle($value)
  3374. {
  3375. $this->_pageTitle=$value;
  3376. }
  3377. public function redirect($url,$terminate=true,$statusCode=302)
  3378. {
  3379. if(is_array($url))
  3380. {
  3381. $route=isset($url[0]) ? $url[0] : '';
  3382. $url=$this->createUrl($route,array_splice($url,1));
  3383. }
  3384. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  3385. }
  3386. public function refresh($terminate=true,$anchor='')
  3387. {
  3388. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  3389. }
  3390. public function recordCachingAction($context,$method,$params)
  3391. {
  3392. if($this->_cachingStack) // record only when there is an active output cache
  3393. {
  3394. foreach($this->_cachingStack as $cache)
  3395. $cache->recordAction($context,$method,$params);
  3396. }
  3397. }
  3398. public function getCachingStack($createIfNull=true)
  3399. {
  3400. if(!$this->_cachingStack)
  3401. $this->_cachingStack=new CStack;
  3402. return $this->_cachingStack;
  3403. }
  3404. public function isCachingStackEmpty()
  3405. {
  3406. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  3407. }
  3408. protected function beforeAction($action)
  3409. {
  3410. return true;
  3411. }
  3412. protected function afterAction($action)
  3413. {
  3414. }
  3415. public function filterPostOnly($filterChain)
  3416. {
  3417. if(Yii::app()->getRequest()->getIsPostRequest())
  3418. $filterChain->run();
  3419. else
  3420. throw new CHttpException(400,Yii::t('yii','Your request is not valid.'));
  3421. }
  3422. public function filterAjaxOnly($filterChain)
  3423. {
  3424. if(Yii::app()->getRequest()->getIsAjaxRequest())
  3425. $filterChain->run();
  3426. else
  3427. throw new CHttpException(400,Yii::t('yii','Your request is not valid.'));
  3428. }
  3429. public function filterAccessControl($filterChain)
  3430. {
  3431. $filter=new CAccessControlFilter;
  3432. $filter->setRules($this->accessRules());
  3433. $filter->filter($filterChain);
  3434. }
  3435. public function paginate($itemCount,$pageSize=null,$pageVar=null)
  3436. {
  3437. $pages=new CPagination($itemCount);
  3438. if($pageSize!==null)
  3439. $pages->pageSize=$pageSize;
  3440. if($pageVar!==null)
  3441. $pages->pageVar=$pageVar;
  3442. return $pages;
  3443. }
  3444. public function getPageState($name,$defaultValue=null)
  3445. {
  3446. if($this->_pageStates===null)
  3447. $this->_pageStates=$this->loadPageStates();
  3448. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  3449. }
  3450. public function setPageState($name,$value,$defaultValue=null)
  3451. {
  3452. if($this->_pageStates===null)
  3453. $this->_pageStates=$this->loadPageStates();
  3454. if($value===$defaultValue)
  3455. unset($this->_pageStates[$name]);
  3456. else
  3457. $this->_pageStates[$name]=$value;
  3458. $params=func_get_args();
  3459. $this->recordCachingAction('','setPageState',$params);
  3460. }
  3461. public function clearPageStates()
  3462. {
  3463. $this->_pageStates=array();
  3464. }
  3465. protected function loadPageStates()
  3466. {
  3467. if(!empty($_POST[self::STATE_INPUT_NAME]))
  3468. {
  3469. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  3470. {
  3471. if(extension_loaded('zlib'))
  3472. $data=@gzuncompress($data);
  3473. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  3474. return unserialize($data);
  3475. }
  3476. }
  3477. return array();
  3478. }
  3479. protected function savePageStates($states,&$output)
  3480. {
  3481. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  3482. if(extension_loaded('zlib'))
  3483. $data=gzcompress($data);
  3484. $value=base64_encode($data);
  3485. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  3486. }
  3487. }
  3488. abstract class CAction extends CComponent implements IAction
  3489. {
  3490. private $_id;
  3491. private $_controller;
  3492. public function __construct($controller,$id)
  3493. {
  3494. $this->_controller=$controller;
  3495. $this->_id=$id;
  3496. }
  3497. public function getController()
  3498. {
  3499. return $this->_controller;
  3500. }
  3501. public function getId()
  3502. {
  3503. return $this->_id;
  3504. }
  3505. }
  3506. class CInlineAction extends CAction
  3507. {
  3508. public function run()
  3509. {
  3510. $controller=$this->getController();
  3511. $methodName='action'.$this->getId();
  3512. $method=new ReflectionMethod($controller,$methodName);
  3513. if(($n=$method->getNumberOfParameters())>0)
  3514. {
  3515. $params=array();
  3516. foreach($method->getParameters() as $i=>$param)
  3517. {
  3518. $name=$param->getName();
  3519. if(isset($_GET[$name]))
  3520. {
  3521. if($param->isArray())
  3522. $params[]=is_array($_GET[$name]) ? $_GET[$name] : array($_GET[$name]);
  3523. else if(!is_array($_GET[$name]))
  3524. $params[]=$_GET[$name];
  3525. else
  3526. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3527. }
  3528. else if($param->isDefaultValueAvailable())
  3529. $params[]=$param->getDefaultValue();
  3530. else
  3531. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3532. }
  3533. $method->invokeArgs($controller,$params);
  3534. }
  3535. else
  3536. $controller->$methodName();
  3537. }
  3538. }
  3539. class CWebUser extends CApplicationComponent implements IWebUser
  3540. {
  3541. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  3542. const FLASH_COUNTERS='Yii.CWebUser.flash.counters';
  3543. const STATES_VAR='__states';
  3544. public $allowAutoLogin=false;
  3545. public $guestName='Guest';
  3546. public $loginUrl=array('/site/login');
  3547. public $identityCookie;
  3548. public $autoRenewCookie=false;
  3549. private $_keyPrefix;
  3550. private $_access=array();
  3551. public function __get($name)
  3552. {
  3553. if($this->hasState($name))
  3554. return $this->getState($name);
  3555. else
  3556. return parent::__get($name);
  3557. }
  3558. public function __set($name,$value)
  3559. {
  3560. if($this->hasState($name))
  3561. $this->setState($name,$value);
  3562. else
  3563. parent::__set($name,$value);
  3564. }
  3565. public function __isset($name)
  3566. {
  3567. if($this->hasState($name))
  3568. return $this->getState($name)!==null;
  3569. else
  3570. return parent::__isset($name);
  3571. }
  3572. public function __unset($name)
  3573. {
  3574. if($this->hasState($name))
  3575. $this->setState($name,null);
  3576. else
  3577. parent::__unset($name);
  3578. }
  3579. public function init()
  3580. {
  3581. parent::init();
  3582. Yii::app()->getSession()->open();
  3583. if($this->getIsGuest() && $this->allowAutoLogin)
  3584. $this->restoreFromCookie();
  3585. else if($this->autoRenewCookie && $this->allowAutoLogin)
  3586. $this->renewCookie();
  3587. $this->updateFlash();
  3588. }
  3589. public function login($identity,$duration=0)
  3590. {
  3591. $id=$identity->getId();
  3592. $states=$identity->getPersistentStates();
  3593. if($this->beforeLogin($id,$states,false))
  3594. {
  3595. $this->changeIdentity($id,$identity->getName(),$states);
  3596. if($duration>0)
  3597. {
  3598. if($this->allowAutoLogin)
  3599. $this->saveToCookie($duration);
  3600. else
  3601. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  3602. array('{class}'=>get_class($this))));
  3603. }
  3604. $this->afterLogin(false);
  3605. }
  3606. }
  3607. public function logout($destroySession=true)
  3608. {
  3609. if($this->beforeLogout())
  3610. {
  3611. if($this->allowAutoLogin)
  3612. {
  3613. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  3614. if($this->identityCookie!==null)
  3615. {
  3616. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3617. $cookie->value=null;
  3618. $cookie->expire=0;
  3619. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  3620. }
  3621. }
  3622. if($destroySession)
  3623. Yii::app()->getSession()->destroy();
  3624. else
  3625. $this->clearStates();
  3626. $this->afterLogout();
  3627. }
  3628. }
  3629. public function getIsGuest()
  3630. {
  3631. return $this->getState('__id')===null;
  3632. }
  3633. public function getId()
  3634. {
  3635. return $this->getState('__id');
  3636. }
  3637. public function setId($value)
  3638. {
  3639. $this->setState('__id',$value);
  3640. }
  3641. public function getName()
  3642. {
  3643. if(($name=$this->getState('__name'))!==null)
  3644. return $name;
  3645. else
  3646. return $this->guestName;
  3647. }
  3648. public function setName($value)
  3649. {
  3650. $this->setState('__name',$value);
  3651. }
  3652. public function getReturnUrl()
  3653. {
  3654. return $this->getState('__returnUrl',Yii::app()->getRequest()->getScriptUrl());
  3655. }
  3656. public function setReturnUrl($value)
  3657. {
  3658. $this->setState('__returnUrl',$value);
  3659. }
  3660. public function loginRequired()
  3661. {
  3662. $app=Yii::app();
  3663. $request=$app->getRequest();
  3664. if(!$request->getIsAjaxRequest())
  3665. $this->setReturnUrl($request->getUrl());
  3666. if(($url=$this->loginUrl)!==null)
  3667. {
  3668. if(is_array($url))
  3669. {
  3670. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  3671. $url=$app->createUrl($route,array_splice($url,1));
  3672. }
  3673. $request->redirect($url);
  3674. }
  3675. else
  3676. throw new CHttpException(403,Yii::t('yii','Login Required'));
  3677. }
  3678. protected function beforeLogin($id,$states,$fromCookie)
  3679. {
  3680. return true;
  3681. }
  3682. protected function afterLogin($fromCookie)
  3683. {
  3684. }
  3685. protected function beforeLogout()
  3686. {
  3687. return true;
  3688. }
  3689. protected function afterLogout()
  3690. {
  3691. }
  3692. protected function restoreFromCookie()
  3693. {
  3694. $app=Yii::app();
  3695. $cookie=$app->getRequest()->getCookies()->itemAt($this->getStateKeyPrefix());
  3696. if($cookie && !empty($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  3697. {
  3698. $data=@unserialize($data);
  3699. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3700. {
  3701. list($id,$name,$duration,$states)=$data;
  3702. if($this->beforeLogin($id,$states,true))
  3703. {
  3704. $this->changeIdentity($id,$name,$states);
  3705. if($this->autoRenewCookie)
  3706. {
  3707. $cookie->expire=time()+$duration;
  3708. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  3709. }
  3710. $this->afterLogin(true);
  3711. }
  3712. }
  3713. }
  3714. }
  3715. protected function renewCookie()
  3716. {
  3717. $cookies=Yii::app()->getRequest()->getCookies();
  3718. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  3719. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  3720. {
  3721. $data=@unserialize($data);
  3722. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3723. {
  3724. $cookie->expire=time()+$data[2];
  3725. $cookies->add($cookie->name,$cookie);
  3726. }
  3727. }
  3728. }
  3729. protected function saveToCookie($duration)
  3730. {
  3731. $app=Yii::app();
  3732. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3733. $cookie->expire=time()+$duration;
  3734. $data=array(
  3735. $this->getId(),
  3736. $this->getName(),
  3737. $duration,
  3738. $this->saveIdentityStates(),
  3739. );
  3740. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  3741. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  3742. }
  3743. protected function createIdentityCookie($name)
  3744. {
  3745. $cookie=new CHttpCookie($name,'');
  3746. if(is_array($this->identityCookie))
  3747. {
  3748. foreach($this->identityCookie as $name=>$value)
  3749. $cookie->$name=$value;
  3750. }
  3751. return $cookie;
  3752. }
  3753. public function getStateKeyPrefix()
  3754. {
  3755. if($this->_keyPrefix!==null)
  3756. return $this->_keyPrefix;
  3757. else
  3758. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  3759. }
  3760. public function setStateKeyPrefix($value)
  3761. {
  3762. $this->_keyPrefix=$value;
  3763. }
  3764. public function getState($key,$defaultValue=null)
  3765. {
  3766. $key=$this->getStateKeyPrefix().$key;
  3767. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  3768. }
  3769. public function setState($key,$value,$defaultValue=null)
  3770. {
  3771. $key=$this->getStateKeyPrefix().$key;
  3772. if($value===$defaultValue)
  3773. unset($_SESSION[$key]);
  3774. else
  3775. $_SESSION[$key]=$value;
  3776. }
  3777. public function hasState($key)
  3778. {
  3779. $key=$this->getStateKeyPrefix().$key;
  3780. return isset($_SESSION[$key]);
  3781. }
  3782. public function clearStates()
  3783. {
  3784. $keys=array_keys($_SESSION);
  3785. $prefix=$this->getStateKeyPrefix();
  3786. $n=strlen($prefix);
  3787. foreach($keys as $key)
  3788. {
  3789. if(!strncmp($key,$prefix,$n))
  3790. unset($_SESSION[$key]);
  3791. }
  3792. }
  3793. public function getFlashes($delete=true)
  3794. {
  3795. $flashes=array();
  3796. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  3797. $keys=array_keys($_SESSION);
  3798. $n=strlen($prefix);
  3799. foreach($keys as $key)
  3800. {
  3801. if(!strncmp($key,$prefix,$n))
  3802. {
  3803. $flashes[substr($key,$n)]=$_SESSION[$key];
  3804. if($delete)
  3805. unset($_SESSION[$key]);
  3806. }
  3807. }
  3808. if($delete)
  3809. $this->setState(self::FLASH_COUNTERS,array());
  3810. return $flashes;
  3811. }
  3812. public function getFlash($key,$defaultValue=null,$delete=true)
  3813. {
  3814. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  3815. if($delete)
  3816. $this->setFlash($key,null);
  3817. return $value;
  3818. }
  3819. public function setFlash($key,$value,$defaultValue=null)
  3820. {
  3821. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  3822. $counters=$this->getState(self::FLASH_COUNTERS,array());
  3823. if($value===$defaultValue)
  3824. unset($counters[$key]);
  3825. else
  3826. $counters[$key]=0;
  3827. $this->setState(self::FLASH_COUNTERS,$counters,array());
  3828. }
  3829. public function hasFlash($key)
  3830. {
  3831. return $this->getFlash($key, null, false)!==null;
  3832. }
  3833. protected function changeIdentity($id,$name,$states)
  3834. {
  3835. $this->setId($id);
  3836. $this->setName($name);
  3837. $this->loadIdentityStates($states);
  3838. }
  3839. protected function saveIdentityStates()
  3840. {
  3841. $states=array();
  3842. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  3843. $states[$name]=$this->getState($name);
  3844. return $states;
  3845. }
  3846. protected function loadIdentityStates($states)
  3847. {
  3848. $names=array();
  3849. if(is_array($states))
  3850. {
  3851. foreach($states as $name=>$value)
  3852. {
  3853. $this->setState($name,$value);
  3854. $names[$name]=true;
  3855. }
  3856. }
  3857. $this->setState(self::STATES_VAR,$names);
  3858. }
  3859. protected function updateFlash()
  3860. {
  3861. $counters=$this->getState(self::FLASH_COUNTERS);
  3862. if(!is_array($counters))
  3863. return;
  3864. foreach($counters as $key=>$count)
  3865. {
  3866. if($count)
  3867. {
  3868. unset($counters[$key]);
  3869. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  3870. }
  3871. else
  3872. $counters[$key]++;
  3873. }
  3874. $this->setState(self::FLASH_COUNTERS,$counters,array());
  3875. }
  3876. public function checkAccess($operation,$params=array(),$allowCaching=true)
  3877. {
  3878. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  3879. return $this->_access[$operation];
  3880. else
  3881. return $this->_access[$operation]=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  3882. }
  3883. }
  3884. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  3885. {
  3886. public $autoStart=true;
  3887. public function init()
  3888. {
  3889. parent::init();
  3890. if($this->autoStart)
  3891. $this->open();
  3892. register_shutdown_function(array($this,'close'));
  3893. }
  3894. public function getUseCustomStorage()
  3895. {
  3896. return false;
  3897. }
  3898. public function open()
  3899. {
  3900. if($this->getUseCustomStorage())
  3901. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  3902. @session_start();
  3903. }
  3904. public function close()
  3905. {
  3906. if(session_id()!=='')
  3907. @session_write_close();
  3908. }
  3909. public function destroy()
  3910. {
  3911. if(session_id()!=='')
  3912. {
  3913. @session_unset();
  3914. @session_destroy();
  3915. }
  3916. }
  3917. public function getIsStarted()
  3918. {
  3919. return session_id()!=='';
  3920. }
  3921. public function getSessionID()
  3922. {
  3923. return session_id();
  3924. }
  3925. public function setSessionID($value)
  3926. {
  3927. session_id($value);
  3928. }
  3929. public function getSessionName()
  3930. {
  3931. return session_name();
  3932. }
  3933. public function setSessionName($value)
  3934. {
  3935. session_name($value);
  3936. }
  3937. public function getSavePath()
  3938. {
  3939. return session_save_path();
  3940. }
  3941. public function setSavePath($value)
  3942. {
  3943. if(is_dir($value))
  3944. session_save_path($value);
  3945. else
  3946. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  3947. array('{path}'=>$value)));
  3948. }
  3949. public function getCookieParams()
  3950. {
  3951. return session_get_cookie_params();
  3952. }
  3953. public function setCookieParams($value)
  3954. {
  3955. $data=session_get_cookie_params();
  3956. extract($data);
  3957. extract($value);
  3958. if(isset($httponly))
  3959. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  3960. else
  3961. session_set_cookie_params($lifetime,$path,$domain,$secure);
  3962. }
  3963. public function getCookieMode()
  3964. {
  3965. if(ini_get('session.use_cookies')==='0')
  3966. return 'none';
  3967. else if(ini_get('session.use_only_cookies')==='0')
  3968. return 'allow';
  3969. else
  3970. return 'only';
  3971. }
  3972. public function setCookieMode($value)
  3973. {
  3974. if($value==='none')
  3975. ini_set('session.use_cookies','0');
  3976. else if($value==='allow')
  3977. {
  3978. ini_set('session.use_cookies','1');
  3979. ini_set('session.use_only_cookies','0');
  3980. }
  3981. else if($value==='only')
  3982. {
  3983. ini_set('session.use_cookies','1');
  3984. ini_set('session.use_only_cookies','1');
  3985. }
  3986. else
  3987. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  3988. }
  3989. public function getGCProbability()
  3990. {
  3991. return (int)ini_get('session.gc_probability');
  3992. }
  3993. public function setGCProbability($value)
  3994. {
  3995. $value=(int)$value;
  3996. if($value>=0 && $value<=100)
  3997. {
  3998. ini_set('session.gc_probability',$value);
  3999. ini_set('session.gc_divisor','100');
  4000. }
  4001. else
  4002. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be an integer between 0 and 100.',
  4003. array('{value}'=>$value)));
  4004. }
  4005. public function getUseTransparentSessionID()
  4006. {
  4007. return ini_get('session.use_trans_sid')==1;
  4008. }
  4009. public function setUseTransparentSessionID($value)
  4010. {
  4011. ini_set('session.use_trans_sid',$value?'1':'0');
  4012. }
  4013. public function getTimeout()
  4014. {
  4015. return (int)ini_get('session.gc_maxlifetime');
  4016. }
  4017. public function setTimeout($value)
  4018. {
  4019. ini_set('session.gc_maxlifetime',$value);
  4020. }
  4021. public function openSession($savePath,$sessionName)
  4022. {
  4023. return true;
  4024. }
  4025. public function closeSession()
  4026. {
  4027. return true;
  4028. }
  4029. public function readSession($id)
  4030. {
  4031. return '';
  4032. }
  4033. public function writeSession($id,$data)
  4034. {
  4035. return true;
  4036. }
  4037. public function destroySession($id)
  4038. {
  4039. return true;
  4040. }
  4041. public function gcSession($maxLifetime)
  4042. {
  4043. return true;
  4044. }
  4045. //------ The following methods enable CHttpSession to be CMap-like -----
  4046. public function getIterator()
  4047. {
  4048. return new CHttpSessionIterator;
  4049. }
  4050. public function getCount()
  4051. {
  4052. return count($_SESSION);
  4053. }
  4054. public function count()
  4055. {
  4056. return $this->getCount();
  4057. }
  4058. public function getKeys()
  4059. {
  4060. return array_keys($_SESSION);
  4061. }
  4062. public function get($key,$defaultValue=null)
  4063. {
  4064. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4065. }
  4066. public function itemAt($key)
  4067. {
  4068. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4069. }
  4070. public function add($key,$value)
  4071. {
  4072. $_SESSION[$key]=$value;
  4073. }
  4074. public function remove($key)
  4075. {
  4076. if(isset($_SESSION[$key]))
  4077. {
  4078. $value=$_SESSION[$key];
  4079. unset($_SESSION[$key]);
  4080. return $value;
  4081. }
  4082. else
  4083. return null;
  4084. }
  4085. public function clear()
  4086. {
  4087. foreach(array_keys($_SESSION) as $key)
  4088. unset($_SESSION[$key]);
  4089. }
  4090. public function contains($key)
  4091. {
  4092. return isset($_SESSION[$key]);
  4093. }
  4094. public function toArray()
  4095. {
  4096. return $_SESSION;
  4097. }
  4098. public function offsetExists($offset)
  4099. {
  4100. return isset($_SESSION[$offset]);
  4101. }
  4102. public function offsetGet($offset)
  4103. {
  4104. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4105. }
  4106. public function offsetSet($offset,$item)
  4107. {
  4108. $_SESSION[$offset]=$item;
  4109. }
  4110. public function offsetUnset($offset)
  4111. {
  4112. unset($_SESSION[$offset]);
  4113. }
  4114. }
  4115. class CHtml
  4116. {
  4117. const ID_PREFIX='yt';
  4118. public static $errorSummaryCss='errorSummary';
  4119. public static $errorMessageCss='errorMessage';
  4120. public static $errorCss='error';
  4121. public static $requiredCss='required';
  4122. public static $beforeRequiredLabel='';
  4123. public static $afterRequiredLabel=' <span class="required">*</span>';
  4124. public static $count=0;
  4125. public static function encode($text)
  4126. {
  4127. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4128. }
  4129. public static function encodeArray($data)
  4130. {
  4131. $d=array();
  4132. foreach($data as $key=>$value)
  4133. {
  4134. if(is_string($key))
  4135. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4136. if(is_string($value))
  4137. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4138. else if(is_array($value))
  4139. $value=self::encodeArray($value);
  4140. $d[$key]=$value;
  4141. }
  4142. return $d;
  4143. }
  4144. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4145. {
  4146. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4147. if($content===false)
  4148. return $closeTag ? $html.' />' : $html.'>';
  4149. else
  4150. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4151. }
  4152. public static function openTag($tag,$htmlOptions=array())
  4153. {
  4154. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4155. }
  4156. public static function closeTag($tag)
  4157. {
  4158. return '</'.$tag.'>';
  4159. }
  4160. public static function cdata($text)
  4161. {
  4162. return '<![CDATA[' . $text . ']]>';
  4163. }
  4164. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4165. {
  4166. if($name!==null)
  4167. $options['name']=$name;
  4168. if($httpEquiv!==null)
  4169. $options['http-equiv']=$httpEquiv;
  4170. $options['content']=$content;
  4171. return self::tag('meta',$options);
  4172. }
  4173. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4174. {
  4175. if($relation!==null)
  4176. $options['rel']=$relation;
  4177. if($type!==null)
  4178. $options['type']=$type;
  4179. if($href!==null)
  4180. $options['href']=$href;
  4181. if($media!==null)
  4182. $options['media']=$media;
  4183. return self::tag('link',$options);
  4184. }
  4185. public static function css($text,$media='')
  4186. {
  4187. if($media!=='')
  4188. $media=' media="'.$media.'"';
  4189. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4190. }
  4191. public static function refresh($seconds, $url='')
  4192. {
  4193. $content="$seconds";
  4194. if($url!=='')
  4195. $content.=';'.self::normalizeUrl($url);
  4196. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4197. }
  4198. public static function cssFile($url,$media='')
  4199. {
  4200. if($media!=='')
  4201. $media=' media="'.$media.'"';
  4202. return '<link rel="stylesheet" type="text/css" href="'.self::encode($url).'"'.$media.' />';
  4203. }
  4204. public static function script($text)
  4205. {
  4206. return "<script type=\"text/javascript\">\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</script>";
  4207. }
  4208. public static function scriptFile($url)
  4209. {
  4210. return '<script type="text/javascript" src="'.self::encode($url).'"></script>';
  4211. }
  4212. public static function form($action='',$method='post',$htmlOptions=array())
  4213. {
  4214. return self::beginForm($action,$method,$htmlOptions);
  4215. }
  4216. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4217. {
  4218. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4219. $htmlOptions['method']=$method;
  4220. $form=self::tag('form',$htmlOptions,false,false);
  4221. $hiddens=array();
  4222. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4223. {
  4224. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4225. {
  4226. if(($pos=strpos($pair,'='))!==false)
  4227. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4228. }
  4229. }
  4230. $request=Yii::app()->request;
  4231. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4232. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4233. if($hiddens!==array())
  4234. $form.="\n".self::tag('div',array('style'=>'display:none'),implode("\n",$hiddens));
  4235. return $form;
  4236. }
  4237. public static function endForm()
  4238. {
  4239. return '</form>';
  4240. }
  4241. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4242. {
  4243. return self::form($action,$method,$htmlOptions)."\n".
  4244. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4245. }
  4246. public static function pageStateField($value)
  4247. {
  4248. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4249. }
  4250. public static function link($text,$url='#',$htmlOptions=array())
  4251. {
  4252. if($url!=='')
  4253. $htmlOptions['href']=self::normalizeUrl($url);
  4254. self::clientChange('click',$htmlOptions);
  4255. return self::tag('a',$htmlOptions,$text);
  4256. }
  4257. public static function mailto($text,$email='',$htmlOptions=array())
  4258. {
  4259. if($email==='')
  4260. $email=$text;
  4261. return self::link($text,'mailto:'.$email,$htmlOptions);
  4262. }
  4263. public static function image($src,$alt='',$htmlOptions=array())
  4264. {
  4265. $htmlOptions['src']=$src;
  4266. $htmlOptions['alt']=$alt;
  4267. return self::tag('img',$htmlOptions);
  4268. }
  4269. public static function button($label='button',$htmlOptions=array())
  4270. {
  4271. if(!isset($htmlOptions['name']))
  4272. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4273. if(!isset($htmlOptions['type']))
  4274. $htmlOptions['type']='button';
  4275. if(!isset($htmlOptions['value']))
  4276. $htmlOptions['value']=$label;
  4277. self::clientChange('click',$htmlOptions);
  4278. return self::tag('input',$htmlOptions);
  4279. }
  4280. public static function htmlButton($label='button',$htmlOptions=array())
  4281. {
  4282. if(!isset($htmlOptions['name']))
  4283. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4284. if(!isset($htmlOptions['type']))
  4285. $htmlOptions['type']='button';
  4286. self::clientChange('click',$htmlOptions);
  4287. return self::tag('button',$htmlOptions,$label);
  4288. }
  4289. public static function submitButton($label='submit',$htmlOptions=array())
  4290. {
  4291. $htmlOptions['type']='submit';
  4292. return self::button($label,$htmlOptions);
  4293. }
  4294. public static function resetButton($label='reset',$htmlOptions=array())
  4295. {
  4296. $htmlOptions['type']='reset';
  4297. return self::button($label,$htmlOptions);
  4298. }
  4299. public static function imageButton($src,$htmlOptions=array())
  4300. {
  4301. $htmlOptions['src']=$src;
  4302. $htmlOptions['type']='image';
  4303. return self::button('submit',$htmlOptions);
  4304. }
  4305. public static function linkButton($label='submit',$htmlOptions=array())
  4306. {
  4307. if(!isset($htmlOptions['submit']))
  4308. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  4309. return self::link($label,'#',$htmlOptions);
  4310. }
  4311. public static function label($label,$for,$htmlOptions=array())
  4312. {
  4313. if($for===false)
  4314. unset($htmlOptions['for']);
  4315. else
  4316. $htmlOptions['for']=$for;
  4317. if(isset($htmlOptions['required']))
  4318. {
  4319. if($htmlOptions['required'])
  4320. {
  4321. if(isset($htmlOptions['class']))
  4322. $htmlOptions['class'].=' '.self::$requiredCss;
  4323. else
  4324. $htmlOptions['class']=self::$requiredCss;
  4325. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  4326. }
  4327. unset($htmlOptions['required']);
  4328. }
  4329. return self::tag('label',$htmlOptions,$label);
  4330. }
  4331. public static function textField($name,$value='',$htmlOptions=array())
  4332. {
  4333. self::clientChange('change',$htmlOptions);
  4334. return self::inputField('text',$name,$value,$htmlOptions);
  4335. }
  4336. public static function hiddenField($name,$value='',$htmlOptions=array())
  4337. {
  4338. return self::inputField('hidden',$name,$value,$htmlOptions);
  4339. }
  4340. public static function passwordField($name,$value='',$htmlOptions=array())
  4341. {
  4342. self::clientChange('change',$htmlOptions);
  4343. return self::inputField('password',$name,$value,$htmlOptions);
  4344. }
  4345. public static function fileField($name,$value='',$htmlOptions=array())
  4346. {
  4347. return self::inputField('file',$name,$value,$htmlOptions);
  4348. }
  4349. public static function textArea($name,$value='',$htmlOptions=array())
  4350. {
  4351. $htmlOptions['name']=$name;
  4352. if(!isset($htmlOptions['id']))
  4353. $htmlOptions['id']=self::getIdByName($name);
  4354. else if($htmlOptions['id']===false)
  4355. unset($htmlOptions['id']);
  4356. self::clientChange('change',$htmlOptions);
  4357. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  4358. }
  4359. public static function radioButton($name,$checked=false,$htmlOptions=array())
  4360. {
  4361. if($checked)
  4362. $htmlOptions['checked']='checked';
  4363. else
  4364. unset($htmlOptions['checked']);
  4365. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4366. self::clientChange('click',$htmlOptions);
  4367. if(array_key_exists('uncheckValue',$htmlOptions))
  4368. {
  4369. $uncheck=$htmlOptions['uncheckValue'];
  4370. unset($htmlOptions['uncheckValue']);
  4371. }
  4372. else
  4373. $uncheck=null;
  4374. if($uncheck!==null)
  4375. {
  4376. // add a hidden field so that if the radio button is not selected, it still submits a value
  4377. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4378. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4379. else
  4380. $uncheckOptions=array('id'=>false);
  4381. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4382. }
  4383. else
  4384. $hidden='';
  4385. // add a hidden field so that if the radio button is not selected, it still submits a value
  4386. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  4387. }
  4388. public static function checkBox($name,$checked=false,$htmlOptions=array())
  4389. {
  4390. if($checked)
  4391. $htmlOptions['checked']='checked';
  4392. else
  4393. unset($htmlOptions['checked']);
  4394. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4395. self::clientChange('click',$htmlOptions);
  4396. if(array_key_exists('uncheckValue',$htmlOptions))
  4397. {
  4398. $uncheck=$htmlOptions['uncheckValue'];
  4399. unset($htmlOptions['uncheckValue']);
  4400. }
  4401. else
  4402. $uncheck=null;
  4403. if($uncheck!==null)
  4404. {
  4405. // add a hidden field so that if the radio button is not selected, it still submits a value
  4406. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4407. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4408. else
  4409. $uncheckOptions=array('id'=>false);
  4410. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4411. }
  4412. else
  4413. $hidden='';
  4414. // add a hidden field so that if the checkbox is not selected, it still submits a value
  4415. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  4416. }
  4417. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  4418. {
  4419. $htmlOptions['name']=$name;
  4420. if(!isset($htmlOptions['id']))
  4421. $htmlOptions['id']=self::getIdByName($name);
  4422. else if($htmlOptions['id']===false)
  4423. unset($htmlOptions['id']);
  4424. self::clientChange('change',$htmlOptions);
  4425. $options="\n".self::listOptions($select,$data,$htmlOptions);
  4426. return self::tag('select',$htmlOptions,$options);
  4427. }
  4428. public static function listBox($name,$select,$data,$htmlOptions=array())
  4429. {
  4430. if(!isset($htmlOptions['size']))
  4431. $htmlOptions['size']=4;
  4432. if(isset($htmlOptions['multiple']))
  4433. {
  4434. if(substr($name,-2)!=='[]')
  4435. $name.='[]';
  4436. }
  4437. return self::dropDownList($name,$select,$data,$htmlOptions);
  4438. }
  4439. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  4440. {
  4441. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4442. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4443. unset($htmlOptions['template'],$htmlOptions['separator']);
  4444. if(substr($name,-2)!=='[]')
  4445. $name.='[]';
  4446. if(isset($htmlOptions['checkAll']))
  4447. {
  4448. $checkAllLabel=$htmlOptions['checkAll'];
  4449. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  4450. }
  4451. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  4452. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4453. unset($htmlOptions['labelOptions']);
  4454. $items=array();
  4455. $baseID=self::getIdByName($name);
  4456. $id=0;
  4457. $checkAll=true;
  4458. foreach($data as $value=>$label)
  4459. {
  4460. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  4461. $checkAll=$checkAll && $checked;
  4462. $htmlOptions['value']=$value;
  4463. $htmlOptions['id']=$baseID.'_'.$id++;
  4464. $option=self::checkBox($name,$checked,$htmlOptions);
  4465. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4466. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4467. }
  4468. if(isset($checkAllLabel))
  4469. {
  4470. $htmlOptions['value']=1;
  4471. $htmlOptions['id']=$id=$baseID.'_all';
  4472. $option=self::checkBox($id,$checkAll,$htmlOptions);
  4473. $label=self::label($checkAllLabel,$id,$labelOptions);
  4474. $item=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4475. if($checkAllLast)
  4476. $items[]=$item;
  4477. else
  4478. array_unshift($items,$item);
  4479. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  4480. $js=<<<EOD
  4481. jQuery('#$id').click(function() {
  4482. jQuery("input[name='$name']").attr('checked', this.checked);
  4483. });
  4484. jQuery("input[name='$name']").click(function() {
  4485. jQuery('#$id').attr('checked', !jQuery("input[name='$name']:not(:checked)").length);
  4486. });
  4487. jQuery('#$id').attr('checked', !jQuery("input[name='$name']:not(:checked)").length);
  4488. EOD;
  4489. $cs=Yii::app()->getClientScript();
  4490. $cs->registerCoreScript('jquery');
  4491. $cs->registerScript($id,$js);
  4492. }
  4493. return implode($separator,$items);
  4494. }
  4495. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  4496. {
  4497. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4498. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4499. unset($htmlOptions['template'],$htmlOptions['separator']);
  4500. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4501. unset($htmlOptions['labelOptions']);
  4502. $items=array();
  4503. $baseID=self::getIdByName($name);
  4504. $id=0;
  4505. foreach($data as $value=>$label)
  4506. {
  4507. $checked=!strcmp($value,$select);
  4508. $htmlOptions['value']=$value;
  4509. $htmlOptions['id']=$baseID.'_'.$id++;
  4510. $option=self::radioButton($name,$checked,$htmlOptions);
  4511. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4512. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4513. }
  4514. return implode($separator,$items);
  4515. }
  4516. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  4517. {
  4518. if(!isset($htmlOptions['href']))
  4519. $htmlOptions['href']='#';
  4520. $ajaxOptions['url']=$url;
  4521. $htmlOptions['ajax']=$ajaxOptions;
  4522. self::clientChange('click',$htmlOptions);
  4523. return self::tag('a',$htmlOptions,$text);
  4524. }
  4525. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4526. {
  4527. $ajaxOptions['url']=$url;
  4528. $htmlOptions['ajax']=$ajaxOptions;
  4529. return self::button($label,$htmlOptions);
  4530. }
  4531. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4532. {
  4533. $ajaxOptions['type']='POST';
  4534. $htmlOptions['type']='submit';
  4535. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  4536. }
  4537. public static function ajax($options)
  4538. {
  4539. Yii::app()->getClientScript()->registerCoreScript('jquery');
  4540. if(!isset($options['url']))
  4541. $options['url']='js:location.href';
  4542. else
  4543. $options['url']=self::normalizeUrl($options['url']);
  4544. if(!isset($options['cache']))
  4545. $options['cache']=false;
  4546. if(!isset($options['data']) && isset($options['type']))
  4547. $options['data']='js:jQuery(this).parents("form").serialize()';
  4548. foreach(array('beforeSend','complete','error','success') as $name)
  4549. {
  4550. if(isset($options[$name]) && strpos($options[$name],'js:')!==0)
  4551. $options[$name]='js:'.$options[$name];
  4552. }
  4553. if(isset($options['update']))
  4554. {
  4555. if(!isset($options['success']))
  4556. $options['success']='js:function(html){jQuery("'.$options['update'].'").html(html)}';
  4557. unset($options['update']);
  4558. }
  4559. if(isset($options['replace']))
  4560. {
  4561. if(!isset($options['success']))
  4562. $options['success']='js:function(html){jQuery("'.$options['replace'].'").replaceWith(html)}';
  4563. unset($options['replace']);
  4564. }
  4565. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  4566. }
  4567. public static function asset($path,$hashByName=false)
  4568. {
  4569. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  4570. }
  4571. public static function normalizeUrl($url)
  4572. {
  4573. if(is_array($url))
  4574. {
  4575. if(isset($url[0]))
  4576. {
  4577. if(($c=Yii::app()->getController())!==null)
  4578. $url=$c->createUrl($url[0],array_splice($url,1));
  4579. else
  4580. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  4581. }
  4582. else
  4583. $url='';
  4584. }
  4585. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  4586. }
  4587. protected static function inputField($type,$name,$value,$htmlOptions)
  4588. {
  4589. $htmlOptions['type']=$type;
  4590. $htmlOptions['value']=$value;
  4591. $htmlOptions['name']=$name;
  4592. if(!isset($htmlOptions['id']))
  4593. $htmlOptions['id']=self::getIdByName($name);
  4594. else if($htmlOptions['id']===false)
  4595. unset($htmlOptions['id']);
  4596. return self::tag('input',$htmlOptions);
  4597. }
  4598. public static function activeLabel($model,$attribute,$htmlOptions=array())
  4599. {
  4600. if(isset($htmlOptions['for']))
  4601. {
  4602. $for=$htmlOptions['for'];
  4603. unset($htmlOptions['for']);
  4604. }
  4605. else
  4606. $for=self::getIdByName(self::resolveName($model,$attribute));
  4607. if(isset($htmlOptions['label']))
  4608. {
  4609. if(($label=$htmlOptions['label'])===false)
  4610. return '';
  4611. unset($htmlOptions['label']);
  4612. }
  4613. else
  4614. $label=$model->getAttributeLabel($attribute);
  4615. if($model->hasErrors($attribute))
  4616. self::addErrorCss($htmlOptions);
  4617. return self::label($label,$for,$htmlOptions);
  4618. }
  4619. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  4620. {
  4621. $realAttribute=$attribute;
  4622. self::resolveName($model,$attribute); // strip off square brackets if any
  4623. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  4624. return self::activeLabel($model,$realAttribute,$htmlOptions);
  4625. }
  4626. public static function activeTextField($model,$attribute,$htmlOptions=array())
  4627. {
  4628. self::resolveNameID($model,$attribute,$htmlOptions);
  4629. self::clientChange('change',$htmlOptions);
  4630. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  4631. }
  4632. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  4633. {
  4634. self::resolveNameID($model,$attribute,$htmlOptions);
  4635. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  4636. }
  4637. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  4638. {
  4639. self::resolveNameID($model,$attribute,$htmlOptions);
  4640. self::clientChange('change',$htmlOptions);
  4641. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  4642. }
  4643. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  4644. {
  4645. self::resolveNameID($model,$attribute,$htmlOptions);
  4646. self::clientChange('change',$htmlOptions);
  4647. if($model->hasErrors($attribute))
  4648. self::addErrorCss($htmlOptions);
  4649. $text=self::resolveValue($model,$attribute);
  4650. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  4651. }
  4652. public static function activeFileField($model,$attribute,$htmlOptions=array())
  4653. {
  4654. self::resolveNameID($model,$attribute,$htmlOptions);
  4655. // add a hidden field so that if a model only has a file field, we can
  4656. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  4657. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4658. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  4659. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  4660. }
  4661. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  4662. {
  4663. self::resolveNameID($model,$attribute,$htmlOptions);
  4664. if(!isset($htmlOptions['value']))
  4665. $htmlOptions['value']=1;
  4666. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  4667. $htmlOptions['checked']='checked';
  4668. self::clientChange('click',$htmlOptions);
  4669. if(array_key_exists('uncheckValue',$htmlOptions))
  4670. {
  4671. $uncheck=$htmlOptions['uncheckValue'];
  4672. unset($htmlOptions['uncheckValue']);
  4673. }
  4674. else
  4675. $uncheck='0';
  4676. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4677. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  4678. // add a hidden field so that if the radio button is not selected, it still submits a value
  4679. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  4680. }
  4681. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  4682. {
  4683. self::resolveNameID($model,$attribute,$htmlOptions);
  4684. if(!isset($htmlOptions['value']))
  4685. $htmlOptions['value']=1;
  4686. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  4687. $htmlOptions['checked']='checked';
  4688. self::clientChange('click',$htmlOptions);
  4689. if(array_key_exists('uncheckValue',$htmlOptions))
  4690. {
  4691. $uncheck=$htmlOptions['uncheckValue'];
  4692. unset($htmlOptions['uncheckValue']);
  4693. }
  4694. else
  4695. $uncheck='0';
  4696. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4697. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  4698. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  4699. }
  4700. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  4701. {
  4702. self::resolveNameID($model,$attribute,$htmlOptions);
  4703. $selection=self::resolveValue($model,$attribute);
  4704. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  4705. self::clientChange('change',$htmlOptions);
  4706. if($model->hasErrors($attribute))
  4707. self::addErrorCss($htmlOptions);
  4708. if(isset($htmlOptions['multiple']))
  4709. {
  4710. if(substr($htmlOptions['name'],-2)!=='[]')
  4711. $htmlOptions['name'].='[]';
  4712. }
  4713. return self::tag('select',$htmlOptions,$options);
  4714. }
  4715. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  4716. {
  4717. if(!isset($htmlOptions['size']))
  4718. $htmlOptions['size']=4;
  4719. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  4720. }
  4721. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  4722. {
  4723. self::resolveNameID($model,$attribute,$htmlOptions);
  4724. $selection=self::resolveValue($model,$attribute);
  4725. if($model->hasErrors($attribute))
  4726. self::addErrorCss($htmlOptions);
  4727. $name=$htmlOptions['name'];
  4728. unset($htmlOptions['name']);
  4729. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4730. return self::hiddenField($name,'',$hiddenOptions)
  4731. . self::checkBoxList($name,$selection,$data,$htmlOptions);
  4732. }
  4733. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  4734. {
  4735. self::resolveNameID($model,$attribute,$htmlOptions);
  4736. $selection=self::resolveValue($model,$attribute);
  4737. if($model->hasErrors($attribute))
  4738. self::addErrorCss($htmlOptions);
  4739. $name=$htmlOptions['name'];
  4740. unset($htmlOptions['name']);
  4741. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4742. return self::hiddenField($name,'',$hiddenOptions)
  4743. . self::radioButtonList($name,$selection,$data,$htmlOptions);
  4744. }
  4745. public static function getActiveId($model,$attribute)
  4746. {
  4747. return self::activeId($model,$attribute);
  4748. }
  4749. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  4750. {
  4751. $content='';
  4752. if(!is_array($model))
  4753. $model=array($model);
  4754. if(isset($htmlOptions['firstError']))
  4755. {
  4756. $firstError=$htmlOptions['firstError'];
  4757. unset($htmlOptions['firstError']);
  4758. }
  4759. else
  4760. $firstError=false;
  4761. foreach($model as $m)
  4762. {
  4763. foreach($m->getErrors() as $errors)
  4764. {
  4765. foreach($errors as $error)
  4766. {
  4767. if($error!='')
  4768. $content.="<li>$error</li>\n";
  4769. if($firstError)
  4770. break;
  4771. }
  4772. }
  4773. }
  4774. if($content!=='')
  4775. {
  4776. if($header===null)
  4777. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  4778. if(!isset($htmlOptions['class']))
  4779. $htmlOptions['class']=self::$errorSummaryCss;
  4780. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  4781. }
  4782. else
  4783. return '';
  4784. }
  4785. public static function error($model,$attribute,$htmlOptions=array())
  4786. {
  4787. $error=$model->getError($attribute);
  4788. if($error!='')
  4789. {
  4790. if(!isset($htmlOptions['class']))
  4791. $htmlOptions['class']=self::$errorMessageCss;
  4792. return self::tag('div',$htmlOptions,$error);
  4793. }
  4794. else
  4795. return '';
  4796. }
  4797. public static function listData($models,$valueField,$textField,$groupField='')
  4798. {
  4799. $listData=array();
  4800. if($groupField==='')
  4801. {
  4802. foreach($models as $model)
  4803. {
  4804. $value=self::value($model,$valueField);
  4805. $text=self::value($model,$textField);
  4806. $listData[$value]=$text;
  4807. }
  4808. }
  4809. else
  4810. {
  4811. foreach($models as $model)
  4812. {
  4813. $group=self::value($model,$groupField);
  4814. $value=self::value($model,$valueField);
  4815. $text=self::value($model,$textField);
  4816. $listData[$group][$value]=$text;
  4817. }
  4818. }
  4819. return $listData;
  4820. }
  4821. public static function value($model,$attribute,$defaultValue=null)
  4822. {
  4823. foreach(explode('.',$attribute) as $name)
  4824. {
  4825. if(is_object($model))
  4826. $model=$model->$name;
  4827. else if(is_array($model) && isset($model[$name]))
  4828. $model=$model[$name];
  4829. else
  4830. return $defaultValue;
  4831. }
  4832. return $model;
  4833. }
  4834. public static function getIdByName($name)
  4835. {
  4836. return str_replace(array('[]', '][', '[', ']'), array('', '_', '_', ''), $name);
  4837. }
  4838. public static function activeId($model,$attribute)
  4839. {
  4840. return self::getIdByName(self::activeName($model,$attribute));
  4841. }
  4842. public static function activeName($model,$attribute)
  4843. {
  4844. $a=$attribute; // because the attribute name may be changed by resolveName
  4845. return self::resolveName($model,$a);
  4846. }
  4847. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  4848. {
  4849. $htmlOptions['type']=$type;
  4850. if($type==='text' || $type==='password')
  4851. {
  4852. if(!isset($htmlOptions['maxlength']))
  4853. {
  4854. foreach($model->getValidators($attribute) as $validator)
  4855. {
  4856. if($validator instanceof CStringValidator && $validator->max!==null)
  4857. {
  4858. $htmlOptions['maxlength']=$validator->max;
  4859. break;
  4860. }
  4861. }
  4862. }
  4863. else if($htmlOptions['maxlength']===false)
  4864. unset($htmlOptions['maxlength']);
  4865. }
  4866. if($type==='file')
  4867. unset($htmlOptions['value']);
  4868. else if(!isset($htmlOptions['value']))
  4869. $htmlOptions['value']=self::resolveValue($model,$attribute);
  4870. if($model->hasErrors($attribute))
  4871. self::addErrorCss($htmlOptions);
  4872. return self::tag('input',$htmlOptions);
  4873. }
  4874. public static function listOptions($selection,$listData,&$htmlOptions)
  4875. {
  4876. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  4877. $content='';
  4878. if(isset($htmlOptions['prompt']))
  4879. {
  4880. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  4881. unset($htmlOptions['prompt']);
  4882. }
  4883. if(isset($htmlOptions['empty']))
  4884. {
  4885. if(!is_array($htmlOptions['empty']))
  4886. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  4887. foreach($htmlOptions['empty'] as $value=>$label)
  4888. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  4889. unset($htmlOptions['empty']);
  4890. }
  4891. if(isset($htmlOptions['options']))
  4892. {
  4893. $options=$htmlOptions['options'];
  4894. unset($htmlOptions['options']);
  4895. }
  4896. else
  4897. $options=array();
  4898. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  4899. if(is_array($selection))
  4900. {
  4901. foreach($selection as $i=>$item)
  4902. {
  4903. if(is_object($item))
  4904. $selection[$i]=$item->$key;
  4905. }
  4906. }
  4907. else if(is_object($selection))
  4908. $selection=$selection->$key;
  4909. foreach($listData as $key=>$value)
  4910. {
  4911. if(is_array($value))
  4912. {
  4913. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  4914. $dummy=array('options'=>$options);
  4915. if(isset($htmlOptions['encode']))
  4916. $dummy['encode']=$htmlOptions['encode'];
  4917. $content.=self::listOptions($selection,$value,$dummy);
  4918. $content.='</optgroup>'."\n";
  4919. }
  4920. else
  4921. {
  4922. $attributes=array('value'=>(string)$key, 'encode'=>!$raw);
  4923. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  4924. $attributes['selected']='selected';
  4925. if(isset($options[$key]))
  4926. $attributes=array_merge($attributes,$options[$key]);
  4927. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  4928. }
  4929. }
  4930. unset($htmlOptions['key']);
  4931. return $content;
  4932. }
  4933. protected static function clientChange($event,&$htmlOptions,$live=true)
  4934. {
  4935. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  4936. return;
  4937. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  4938. $return='return true';
  4939. else
  4940. $return='return false';
  4941. if(isset($htmlOptions['on'.$event]))
  4942. {
  4943. $handler=trim($htmlOptions['on'.$event],';').';';
  4944. unset($htmlOptions['on'.$event]);
  4945. }
  4946. else
  4947. $handler='';
  4948. if(isset($htmlOptions['id']))
  4949. $id=$htmlOptions['id'];
  4950. else
  4951. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  4952. $cs=Yii::app()->getClientScript();
  4953. $cs->registerCoreScript('jquery');
  4954. if(isset($htmlOptions['submit']))
  4955. {
  4956. $cs->registerCoreScript('yii');
  4957. $request=Yii::app()->getRequest();
  4958. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  4959. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  4960. if(isset($htmlOptions['params']))
  4961. $params=CJavaScript::encode($htmlOptions['params']);
  4962. else
  4963. $params='{}';
  4964. if($htmlOptions['submit']!=='')
  4965. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  4966. else
  4967. $url='';
  4968. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  4969. }
  4970. if(isset($htmlOptions['ajax']))
  4971. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  4972. if(isset($htmlOptions['confirm']))
  4973. {
  4974. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  4975. if($handler!=='')
  4976. $handler="if($confirm) {".$handler."} else return false;";
  4977. else
  4978. $handler="return $confirm;";
  4979. }
  4980. if($live)
  4981. $cs->registerScript('Yii.CHtml.#'.$id,"jQuery('body').delegate('#$id','$event',function(){{$handler}});");
  4982. else
  4983. $cs->registerScript('Yii.CHtml.#'.$id,"jQuery('#$id').$event(function(){{$handler}});");
  4984. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  4985. }
  4986. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  4987. {
  4988. if(!isset($htmlOptions['name']))
  4989. $htmlOptions['name']=self::resolveName($model,$attribute);
  4990. if(!isset($htmlOptions['id']))
  4991. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  4992. else if($htmlOptions['id']===false)
  4993. unset($htmlOptions['id']);
  4994. }
  4995. public static function resolveName($model,&$attribute)
  4996. {
  4997. if(($pos=strpos($attribute,'['))!==false)
  4998. {
  4999. if($pos!==0) // e.g. name[a][b]
  5000. return get_class($model).'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5001. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5002. {
  5003. $sub=substr($attribute,0,$pos+1);
  5004. $attribute=substr($attribute,$pos+1);
  5005. return get_class($model).$sub.'['.$attribute.']';
  5006. }
  5007. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5008. {
  5009. $name=get_class($model).'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5010. $attribute=$matches[1];
  5011. return $name;
  5012. }
  5013. }
  5014. else
  5015. return get_class($model).'['.$attribute.']';
  5016. }
  5017. public static function resolveValue($model,$attribute)
  5018. {
  5019. if(($pos=strpos($attribute,'['))!==false)
  5020. {
  5021. $name=substr($attribute,0,$pos);
  5022. $value=$model->$name;
  5023. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5024. {
  5025. if(is_array($value) && isset($value[$id]))
  5026. $value=$value[$id];
  5027. else
  5028. return null;
  5029. }
  5030. return $value;
  5031. }
  5032. else
  5033. return $model->$attribute;
  5034. }
  5035. protected static function addErrorCss(&$htmlOptions)
  5036. {
  5037. if(isset($htmlOptions['class']))
  5038. $htmlOptions['class'].=' '.self::$errorCss;
  5039. else
  5040. $htmlOptions['class']=self::$errorCss;
  5041. }
  5042. public static function renderAttributes($htmlOptions)
  5043. {
  5044. static $specialAttributes=array(
  5045. 'checked'=>1,
  5046. 'declare'=>1,
  5047. 'defer'=>1,
  5048. 'disabled'=>1,
  5049. 'ismap'=>1,
  5050. 'multiple'=>1,
  5051. 'nohref'=>1,
  5052. 'noresize'=>1,
  5053. 'readonly'=>1,
  5054. 'selected'=>1,
  5055. );
  5056. if($htmlOptions===array())
  5057. return '';
  5058. $html='';
  5059. if(isset($htmlOptions['encode']))
  5060. {
  5061. $raw=!$htmlOptions['encode'];
  5062. unset($htmlOptions['encode']);
  5063. }
  5064. else
  5065. $raw=false;
  5066. if($raw)
  5067. {
  5068. foreach($htmlOptions as $name=>$value)
  5069. {
  5070. if(isset($specialAttributes[$name]))
  5071. {
  5072. if($value)
  5073. $html .= ' ' . $name . '="' . $name . '"';
  5074. }
  5075. else if($value!==null)
  5076. $html .= ' ' . $name . '="' . $value . '"';
  5077. }
  5078. }
  5079. else
  5080. {
  5081. foreach($htmlOptions as $name=>$value)
  5082. {
  5083. if(isset($specialAttributes[$name]))
  5084. {
  5085. if($value)
  5086. $html .= ' ' . $name . '="' . $name . '"';
  5087. }
  5088. else if($value!==null)
  5089. $html .= ' ' . $name . '="' . self::encode($value) . '"';
  5090. }
  5091. }
  5092. return $html;
  5093. }
  5094. }
  5095. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  5096. {
  5097. public $enableSkin=false;
  5098. public $widgets=array();
  5099. public $skinnableWidgets;
  5100. public $skinPath;
  5101. private $_skins=array(); // class name, skin name, property name => value
  5102. public function init()
  5103. {
  5104. parent::init();
  5105. if($this->enableSkin && $this->skinPath===null)
  5106. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  5107. }
  5108. public function createWidget($owner,$className,$properties=array())
  5109. {
  5110. $className=Yii::import($className,true);
  5111. $widget=new $className($owner);
  5112. if(isset($this->widgets[$className]))
  5113. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  5114. if($this->enableSkin)
  5115. {
  5116. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  5117. {
  5118. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  5119. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  5120. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  5121. }
  5122. }
  5123. foreach($properties as $name=>$value)
  5124. $widget->$name=$value;
  5125. return $widget;
  5126. }
  5127. protected function getSkin($className,$skinName)
  5128. {
  5129. if(!isset($this->_skins[$className][$skinName]))
  5130. {
  5131. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  5132. if(is_file($skinFile))
  5133. $this->_skins[$className]=require($skinFile);
  5134. else
  5135. $this->_skins[$className]=array();
  5136. if(($theme=Yii::app()->getTheme())!==null)
  5137. {
  5138. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  5139. if(is_file($skinFile))
  5140. {
  5141. $skins=require($skinFile);
  5142. foreach($skins as $name=>$skin)
  5143. $this->_skins[$className][$name]=$skin;
  5144. }
  5145. }
  5146. if(!isset($this->_skins[$className][$skinName]))
  5147. $this->_skins[$className][$skinName]=array();
  5148. }
  5149. return $this->_skins[$className][$skinName];
  5150. }
  5151. }
  5152. class CWidget extends CBaseController
  5153. {
  5154. public $actionPrefix;
  5155. public $skin='default';
  5156. private static $_viewPaths;
  5157. private static $_counter=0;
  5158. private $_id;
  5159. private $_owner;
  5160. public static function actions()
  5161. {
  5162. return array();
  5163. }
  5164. public function __construct($owner=null)
  5165. {
  5166. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  5167. }
  5168. public function getOwner()
  5169. {
  5170. return $this->_owner;
  5171. }
  5172. public function getId($autoGenerate=true)
  5173. {
  5174. if($this->_id!==null)
  5175. return $this->_id;
  5176. else if($autoGenerate)
  5177. return $this->_id='yw'.self::$_counter++;
  5178. }
  5179. public function setId($value)
  5180. {
  5181. $this->_id=$value;
  5182. }
  5183. public function getController()
  5184. {
  5185. if($this->_owner instanceof CController)
  5186. return $this->_owner;
  5187. else
  5188. return Yii::app()->getController();
  5189. }
  5190. public function init()
  5191. {
  5192. }
  5193. public function run()
  5194. {
  5195. }
  5196. public function getViewPath()
  5197. {
  5198. $className=get_class($this);
  5199. if(isset(self::$_viewPaths[$className]))
  5200. return self::$_viewPaths[$className];
  5201. else
  5202. {
  5203. $class=new ReflectionClass(get_class($this));
  5204. return self::$_viewPaths[$className]=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  5205. }
  5206. }
  5207. public function getViewFile($viewName)
  5208. {
  5209. if(($renderer=Yii::app()->getViewRenderer())!==null)
  5210. $extension=$renderer->fileExtension;
  5211. else
  5212. $extension='.php';
  5213. if(strpos($viewName,'.')) // a path alias
  5214. $viewFile=Yii::getPathOfAlias($viewName);
  5215. else
  5216. {
  5217. if(($theme=Yii::app()->getTheme())!==null)
  5218. {
  5219. $className=str_replace('\\','_',ltrim(get_class($this),'\\')); // possibly namespaced class
  5220. $viewFile=$theme->getViewPath().DIRECTORY_SEPARATOR.$className.DIRECTORY_SEPARATOR.$viewName;
  5221. if(is_file($viewFile.$extension))
  5222. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5223. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5224. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5225. }
  5226. $viewFile=$this->getViewPath().DIRECTORY_SEPARATOR.$viewName;
  5227. }
  5228. if(is_file($viewFile.$extension))
  5229. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5230. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5231. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5232. else
  5233. return false;
  5234. }
  5235. public function render($view,$data=null,$return=false)
  5236. {
  5237. if(($viewFile=$this->getViewFile($view))!==false)
  5238. return $this->renderFile($viewFile,$data,$return);
  5239. else
  5240. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  5241. array('{widget}'=>get_class($this), '{view}'=>$view)));
  5242. }
  5243. }
  5244. class CClientScript extends CApplicationComponent
  5245. {
  5246. const POS_HEAD=0;
  5247. const POS_BEGIN=1;
  5248. const POS_END=2;
  5249. const POS_LOAD=3;
  5250. const POS_READY=4;
  5251. public $enableJavaScript=true;
  5252. public $scriptMap=array();
  5253. protected $cssFiles=array();
  5254. protected $scriptFiles=array();
  5255. protected $scripts=array();
  5256. protected $metaTags=array();
  5257. protected $linkTags=array();
  5258. protected $css=array();
  5259. public $coreScriptPosition=self::POS_HEAD;
  5260. private $_hasScripts=false;
  5261. private $_packages;
  5262. private $_dependencies;
  5263. private $_baseUrl;
  5264. private $_coreScripts=array();
  5265. public function reset()
  5266. {
  5267. $this->_hasScripts=false;
  5268. $this->_coreScripts=array();
  5269. $this->cssFiles=array();
  5270. $this->css=array();
  5271. $this->scriptFiles=array();
  5272. $this->scripts=array();
  5273. $this->metaTags=array();
  5274. $this->linkTags=array();
  5275. $this->recordCachingAction('clientScript','reset',array());
  5276. }
  5277. public function render(&$output)
  5278. {
  5279. if(!$this->_hasScripts)
  5280. return;
  5281. $this->renderCoreScripts();
  5282. if(!empty($this->scriptMap))
  5283. $this->remapScripts();
  5284. $this->unifyScripts();
  5285. $this->renderHead($output);
  5286. if($this->enableJavaScript)
  5287. {
  5288. $this->renderBodyBegin($output);
  5289. $this->renderBodyEnd($output);
  5290. }
  5291. }
  5292. protected function unifyScripts()
  5293. {
  5294. if(!$this->enableJavaScript)
  5295. return;
  5296. $map=array();
  5297. if(isset($this->scriptFiles[self::POS_HEAD]))
  5298. $map=$this->scriptFiles[self::POS_HEAD];
  5299. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5300. {
  5301. foreach($this->scriptFiles[self::POS_BEGIN] as $key=>$scriptFile)
  5302. {
  5303. if(isset($map[$scriptFile]))
  5304. unset($this->scriptFiles[self::POS_BEGIN][$key]);
  5305. else
  5306. $map[$scriptFile]=true;
  5307. }
  5308. }
  5309. if(isset($this->scriptFiles[self::POS_END]))
  5310. {
  5311. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  5312. {
  5313. if(isset($map[$scriptFile]))
  5314. unset($this->scriptFiles[self::POS_END][$key]);
  5315. }
  5316. }
  5317. }
  5318. protected function remapScripts()
  5319. {
  5320. $cssFiles=array();
  5321. foreach($this->cssFiles as $url=>$media)
  5322. {
  5323. $name=basename($url);
  5324. if(isset($this->scriptMap[$name]))
  5325. {
  5326. if($this->scriptMap[$name]!==false)
  5327. $cssFiles[$this->scriptMap[$name]]=$media;
  5328. }
  5329. else if(isset($this->scriptMap['*.css']))
  5330. {
  5331. if($this->scriptMap['*.css']!==false)
  5332. $cssFiles[$this->scriptMap['*.css']]=$media;
  5333. }
  5334. else
  5335. $cssFiles[$url]=$media;
  5336. }
  5337. $this->cssFiles=$cssFiles;
  5338. $jsFiles=array();
  5339. foreach($this->scriptFiles as $position=>$scripts)
  5340. {
  5341. $jsFiles[$position]=array();
  5342. foreach($scripts as $key=>$script)
  5343. {
  5344. $name=basename($script);
  5345. if(isset($this->scriptMap[$name]))
  5346. {
  5347. if($this->scriptMap[$name]!==false)
  5348. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  5349. }
  5350. else if(isset($this->scriptMap['*.js']))
  5351. {
  5352. if($this->scriptMap['*.js']!==false)
  5353. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  5354. }
  5355. else
  5356. $jsFiles[$position][$key]=$script;
  5357. }
  5358. }
  5359. $this->scriptFiles=$jsFiles;
  5360. }
  5361. public function renderCoreScripts()
  5362. {
  5363. if($this->_packages===null)
  5364. return;
  5365. $baseUrl=$this->getCoreScriptUrl();
  5366. $cssFiles=array();
  5367. $jsFiles=array();
  5368. foreach($this->_coreScripts as $name)
  5369. {
  5370. foreach($this->_packages[$name] as $path)
  5371. {
  5372. $url=$baseUrl.'/'.$path;
  5373. if(substr($path,-4)==='.css')
  5374. $cssFiles[$url]='';
  5375. else
  5376. $jsFiles[$url]=$url;
  5377. }
  5378. }
  5379. // merge in place
  5380. if($cssFiles!==array())
  5381. {
  5382. foreach($this->cssFiles as $cssFile=>$media)
  5383. $cssFiles[$cssFile]=$media;
  5384. $this->cssFiles=$cssFiles;
  5385. }
  5386. if($jsFiles!==array())
  5387. {
  5388. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  5389. {
  5390. foreach($this->scriptFiles[$this->coreScriptPosition] as $url)
  5391. $jsFiles[$url]=$url;
  5392. }
  5393. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  5394. }
  5395. }
  5396. public function renderHead(&$output)
  5397. {
  5398. $html='';
  5399. foreach($this->metaTags as $meta)
  5400. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  5401. foreach($this->linkTags as $link)
  5402. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  5403. foreach($this->cssFiles as $url=>$media)
  5404. $html.=CHtml::cssFile($url,$media)."\n";
  5405. foreach($this->css as $css)
  5406. $html.=CHtml::css($css[0],$css[1])."\n";
  5407. if($this->enableJavaScript)
  5408. {
  5409. if(isset($this->scriptFiles[self::POS_HEAD]))
  5410. {
  5411. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFile)
  5412. $html.=CHtml::scriptFile($scriptFile)."\n";
  5413. }
  5414. if(isset($this->scripts[self::POS_HEAD]))
  5415. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_HEAD]))."\n";
  5416. }
  5417. if($html!=='')
  5418. {
  5419. $count=0;
  5420. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  5421. if($count)
  5422. $output=str_replace('<###head###>',$html,$output);
  5423. else
  5424. $output=$html.$output;
  5425. }
  5426. }
  5427. public function renderBodyBegin(&$output)
  5428. {
  5429. $html='';
  5430. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5431. {
  5432. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile)
  5433. $html.=CHtml::scriptFile($scriptFile)."\n";
  5434. }
  5435. if(isset($this->scripts[self::POS_BEGIN]))
  5436. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_BEGIN]))."\n";
  5437. if($html!=='')
  5438. {
  5439. $count=0;
  5440. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  5441. if($count)
  5442. $output=str_replace('<###begin###>',$html,$output);
  5443. else
  5444. $output=$html.$output;
  5445. }
  5446. }
  5447. public function renderBodyEnd(&$output)
  5448. {
  5449. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  5450. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  5451. return;
  5452. $fullPage=0;
  5453. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  5454. $html='';
  5455. if(isset($this->scriptFiles[self::POS_END]))
  5456. {
  5457. foreach($this->scriptFiles[self::POS_END] as $scriptFile)
  5458. $html.=CHtml::scriptFile($scriptFile)."\n";
  5459. }
  5460. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  5461. if(isset($this->scripts[self::POS_READY]))
  5462. {
  5463. if($fullPage)
  5464. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  5465. else
  5466. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  5467. }
  5468. if(isset($this->scripts[self::POS_LOAD]))
  5469. {
  5470. if($fullPage)
  5471. $scripts[]="jQuery(window).load(function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  5472. else
  5473. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  5474. }
  5475. if(!empty($scripts))
  5476. $html.=CHtml::script(implode("\n",$scripts))."\n";
  5477. if($fullPage)
  5478. $output=str_replace('<###end###>',$html,$output);
  5479. else
  5480. $output=$output.$html;
  5481. }
  5482. public function getCoreScriptUrl()
  5483. {
  5484. if($this->_baseUrl!==null)
  5485. return $this->_baseUrl;
  5486. else
  5487. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  5488. }
  5489. public function setCoreScriptUrl($value)
  5490. {
  5491. $this->_baseUrl=$value;
  5492. }
  5493. public function registerCoreScript($name)
  5494. {
  5495. if(isset($this->_coreScripts[$name]))
  5496. return $this;
  5497. if($this->_packages===null)
  5498. {
  5499. $config=require(YII_PATH.'/web/js/packages.php');
  5500. $this->_packages=$config[0];
  5501. $this->_dependencies=$config[1];
  5502. }
  5503. if(!isset($this->_packages[$name]))
  5504. return $this;
  5505. if(isset($this->_dependencies[$name]))
  5506. {
  5507. foreach($this->_dependencies[$name] as $depName)
  5508. $this->registerCoreScript($depName);
  5509. }
  5510. $this->_hasScripts=true;
  5511. $this->_coreScripts[$name]=$name;
  5512. $params=func_get_args();
  5513. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  5514. return $this;
  5515. }
  5516. public function registerCssFile($url,$media='')
  5517. {
  5518. $this->_hasScripts=true;
  5519. $this->cssFiles[$url]=$media;
  5520. $params=func_get_args();
  5521. $this->recordCachingAction('clientScript','registerCssFile',$params);
  5522. return $this;
  5523. }
  5524. public function registerCss($id,$css,$media='')
  5525. {
  5526. $this->_hasScripts=true;
  5527. $this->css[$id]=array($css,$media);
  5528. $params=func_get_args();
  5529. $this->recordCachingAction('clientScript','registerCss',$params);
  5530. return $this;
  5531. }
  5532. public function registerScriptFile($url,$position=self::POS_HEAD)
  5533. {
  5534. $this->_hasScripts=true;
  5535. $this->scriptFiles[$position][$url]=$url;
  5536. $params=func_get_args();
  5537. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  5538. return $this;
  5539. }
  5540. public function registerScript($id,$script,$position=self::POS_READY)
  5541. {
  5542. $this->_hasScripts=true;
  5543. $this->scripts[$position][$id]=$script;
  5544. if($position===self::POS_READY || $position===self::POS_LOAD)
  5545. $this->registerCoreScript('jquery');
  5546. $params=func_get_args();
  5547. $this->recordCachingAction('clientScript','registerScript',$params);
  5548. return $this;
  5549. }
  5550. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array())
  5551. {
  5552. $this->_hasScripts=true;
  5553. if($name!==null)
  5554. $options['name']=$name;
  5555. if($httpEquiv!==null)
  5556. $options['http-equiv']=$httpEquiv;
  5557. $options['content']=$content;
  5558. $this->metaTags[serialize($options)]=$options;
  5559. $params=func_get_args();
  5560. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  5561. return $this;
  5562. }
  5563. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  5564. {
  5565. $this->_hasScripts=true;
  5566. if($relation!==null)
  5567. $options['rel']=$relation;
  5568. if($type!==null)
  5569. $options['type']=$type;
  5570. if($href!==null)
  5571. $options['href']=$href;
  5572. if($media!==null)
  5573. $options['media']=$media;
  5574. $this->linkTags[serialize($options)]=$options;
  5575. $params=func_get_args();
  5576. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  5577. return $this;
  5578. }
  5579. public function isCssFileRegistered($url)
  5580. {
  5581. return isset($this->cssFiles[$url]);
  5582. }
  5583. public function isCssRegistered($id)
  5584. {
  5585. return isset($this->css[$id]);
  5586. }
  5587. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  5588. {
  5589. return isset($this->scriptFiles[$position][$url]);
  5590. }
  5591. public function isScriptRegistered($id,$position=self::POS_READY)
  5592. {
  5593. return isset($this->scripts[$position][$id]);
  5594. }
  5595. protected function recordCachingAction($context,$method,$params)
  5596. {
  5597. if(($controller=Yii::app()->getController())!==null)
  5598. $controller->recordCachingAction($context,$method,$params);
  5599. }
  5600. }
  5601. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  5602. {
  5603. private $_d=array();
  5604. private $_c=0;
  5605. private $_r=false;
  5606. public function __construct($data=null,$readOnly=false)
  5607. {
  5608. if($data!==null)
  5609. $this->copyFrom($data);
  5610. $this->setReadOnly($readOnly);
  5611. }
  5612. public function getReadOnly()
  5613. {
  5614. return $this->_r;
  5615. }
  5616. protected function setReadOnly($value)
  5617. {
  5618. $this->_r=$value;
  5619. }
  5620. public function getIterator()
  5621. {
  5622. return new CListIterator($this->_d);
  5623. }
  5624. public function count()
  5625. {
  5626. return $this->getCount();
  5627. }
  5628. public function getCount()
  5629. {
  5630. return $this->_c;
  5631. }
  5632. public function itemAt($index)
  5633. {
  5634. if(isset($this->_d[$index]))
  5635. return $this->_d[$index];
  5636. else if($index>=0 && $index<$this->_c) // in case the value is null
  5637. return $this->_d[$index];
  5638. else
  5639. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  5640. array('{index}'=>$index)));
  5641. }
  5642. public function add($item)
  5643. {
  5644. $this->insertAt($this->_c,$item);
  5645. return $this->_c-1;
  5646. }
  5647. public function insertAt($index,$item)
  5648. {
  5649. if(!$this->_r)
  5650. {
  5651. if($index===$this->_c)
  5652. $this->_d[$this->_c++]=$item;
  5653. else if($index>=0 && $index<$this->_c)
  5654. {
  5655. array_splice($this->_d,$index,0,array($item));
  5656. $this->_c++;
  5657. }
  5658. else
  5659. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  5660. array('{index}'=>$index)));
  5661. }
  5662. else
  5663. throw new CException(Yii::t('yii','The list is read only.'));
  5664. }
  5665. public function remove($item)
  5666. {
  5667. if(($index=$this->indexOf($item))>=0)
  5668. {
  5669. $this->removeAt($index);
  5670. return $index;
  5671. }
  5672. else
  5673. return false;
  5674. }
  5675. public function removeAt($index)
  5676. {
  5677. if(!$this->_r)
  5678. {
  5679. if($index>=0 && $index<$this->_c)
  5680. {
  5681. $this->_c--;
  5682. if($index===$this->_c)
  5683. return array_pop($this->_d);
  5684. else
  5685. {
  5686. $item=$this->_d[$index];
  5687. array_splice($this->_d,$index,1);
  5688. return $item;
  5689. }
  5690. }
  5691. else
  5692. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  5693. array('{index}'=>$index)));
  5694. }
  5695. else
  5696. throw new CException(Yii::t('yii','The list is read only.'));
  5697. }
  5698. public function clear()
  5699. {
  5700. for($i=$this->_c-1;$i>=0;--$i)
  5701. $this->removeAt($i);
  5702. }
  5703. public function contains($item)
  5704. {
  5705. return $this->indexOf($item)>=0;
  5706. }
  5707. public function indexOf($item)
  5708. {
  5709. if(($index=array_search($item,$this->_d,true))!==false)
  5710. return $index;
  5711. else
  5712. return -1;
  5713. }
  5714. public function toArray()
  5715. {
  5716. return $this->_d;
  5717. }
  5718. public function copyFrom($data)
  5719. {
  5720. if(is_array($data) || ($data instanceof Traversable))
  5721. {
  5722. if($this->_c>0)
  5723. $this->clear();
  5724. if($data instanceof CList)
  5725. $data=$data->_d;
  5726. foreach($data as $item)
  5727. $this->add($item);
  5728. }
  5729. else if($data!==null)
  5730. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  5731. }
  5732. public function mergeWith($data)
  5733. {
  5734. if(is_array($data) || ($data instanceof Traversable))
  5735. {
  5736. if($data instanceof CList)
  5737. $data=$data->_d;
  5738. foreach($data as $item)
  5739. $this->add($item);
  5740. }
  5741. else if($data!==null)
  5742. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  5743. }
  5744. public function offsetExists($offset)
  5745. {
  5746. return ($offset>=0 && $offset<$this->_c);
  5747. }
  5748. public function offsetGet($offset)
  5749. {
  5750. return $this->itemAt($offset);
  5751. }
  5752. public function offsetSet($offset,$item)
  5753. {
  5754. if($offset===null || $offset===$this->_c)
  5755. $this->insertAt($this->_c,$item);
  5756. else
  5757. {
  5758. $this->removeAt($offset);
  5759. $this->insertAt($offset,$item);
  5760. }
  5761. }
  5762. public function offsetUnset($offset)
  5763. {
  5764. $this->removeAt($offset);
  5765. }
  5766. }
  5767. class CFilterChain extends CList
  5768. {
  5769. public $controller;
  5770. public $action;
  5771. public $filterIndex=0;
  5772. public function __construct($controller,$action)
  5773. {
  5774. $this->controller=$controller;
  5775. $this->action=$action;
  5776. }
  5777. public static function create($controller,$action,$filters)
  5778. {
  5779. $chain=new CFilterChain($controller,$action);
  5780. $actionID=$action->getId();
  5781. foreach($filters as $filter)
  5782. {
  5783. if(is_string($filter)) // filterName [+|- action1 action2]
  5784. {
  5785. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  5786. {
  5787. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  5788. if(($filter[$pos]==='+')===$matched)
  5789. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  5790. }
  5791. else
  5792. $filter=CInlineFilter::create($controller,$filter);
  5793. }
  5794. else if(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  5795. {
  5796. if(!isset($filter[0]))
  5797. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  5798. $filterClass=$filter[0];
  5799. unset($filter[0]);
  5800. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  5801. {
  5802. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  5803. if(($filterClass[$pos]==='+')===$matched)
  5804. $filterClass=trim(substr($filterClass,0,$pos));
  5805. else
  5806. continue;
  5807. }
  5808. $filter['class']=$filterClass;
  5809. $filter=Yii::createComponent($filter);
  5810. }
  5811. if(is_object($filter))
  5812. {
  5813. $filter->init();
  5814. $chain->add($filter);
  5815. }
  5816. }
  5817. return $chain;
  5818. }
  5819. public function insertAt($index,$item)
  5820. {
  5821. if($item instanceof IFilter)
  5822. parent::insertAt($index,$item);
  5823. else
  5824. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  5825. }
  5826. public function run()
  5827. {
  5828. if($this->offsetExists($this->filterIndex))
  5829. {
  5830. $filter=$this->itemAt($this->filterIndex++);
  5831. $filter->filter($this);
  5832. }
  5833. else
  5834. $this->controller->runAction($this->action);
  5835. }
  5836. }
  5837. class CFilter extends CComponent implements IFilter
  5838. {
  5839. public function filter($filterChain)
  5840. {
  5841. if($this->preFilter($filterChain))
  5842. {
  5843. $filterChain->run();
  5844. $this->postFilter($filterChain);
  5845. }
  5846. }
  5847. public function init()
  5848. {
  5849. }
  5850. protected function preFilter($filterChain)
  5851. {
  5852. return true;
  5853. }
  5854. protected function postFilter($filterChain)
  5855. {
  5856. }
  5857. }
  5858. class CInlineFilter extends CFilter
  5859. {
  5860. public $name;
  5861. public static function create($controller,$filterName)
  5862. {
  5863. if(method_exists($controller,'filter'.$filterName))
  5864. {
  5865. $filter=new CInlineFilter;
  5866. $filter->name=$filterName;
  5867. return $filter;
  5868. }
  5869. else
  5870. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does have the filter method "filter{filter}".',
  5871. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  5872. }
  5873. public function filter($filterChain)
  5874. {
  5875. $method='filter'.$this->name;
  5876. $filterChain->controller->$method($filterChain);
  5877. }
  5878. }
  5879. class CAccessControlFilter extends CFilter
  5880. {
  5881. public $message;
  5882. private $_rules=array();
  5883. public function getRules()
  5884. {
  5885. return $this->_rules;
  5886. }
  5887. public function setRules($rules)
  5888. {
  5889. foreach($rules as $rule)
  5890. {
  5891. if(is_array($rule) && isset($rule[0]))
  5892. {
  5893. $r=new CAccessRule;
  5894. $r->allow=$rule[0]==='allow';
  5895. foreach(array_slice($rule,1) as $name=>$value)
  5896. {
  5897. if($name==='expression' || $name==='roles' || $name==='message')
  5898. $r->$name=$value;
  5899. else
  5900. $r->$name=array_map('strtolower',$value);
  5901. }
  5902. $this->_rules[]=$r;
  5903. }
  5904. }
  5905. }
  5906. protected function preFilter($filterChain)
  5907. {
  5908. $app=Yii::app();
  5909. $request=$app->getRequest();
  5910. $user=$app->getUser();
  5911. $verb=$request->getRequestType();
  5912. $ip=$request->getUserHostAddress();
  5913. foreach($this->getRules() as $rule)
  5914. {
  5915. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  5916. break;
  5917. else if($allow<0) // denied
  5918. {
  5919. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  5920. return false;
  5921. }
  5922. }
  5923. return true;
  5924. }
  5925. protected function resolveErrorMessage($rule)
  5926. {
  5927. if($rule->message!==null)
  5928. return $rule->message;
  5929. else if($this->message!==null)
  5930. return $this->message;
  5931. else
  5932. return Yii::t('yii','You are not authorized to perform this action.');
  5933. }
  5934. protected function accessDenied($user,$message)
  5935. {
  5936. if($user->getIsGuest())
  5937. $user->loginRequired();
  5938. else
  5939. throw new CHttpException(403,$message);
  5940. }
  5941. }
  5942. class CAccessRule extends CComponent
  5943. {
  5944. public $allow;
  5945. public $actions;
  5946. public $controllers;
  5947. public $users;
  5948. public $roles;
  5949. public $ips;
  5950. public $verbs;
  5951. public $expression;
  5952. public $message;
  5953. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  5954. {
  5955. if($this->isActionMatched($action)
  5956. && $this->isUserMatched($user)
  5957. && $this->isRoleMatched($user)
  5958. && $this->isIpMatched($ip)
  5959. && $this->isVerbMatched($verb)
  5960. && $this->isControllerMatched($controller)
  5961. && $this->isExpressionMatched($user))
  5962. return $this->allow ? 1 : -1;
  5963. else
  5964. return 0;
  5965. }
  5966. protected function isActionMatched($action)
  5967. {
  5968. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  5969. }
  5970. protected function isControllerMatched($controller)
  5971. {
  5972. return empty($this->controllers) || in_array(strtolower($controller->getId()),$this->controllers);
  5973. }
  5974. protected function isUserMatched($user)
  5975. {
  5976. if(empty($this->users))
  5977. return true;
  5978. foreach($this->users as $u)
  5979. {
  5980. if($u==='*')
  5981. return true;
  5982. else if($u==='?' && $user->getIsGuest())
  5983. return true;
  5984. else if($u==='@' && !$user->getIsGuest())
  5985. return true;
  5986. else if(!strcasecmp($u,$user->getName()))
  5987. return true;
  5988. }
  5989. return false;
  5990. }
  5991. protected function isRoleMatched($user)
  5992. {
  5993. if(empty($this->roles))
  5994. return true;
  5995. foreach($this->roles as $role)
  5996. {
  5997. if($user->checkAccess($role))
  5998. return true;
  5999. }
  6000. return false;
  6001. }
  6002. protected function isIpMatched($ip)
  6003. {
  6004. if(empty($this->ips))
  6005. return true;
  6006. foreach($this->ips as $rule)
  6007. {
  6008. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  6009. return true;
  6010. }
  6011. return false;
  6012. }
  6013. protected function isVerbMatched($verb)
  6014. {
  6015. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  6016. }
  6017. protected function isExpressionMatched($user)
  6018. {
  6019. if($this->expression===null)
  6020. return true;
  6021. else
  6022. return $this->evaluateExpression($this->expression, array('user'=>$user));
  6023. }
  6024. }
  6025. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  6026. {
  6027. private $_errors=array(); // attribute name => array of errors
  6028. private $_validators; // validators
  6029. private $_scenario=''; // scenario
  6030. abstract public function attributeNames();
  6031. public function rules()
  6032. {
  6033. return array();
  6034. }
  6035. public function behaviors()
  6036. {
  6037. return array();
  6038. }
  6039. public function attributeLabels()
  6040. {
  6041. return array();
  6042. }
  6043. public function validate($attributes=null)
  6044. {
  6045. $this->clearErrors();
  6046. if($this->beforeValidate())
  6047. {
  6048. foreach($this->getValidators() as $validator)
  6049. $validator->validate($this,$attributes);
  6050. $this->afterValidate();
  6051. return !$this->hasErrors();
  6052. }
  6053. else
  6054. return false;
  6055. }
  6056. protected function afterConstruct()
  6057. {
  6058. if($this->hasEventHandler('onAfterConstruct'))
  6059. $this->onAfterConstruct(new CEvent($this));
  6060. }
  6061. protected function beforeValidate()
  6062. {
  6063. $event=new CModelEvent($this);
  6064. $this->onBeforeValidate($event);
  6065. return $event->isValid;
  6066. }
  6067. protected function afterValidate()
  6068. {
  6069. $this->onAfterValidate(new CEvent($this));
  6070. }
  6071. public function onAfterConstruct($event)
  6072. {
  6073. $this->raiseEvent('onAfterConstruct',$event);
  6074. }
  6075. public function onBeforeValidate($event)
  6076. {
  6077. $this->raiseEvent('onBeforeValidate',$event);
  6078. }
  6079. public function onAfterValidate($event)
  6080. {
  6081. $this->raiseEvent('onAfterValidate',$event);
  6082. }
  6083. public function getValidatorList()
  6084. {
  6085. if($this->_validators===null)
  6086. $this->_validators=$this->createValidators();
  6087. return $this->_validators;
  6088. }
  6089. public function getValidators($attribute=null)
  6090. {
  6091. if($this->_validators===null)
  6092. $this->_validators=$this->createValidators();
  6093. $validators=array();
  6094. $scenario=$this->getScenario();
  6095. foreach($this->_validators as $validator)
  6096. {
  6097. if($validator->applyTo($scenario))
  6098. {
  6099. if($attribute===null || in_array($attribute,$validator->attributes,true))
  6100. $validators[]=$validator;
  6101. }
  6102. }
  6103. return $validators;
  6104. }
  6105. public function createValidators()
  6106. {
  6107. $validators=new CList;
  6108. foreach($this->rules() as $rule)
  6109. {
  6110. if(isset($rule[0],$rule[1])) // attributes, validator name
  6111. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  6112. else
  6113. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  6114. array('{class}'=>get_class($this))));
  6115. }
  6116. return $validators;
  6117. }
  6118. public function isAttributeRequired($attribute)
  6119. {
  6120. foreach($this->getValidators($attribute) as $validator)
  6121. {
  6122. if($validator instanceof CRequiredValidator)
  6123. return true;
  6124. }
  6125. return false;
  6126. }
  6127. public function isAttributeSafe($attribute)
  6128. {
  6129. $attributes=$this->getSafeAttributeNames();
  6130. return in_array($attribute,$attributes);
  6131. }
  6132. public function getAttributeLabel($attribute)
  6133. {
  6134. $labels=$this->attributeLabels();
  6135. if(isset($labels[$attribute]))
  6136. return $labels[$attribute];
  6137. else
  6138. return $this->generateAttributeLabel($attribute);
  6139. }
  6140. public function hasErrors($attribute=null)
  6141. {
  6142. if($attribute===null)
  6143. return $this->_errors!==array();
  6144. else
  6145. return isset($this->_errors[$attribute]);
  6146. }
  6147. public function getErrors($attribute=null)
  6148. {
  6149. if($attribute===null)
  6150. return $this->_errors;
  6151. else
  6152. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  6153. }
  6154. public function getError($attribute)
  6155. {
  6156. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  6157. }
  6158. public function addError($attribute,$error)
  6159. {
  6160. $this->_errors[$attribute][]=$error;
  6161. }
  6162. public function addErrors($errors)
  6163. {
  6164. foreach($errors as $attribute=>$error)
  6165. {
  6166. if(is_array($error))
  6167. {
  6168. foreach($error as $e)
  6169. $this->_errors[$attribute][]=$e;
  6170. }
  6171. else
  6172. $this->_errors[$attribute][]=$error;
  6173. }
  6174. }
  6175. public function clearErrors($attribute=null)
  6176. {
  6177. if($attribute===null)
  6178. $this->_errors=array();
  6179. else
  6180. unset($this->_errors[$attribute]);
  6181. }
  6182. public function generateAttributeLabel($name)
  6183. {
  6184. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  6185. }
  6186. public function getAttributes($names=null)
  6187. {
  6188. $values=array();
  6189. foreach($this->attributeNames() as $name)
  6190. $values[$name]=$this->$name;
  6191. if(is_array($names))
  6192. {
  6193. $values2=array();
  6194. foreach($names as $name)
  6195. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  6196. return $values2;
  6197. }
  6198. else
  6199. return $values;
  6200. }
  6201. public function setAttributes($values,$safeOnly=true)
  6202. {
  6203. if(!is_array($values))
  6204. return;
  6205. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  6206. foreach($values as $name=>$value)
  6207. {
  6208. if(isset($attributes[$name]))
  6209. $this->$name=$value;
  6210. else if($safeOnly)
  6211. $this->onUnsafeAttribute($name,$value);
  6212. }
  6213. }
  6214. public function unsetAttributes($names=null)
  6215. {
  6216. if($names===null)
  6217. $names=$this->attributeNames();
  6218. foreach($names as $name)
  6219. $this->$name=null;
  6220. }
  6221. public function onUnsafeAttribute($name,$value)
  6222. {
  6223. if(YII_DEBUG)
  6224. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}".',array('{attribute}'=>$name)),CLogger::LEVEL_WARNING);
  6225. }
  6226. public function getScenario()
  6227. {
  6228. return $this->_scenario;
  6229. }
  6230. public function setScenario($value)
  6231. {
  6232. $this->_scenario=$value;
  6233. }
  6234. public function getSafeAttributeNames()
  6235. {
  6236. $attributes=array();
  6237. $unsafe=array();
  6238. foreach($this->getValidators() as $validator)
  6239. {
  6240. if(!$validator->safe)
  6241. {
  6242. foreach($validator->attributes as $name)
  6243. $unsafe[]=$name;
  6244. }
  6245. else
  6246. {
  6247. foreach($validator->attributes as $name)
  6248. $attributes[$name]=true;
  6249. }
  6250. }
  6251. foreach($unsafe as $name)
  6252. unset($attributes[$name]);
  6253. return array_keys($attributes);
  6254. }
  6255. public function getIterator()
  6256. {
  6257. $attributes=$this->getAttributes();
  6258. return new CMapIterator($attributes);
  6259. }
  6260. public function offsetExists($offset)
  6261. {
  6262. return property_exists($this,$offset);
  6263. }
  6264. public function offsetGet($offset)
  6265. {
  6266. return $this->$offset;
  6267. }
  6268. public function offsetSet($offset,$item)
  6269. {
  6270. $this->$offset=$item;
  6271. }
  6272. public function offsetUnset($offset)
  6273. {
  6274. unset($this->$offset);
  6275. }
  6276. }
  6277. abstract class CActiveRecord extends CModel
  6278. {
  6279. const BELONGS_TO='CBelongsToRelation';
  6280. const HAS_ONE='CHasOneRelation';
  6281. const HAS_MANY='CHasManyRelation';
  6282. const MANY_MANY='CManyManyRelation';
  6283. const STAT='CStatRelation';
  6284. public static $db;
  6285. private static $_models=array(); // class name => model
  6286. private $_md; // meta data
  6287. private $_new=false; // whether this instance is new or not
  6288. private $_attributes=array(); // attribute name => attribute value
  6289. private $_related=array(); // attribute name => related objects
  6290. private $_c; // query criteria (used by finder only)
  6291. private $_pk; // old primary key value
  6292. private $_alias='t'; // the table alias being used for query
  6293. public function __construct($scenario='insert')
  6294. {
  6295. if($scenario===null) // internally used by populateRecord() and model()
  6296. return;
  6297. $this->setScenario($scenario);
  6298. $this->setIsNewRecord(true);
  6299. $this->_attributes=$this->getMetaData()->attributeDefaults;
  6300. $this->init();
  6301. $this->attachBehaviors($this->behaviors());
  6302. $this->afterConstruct();
  6303. }
  6304. public function init()
  6305. {
  6306. }
  6307. public function __sleep()
  6308. {
  6309. $this->_md=null;
  6310. return array_keys((array)$this);
  6311. }
  6312. public function __get($name)
  6313. {
  6314. if(isset($this->_attributes[$name]))
  6315. return $this->_attributes[$name];
  6316. else if(isset($this->getMetaData()->columns[$name]))
  6317. return null;
  6318. else if(isset($this->_related[$name]))
  6319. return $this->_related[$name];
  6320. else if(isset($this->getMetaData()->relations[$name]))
  6321. return $this->getRelated($name);
  6322. else
  6323. return parent::__get($name);
  6324. }
  6325. public function __set($name,$value)
  6326. {
  6327. if($this->setAttribute($name,$value)===false)
  6328. {
  6329. if(isset($this->getMetaData()->relations[$name]))
  6330. $this->_related[$name]=$value;
  6331. else
  6332. parent::__set($name,$value);
  6333. }
  6334. }
  6335. public function __isset($name)
  6336. {
  6337. if(isset($this->_attributes[$name]))
  6338. return true;
  6339. else if(isset($this->getMetaData()->columns[$name]))
  6340. return false;
  6341. else if(isset($this->_related[$name]))
  6342. return true;
  6343. else if(isset($this->getMetaData()->relations[$name]))
  6344. return $this->getRelated($name)!==null;
  6345. else
  6346. return parent::__isset($name);
  6347. }
  6348. public function __unset($name)
  6349. {
  6350. if(isset($this->getMetaData()->columns[$name]))
  6351. unset($this->_attributes[$name]);
  6352. else if(isset($this->getMetaData()->relations[$name]))
  6353. unset($this->_related[$name]);
  6354. else
  6355. parent::__unset($name);
  6356. }
  6357. public function __call($name,$parameters)
  6358. {
  6359. if(isset($this->getMetaData()->relations[$name]))
  6360. {
  6361. if(empty($parameters))
  6362. return $this->getRelated($name,false);
  6363. else
  6364. return $this->getRelated($name,false,$parameters[0]);
  6365. }
  6366. $scopes=$this->scopes();
  6367. if(isset($scopes[$name]))
  6368. {
  6369. $this->getDbCriteria()->mergeWith($scopes[$name]);
  6370. return $this;
  6371. }
  6372. return parent::__call($name,$parameters);
  6373. }
  6374. public function getRelated($name,$refresh=false,$params=array())
  6375. {
  6376. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  6377. return $this->_related[$name];
  6378. $md=$this->getMetaData();
  6379. if(!isset($md->relations[$name]))
  6380. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  6381. array('{class}'=>get_class($this), '{name}'=>$name)));
  6382. $relation=$md->relations[$name];
  6383. if($this->getIsNewRecord() && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  6384. return $relation instanceof CHasOneRelation ? null : array();
  6385. if($params!==array()) // dynamic query
  6386. {
  6387. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6388. if($exists)
  6389. $save=$this->_related[$name];
  6390. $r=array($name=>$params);
  6391. }
  6392. else
  6393. $r=$name;
  6394. unset($this->_related[$name]);
  6395. $finder=new CActiveFinder($this,$r);
  6396. $finder->lazyFind($this);
  6397. if(!isset($this->_related[$name]))
  6398. {
  6399. if($relation instanceof CHasManyRelation)
  6400. $this->_related[$name]=array();
  6401. else if($relation instanceof CStatRelation)
  6402. $this->_related[$name]=$relation->defaultValue;
  6403. else
  6404. $this->_related[$name]=null;
  6405. }
  6406. if($params!==array())
  6407. {
  6408. $results=$this->_related[$name];
  6409. if($exists)
  6410. $this->_related[$name]=$save;
  6411. else
  6412. unset($this->_related[$name]);
  6413. return $results;
  6414. }
  6415. else
  6416. return $this->_related[$name];
  6417. }
  6418. public function hasRelated($name)
  6419. {
  6420. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6421. }
  6422. public function getDbCriteria($createIfNull=true)
  6423. {
  6424. if($this->_c===null)
  6425. {
  6426. if(($c=$this->defaultScope())!==array() || $createIfNull)
  6427. $this->_c=new CDbCriteria($c);
  6428. }
  6429. return $this->_c;
  6430. }
  6431. public function setDbCriteria($criteria)
  6432. {
  6433. $this->_c=$criteria;
  6434. }
  6435. public function defaultScope()
  6436. {
  6437. return array();
  6438. }
  6439. public function resetScope()
  6440. {
  6441. $this->_c=new CDbCriteria();
  6442. return $this;
  6443. }
  6444. public static function model($className=__CLASS__)
  6445. {
  6446. if(isset(self::$_models[$className]))
  6447. return self::$_models[$className];
  6448. else
  6449. {
  6450. $model=self::$_models[$className]=new $className(null);
  6451. $model->_md=new CActiveRecordMetaData($model);
  6452. $model->attachBehaviors($model->behaviors());
  6453. return $model;
  6454. }
  6455. }
  6456. public function getMetaData()
  6457. {
  6458. if($this->_md!==null)
  6459. return $this->_md;
  6460. else
  6461. return $this->_md=self::model(get_class($this))->_md;
  6462. }
  6463. public function refreshMetaData()
  6464. {
  6465. $finder=self::model(get_class($this));
  6466. $finder->_md=new CActiveRecordMetaData($finder);
  6467. if($this!==$finder)
  6468. $this->_md=$finder->_md;
  6469. }
  6470. public function tableName()
  6471. {
  6472. return get_class($this);
  6473. }
  6474. public function primaryKey()
  6475. {
  6476. }
  6477. public function relations()
  6478. {
  6479. return array();
  6480. }
  6481. public function scopes()
  6482. {
  6483. return array();
  6484. }
  6485. public function attributeNames()
  6486. {
  6487. return array_keys($this->getMetaData()->columns);
  6488. }
  6489. public function getAttributeLabel($attribute)
  6490. {
  6491. $labels=$this->attributeLabels();
  6492. if(isset($labels[$attribute]))
  6493. return $labels[$attribute];
  6494. else if(strpos($attribute,'.')!==false)
  6495. {
  6496. $segs=explode('.',$attribute);
  6497. $name=array_pop($segs);
  6498. $model=$this;
  6499. foreach($segs as $seg)
  6500. {
  6501. $relations=$model->getMetaData()->relations;
  6502. if(isset($relations[$seg]))
  6503. $model=CActiveRecord::model($relations[$seg]->className);
  6504. else
  6505. break;
  6506. }
  6507. return $model->getAttributeLabel($name);
  6508. }
  6509. else
  6510. return $this->generateAttributeLabel($attribute);
  6511. }
  6512. public function getDbConnection()
  6513. {
  6514. if(self::$db!==null)
  6515. return self::$db;
  6516. else
  6517. {
  6518. self::$db=Yii::app()->getDb();
  6519. if(self::$db instanceof CDbConnection)
  6520. {
  6521. self::$db->setActive(true);
  6522. return self::$db;
  6523. }
  6524. else
  6525. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  6526. }
  6527. }
  6528. public function getActiveRelation($name)
  6529. {
  6530. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  6531. }
  6532. public function getTableSchema()
  6533. {
  6534. return $this->getMetaData()->tableSchema;
  6535. }
  6536. public function getCommandBuilder()
  6537. {
  6538. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  6539. }
  6540. public function hasAttribute($name)
  6541. {
  6542. return isset($this->getMetaData()->columns[$name]);
  6543. }
  6544. public function getAttribute($name)
  6545. {
  6546. if(property_exists($this,$name))
  6547. return $this->$name;
  6548. else if(isset($this->_attributes[$name]))
  6549. return $this->_attributes[$name];
  6550. }
  6551. public function setAttribute($name,$value)
  6552. {
  6553. if(property_exists($this,$name))
  6554. $this->$name=$value;
  6555. else if(isset($this->getMetaData()->columns[$name]))
  6556. $this->_attributes[$name]=$value;
  6557. else
  6558. return false;
  6559. return true;
  6560. }
  6561. public function addRelatedRecord($name,$record,$index)
  6562. {
  6563. if($index!==false)
  6564. {
  6565. if(!isset($this->_related[$name]))
  6566. $this->_related[$name]=array();
  6567. if($record instanceof CActiveRecord)
  6568. {
  6569. if($index===true)
  6570. $this->_related[$name][]=$record;
  6571. else
  6572. $this->_related[$name][$index]=$record;
  6573. }
  6574. }
  6575. else if(!isset($this->_related[$name]))
  6576. $this->_related[$name]=$record;
  6577. }
  6578. public function getAttributes($names=true)
  6579. {
  6580. $attributes=$this->_attributes;
  6581. foreach($this->getMetaData()->columns as $name=>$column)
  6582. {
  6583. if(property_exists($this,$name))
  6584. $attributes[$name]=$this->$name;
  6585. else if($names===true && !isset($attributes[$name]))
  6586. $attributes[$name]=null;
  6587. }
  6588. if(is_array($names))
  6589. {
  6590. $attrs=array();
  6591. foreach($names as $name)
  6592. {
  6593. if(property_exists($this,$name))
  6594. $attrs[$name]=$this->$name;
  6595. else
  6596. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  6597. }
  6598. return $attrs;
  6599. }
  6600. else
  6601. return $attributes;
  6602. }
  6603. public function save($runValidation=true,$attributes=null)
  6604. {
  6605. if(!$runValidation || $this->validate($attributes))
  6606. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  6607. else
  6608. return false;
  6609. }
  6610. public function getIsNewRecord()
  6611. {
  6612. return $this->_new;
  6613. }
  6614. public function setIsNewRecord($value)
  6615. {
  6616. $this->_new=$value;
  6617. }
  6618. public function onBeforeSave($event)
  6619. {
  6620. $this->raiseEvent('onBeforeSave',$event);
  6621. }
  6622. public function onAfterSave($event)
  6623. {
  6624. $this->raiseEvent('onAfterSave',$event);
  6625. }
  6626. public function onBeforeDelete($event)
  6627. {
  6628. $this->raiseEvent('onBeforeDelete',$event);
  6629. }
  6630. public function onAfterDelete($event)
  6631. {
  6632. $this->raiseEvent('onAfterDelete',$event);
  6633. }
  6634. public function onBeforeFind($event)
  6635. {
  6636. $this->raiseEvent('onBeforeFind',$event);
  6637. }
  6638. public function onAfterFind($event)
  6639. {
  6640. $this->raiseEvent('onAfterFind',$event);
  6641. }
  6642. protected function beforeSave()
  6643. {
  6644. if($this->hasEventHandler('onBeforeSave'))
  6645. {
  6646. $event=new CModelEvent($this);
  6647. $this->onBeforeSave($event);
  6648. return $event->isValid;
  6649. }
  6650. else
  6651. return true;
  6652. }
  6653. protected function afterSave()
  6654. {
  6655. if($this->hasEventHandler('onAfterSave'))
  6656. $this->onAfterSave(new CEvent($this));
  6657. }
  6658. protected function beforeDelete()
  6659. {
  6660. if($this->hasEventHandler('onBeforeDelete'))
  6661. {
  6662. $event=new CModelEvent($this);
  6663. $this->onBeforeDelete($event);
  6664. return $event->isValid;
  6665. }
  6666. else
  6667. return true;
  6668. }
  6669. protected function afterDelete()
  6670. {
  6671. if($this->hasEventHandler('onAfterDelete'))
  6672. $this->onAfterDelete(new CEvent($this));
  6673. }
  6674. protected function beforeFind()
  6675. {
  6676. if($this->hasEventHandler('onBeforeFind'))
  6677. {
  6678. $event=new CModelEvent($this);
  6679. // for backward compatibility
  6680. $event->criteria=func_num_args()>0 ? func_get_arg(0) : null;
  6681. $this->onBeforeFind($event);
  6682. }
  6683. }
  6684. protected function afterFind()
  6685. {
  6686. if($this->hasEventHandler('onAfterFind'))
  6687. $this->onAfterFind(new CEvent($this));
  6688. }
  6689. public function beforeFindInternal()
  6690. {
  6691. $this->beforeFind();
  6692. }
  6693. public function afterFindInternal()
  6694. {
  6695. $this->afterFind();
  6696. }
  6697. public function insert($attributes=null)
  6698. {
  6699. if(!$this->getIsNewRecord())
  6700. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  6701. if($this->beforeSave())
  6702. {
  6703. $builder=$this->getCommandBuilder();
  6704. $table=$this->getMetaData()->tableSchema;
  6705. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  6706. if($command->execute())
  6707. {
  6708. $primaryKey=$table->primaryKey;
  6709. if($table->sequenceName!==null)
  6710. {
  6711. if(is_string($primaryKey) && $this->$primaryKey===null)
  6712. $this->$primaryKey=$builder->getLastInsertID($table);
  6713. else if(is_array($primaryKey))
  6714. {
  6715. foreach($primaryKey as $pk)
  6716. {
  6717. if($this->$pk===null)
  6718. {
  6719. $this->$pk=$builder->getLastInsertID($table);
  6720. break;
  6721. }
  6722. }
  6723. }
  6724. }
  6725. $this->_pk=$this->getPrimaryKey();
  6726. $this->afterSave();
  6727. $this->setIsNewRecord(false);
  6728. $this->setScenario('update');
  6729. return true;
  6730. }
  6731. }
  6732. return false;
  6733. }
  6734. public function update($attributes=null)
  6735. {
  6736. if($this->getIsNewRecord())
  6737. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  6738. if($this->beforeSave())
  6739. {
  6740. if($this->_pk===null)
  6741. $this->_pk=$this->getPrimaryKey();
  6742. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  6743. $this->_pk=$this->getPrimaryKey();
  6744. $this->afterSave();
  6745. return true;
  6746. }
  6747. else
  6748. return false;
  6749. }
  6750. public function saveAttributes($attributes)
  6751. {
  6752. if(!$this->getIsNewRecord())
  6753. {
  6754. $values=array();
  6755. foreach($attributes as $name=>$value)
  6756. {
  6757. if(is_integer($name))
  6758. $values[$value]=$this->$value;
  6759. else
  6760. $values[$name]=$this->$name=$value;
  6761. }
  6762. if($this->_pk===null)
  6763. $this->_pk=$this->getPrimaryKey();
  6764. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  6765. {
  6766. $this->_pk=$this->getPrimaryKey();
  6767. return true;
  6768. }
  6769. else
  6770. return false;
  6771. }
  6772. else
  6773. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  6774. }
  6775. public function delete()
  6776. {
  6777. if(!$this->getIsNewRecord())
  6778. {
  6779. if($this->beforeDelete())
  6780. {
  6781. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  6782. $this->afterDelete();
  6783. return $result;
  6784. }
  6785. else
  6786. return false;
  6787. }
  6788. else
  6789. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  6790. }
  6791. public function refresh()
  6792. {
  6793. if(!$this->getIsNewRecord() && ($record=$this->findByPk($this->getPrimaryKey()))!==null)
  6794. {
  6795. $this->_attributes=array();
  6796. $this->_related=array();
  6797. foreach($this->getMetaData()->columns as $name=>$column)
  6798. {
  6799. if(property_exists($this,$name))
  6800. $this->$name=$record->$name;
  6801. else
  6802. $this->_attributes[$name]=$record->$name;
  6803. }
  6804. return true;
  6805. }
  6806. else
  6807. return false;
  6808. }
  6809. public function equals($record)
  6810. {
  6811. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  6812. }
  6813. public function getPrimaryKey()
  6814. {
  6815. $table=$this->getMetaData()->tableSchema;
  6816. if(is_string($table->primaryKey))
  6817. return $this->{$table->primaryKey};
  6818. else if(is_array($table->primaryKey))
  6819. {
  6820. $values=array();
  6821. foreach($table->primaryKey as $name)
  6822. $values[$name]=$this->$name;
  6823. return $values;
  6824. }
  6825. else
  6826. return null;
  6827. }
  6828. public function setPrimaryKey($value)
  6829. {
  6830. $this->_pk=$this->getPrimaryKey();
  6831. $table=$this->getMetaData()->tableSchema;
  6832. if(is_string($table->primaryKey))
  6833. $this->{$table->primaryKey}=$value;
  6834. else if(is_array($table->primaryKey))
  6835. {
  6836. foreach($table->primaryKey as $name)
  6837. $this->$name=$value[$name];
  6838. }
  6839. }
  6840. public function getOldPrimaryKey()
  6841. {
  6842. return $this->_pk;
  6843. }
  6844. public function setOldPrimaryKey($value)
  6845. {
  6846. $this->_pk=$value;
  6847. }
  6848. /*
  6849. * @param CDbCriteria $criteria the query criteria
  6850. * @param boolean $all whether to return all data
  6851. */
  6852. private function query($criteria,$all=false)
  6853. {
  6854. $this->beforeFind($criteria);
  6855. $this->applyScopes($criteria);
  6856. if(empty($criteria->with))
  6857. {
  6858. if(!$all)
  6859. $criteria->limit=1;
  6860. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  6861. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  6862. }
  6863. else
  6864. {
  6865. $finder=new CActiveFinder($this,$criteria->with);
  6866. return $finder->query($criteria,$all);
  6867. }
  6868. }
  6869. public function applyScopes(&$criteria)
  6870. {
  6871. if(($c=$this->getDbCriteria(false))!==null)
  6872. {
  6873. $c->mergeWith($criteria);
  6874. $criteria=$c;
  6875. $this->_c=null;
  6876. }
  6877. }
  6878. public function getTableAlias($quote=false, $checkScopes=true)
  6879. {
  6880. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  6881. $alias=$criteria->alias;
  6882. else
  6883. $alias=$this->_alias;
  6884. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  6885. }
  6886. public function setTableAlias($alias)
  6887. {
  6888. $this->_alias=$alias;
  6889. }
  6890. public function find($condition='',$params=array())
  6891. {
  6892. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  6893. return $this->query($criteria);
  6894. }
  6895. public function findAll($condition='',$params=array())
  6896. {
  6897. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  6898. return $this->query($criteria,true);
  6899. }
  6900. public function findByPk($pk,$condition='',$params=array())
  6901. {
  6902. $prefix=$this->getTableAlias(true).'.';
  6903. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  6904. return $this->query($criteria);
  6905. }
  6906. public function findAllByPk($pk,$condition='',$params=array())
  6907. {
  6908. $prefix=$this->getTableAlias(true).'.';
  6909. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  6910. return $this->query($criteria,true);
  6911. }
  6912. public function findByAttributes($attributes,$condition='',$params=array())
  6913. {
  6914. $prefix=$this->getTableAlias(true).'.';
  6915. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  6916. return $this->query($criteria);
  6917. }
  6918. public function findAllByAttributes($attributes,$condition='',$params=array())
  6919. {
  6920. $prefix=$this->getTableAlias(true).'.';
  6921. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  6922. return $this->query($criteria,true);
  6923. }
  6924. public function findBySql($sql,$params=array())
  6925. {
  6926. $this->beforeFind();
  6927. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  6928. {
  6929. $this->_c=null;
  6930. $finder=new CActiveFinder($this,$criteria->with);
  6931. return $finder->findBySql($sql,$params);
  6932. }
  6933. else
  6934. {
  6935. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  6936. return $this->populateRecord($command->queryRow());
  6937. }
  6938. }
  6939. public function findAllBySql($sql,$params=array())
  6940. {
  6941. $this->beforeFind();
  6942. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  6943. {
  6944. $this->_c=null;
  6945. $finder=new CActiveFinder($this,$criteria->with);
  6946. return $finder->findAllBySql($sql,$params);
  6947. }
  6948. else
  6949. {
  6950. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  6951. return $this->populateRecords($command->queryAll());
  6952. }
  6953. }
  6954. public function count($condition='',$params=array())
  6955. {
  6956. $builder=$this->getCommandBuilder();
  6957. $criteria=$builder->createCriteria($condition,$params);
  6958. $this->applyScopes($criteria);
  6959. if(empty($criteria->with))
  6960. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  6961. else
  6962. {
  6963. $finder=new CActiveFinder($this,$criteria->with);
  6964. return $finder->count($criteria);
  6965. }
  6966. }
  6967. public function countByAttributes($attributes,$condition='',$params=array())
  6968. {
  6969. $prefix=$this->getTableAlias(true).'.';
  6970. $builder=$this->getCommandBuilder();
  6971. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  6972. $this->applyScopes($criteria);
  6973. if(empty($criteria->with))
  6974. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  6975. else
  6976. {
  6977. $finder=new CActiveFinder($this,$criteria->with);
  6978. return $finder->count($criteria);
  6979. }
  6980. }
  6981. public function countBySql($sql,$params=array())
  6982. {
  6983. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  6984. }
  6985. public function exists($condition='',$params=array())
  6986. {
  6987. $builder=$this->getCommandBuilder();
  6988. $criteria=$builder->createCriteria($condition,$params);
  6989. $table=$this->getTableSchema();
  6990. $criteria->select=reset($table->columns)->rawName;
  6991. $criteria->limit=1;
  6992. $this->applyScopes($criteria);
  6993. return $builder->createFindCommand($table,$criteria)->queryRow()!==false;
  6994. }
  6995. public function with()
  6996. {
  6997. if(func_num_args()>0)
  6998. {
  6999. $with=func_get_args();
  7000. if(is_array($with[0])) // the parameter is given as an array
  7001. $with=$with[0];
  7002. if(!empty($with))
  7003. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  7004. }
  7005. return $this;
  7006. }
  7007. public function together()
  7008. {
  7009. $this->getDbCriteria()->together=true;
  7010. return $this;
  7011. }
  7012. public function updateByPk($pk,$attributes,$condition='',$params=array())
  7013. {
  7014. $builder=$this->getCommandBuilder();
  7015. $table=$this->getTableSchema();
  7016. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  7017. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  7018. return $command->execute();
  7019. }
  7020. public function updateAll($attributes,$condition='',$params=array())
  7021. {
  7022. $builder=$this->getCommandBuilder();
  7023. $criteria=$builder->createCriteria($condition,$params);
  7024. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  7025. return $command->execute();
  7026. }
  7027. public function updateCounters($counters,$condition='',$params=array())
  7028. {
  7029. $builder=$this->getCommandBuilder();
  7030. $criteria=$builder->createCriteria($condition,$params);
  7031. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7032. return $command->execute();
  7033. }
  7034. public function deleteByPk($pk,$condition='',$params=array())
  7035. {
  7036. $builder=$this->getCommandBuilder();
  7037. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  7038. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7039. return $command->execute();
  7040. }
  7041. public function deleteAll($condition='',$params=array())
  7042. {
  7043. $builder=$this->getCommandBuilder();
  7044. $criteria=$builder->createCriteria($condition,$params);
  7045. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7046. return $command->execute();
  7047. }
  7048. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  7049. {
  7050. $builder=$this->getCommandBuilder();
  7051. $table=$this->getTableSchema();
  7052. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  7053. $command=$builder->createDeleteCommand($table,$criteria);
  7054. return $command->execute();
  7055. }
  7056. public function populateRecord($attributes,$callAfterFind=true)
  7057. {
  7058. if($attributes!==false)
  7059. {
  7060. $record=$this->instantiate($attributes);
  7061. $record->setScenario('update');
  7062. $record->init();
  7063. $md=$record->getMetaData();
  7064. foreach($attributes as $name=>$value)
  7065. {
  7066. if(property_exists($record,$name))
  7067. $record->$name=$value;
  7068. else if(isset($md->columns[$name]))
  7069. $record->_attributes[$name]=$value;
  7070. }
  7071. $record->_pk=$record->getPrimaryKey();
  7072. $record->attachBehaviors($record->behaviors());
  7073. if($callAfterFind)
  7074. $record->afterFind();
  7075. return $record;
  7076. }
  7077. else
  7078. return null;
  7079. }
  7080. public function populateRecords($data,$callAfterFind=true,$index=null)
  7081. {
  7082. $records=array();
  7083. foreach($data as $attributes)
  7084. {
  7085. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  7086. {
  7087. if($index===null)
  7088. $records[]=$record;
  7089. else
  7090. $records[$record->$index]=$record;
  7091. }
  7092. }
  7093. return $records;
  7094. }
  7095. protected function instantiate($attributes)
  7096. {
  7097. $class=get_class($this);
  7098. $model=new $class(null);
  7099. return $model;
  7100. }
  7101. public function offsetExists($offset)
  7102. {
  7103. return isset($this->getMetaData()->columns[$offset]);
  7104. }
  7105. }
  7106. class CBaseActiveRelation extends CComponent
  7107. {
  7108. public $name;
  7109. public $className;
  7110. public $foreignKey;
  7111. public $select='*';
  7112. public $condition='';
  7113. public $params=array();
  7114. public $group='';
  7115. public $join='';
  7116. public $having='';
  7117. public $order='';
  7118. public function __construct($name,$className,$foreignKey,$options=array())
  7119. {
  7120. $this->name=$name;
  7121. $this->className=$className;
  7122. $this->foreignKey=$foreignKey;
  7123. foreach($options as $name=>$value)
  7124. $this->$name=$value;
  7125. }
  7126. public function mergeWith($criteria,$fromScope=false)
  7127. {
  7128. if($criteria instanceof CDbCriteria)
  7129. $criteria=$criteria->toArray();
  7130. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  7131. {
  7132. if($this->select==='*')
  7133. $this->select=$criteria['select'];
  7134. else if($criteria['select']!=='*')
  7135. {
  7136. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  7137. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  7138. $this->select=array_merge($select1,array_diff($select2,$select1));
  7139. }
  7140. }
  7141. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  7142. {
  7143. if($this->condition==='')
  7144. $this->condition=$criteria['condition'];
  7145. else if($criteria['condition']!=='')
  7146. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  7147. }
  7148. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  7149. $this->params=array_merge($this->params,$criteria['params']);
  7150. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  7151. {
  7152. if($this->order==='')
  7153. $this->order=$criteria['order'];
  7154. else if($criteria['order']!=='')
  7155. $this->order=$criteria['order'].', '.$this->order;
  7156. }
  7157. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  7158. {
  7159. if($this->group==='')
  7160. $this->group=$criteria['group'];
  7161. else if($criteria['group']!=='')
  7162. $this->group.=', '.$criteria['group'];
  7163. }
  7164. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  7165. {
  7166. if($this->join==='')
  7167. $this->join=$criteria['join'];
  7168. else if($criteria['join']!=='')
  7169. $this->join.=' '.$criteria['join'];
  7170. }
  7171. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  7172. {
  7173. if($this->having==='')
  7174. $this->having=$criteria['having'];
  7175. else if($criteria['having']!=='')
  7176. $this->having="({$this->having}) AND ({$criteria['having']})";
  7177. }
  7178. }
  7179. }
  7180. class CStatRelation extends CBaseActiveRelation
  7181. {
  7182. public $select='COUNT(*)';
  7183. public $defaultValue=0;
  7184. public function mergeWith($criteria,$fromScope=false)
  7185. {
  7186. if($criteria instanceof CDbCriteria)
  7187. $criteria=$criteria->toArray();
  7188. parent::mergeWith($criteria,$fromScope);
  7189. if(isset($criteria['defaultValue']))
  7190. $this->defaultValue=$criteria['defaultValue'];
  7191. }
  7192. }
  7193. class CActiveRelation extends CBaseActiveRelation
  7194. {
  7195. public $joinType='LEFT OUTER JOIN';
  7196. public $on='';
  7197. public $alias;
  7198. public $with=array();
  7199. public $together;
  7200. public function mergeWith($criteria,$fromScope=false)
  7201. {
  7202. if($criteria instanceof CDbCriteria)
  7203. $criteria=$criteria->toArray();
  7204. if($fromScope)
  7205. {
  7206. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  7207. {
  7208. if($this->on==='')
  7209. $this->on=$criteria['condition'];
  7210. else if($criteria['condition']!=='')
  7211. $this->on="({$this->on}) AND ({$criteria['condition']})";
  7212. }
  7213. unset($criteria['condition']);
  7214. }
  7215. parent::mergeWith($criteria);
  7216. if(isset($criteria['joinType']))
  7217. $this->joinType=$criteria['joinType'];
  7218. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  7219. {
  7220. if($this->on==='')
  7221. $this->on=$criteria['on'];
  7222. else if($criteria['on']!=='')
  7223. $this->on="({$this->on}) AND ({$criteria['on']})";
  7224. }
  7225. if(isset($criteria['with']))
  7226. $this->with=$criteria['with'];
  7227. if(isset($criteria['alias']))
  7228. $this->alias=$criteria['alias'];
  7229. if(array_key_exists('together',$criteria))
  7230. $this->together=$criteria['together'];
  7231. }
  7232. }
  7233. class CBelongsToRelation extends CActiveRelation
  7234. {
  7235. }
  7236. class CHasOneRelation extends CActiveRelation
  7237. {
  7238. }
  7239. class CHasManyRelation extends CActiveRelation
  7240. {
  7241. public $limit=-1;
  7242. public $offset=-1;
  7243. public $index;
  7244. public function mergeWith($criteria,$fromScope=false)
  7245. {
  7246. if($criteria instanceof CDbCriteria)
  7247. $criteria=$criteria->toArray();
  7248. parent::mergeWith($criteria,$fromScope);
  7249. if(isset($criteria['limit']) && $criteria['limit']>0)
  7250. $this->limit=$criteria['limit'];
  7251. if(isset($criteria['offset']) && $criteria['offset']>=0)
  7252. $this->offset=$criteria['offset'];
  7253. if(isset($criteria['index']))
  7254. $this->index=$criteria['index'];
  7255. }
  7256. }
  7257. class CManyManyRelation extends CHasManyRelation
  7258. {
  7259. }
  7260. class CActiveRecordMetaData
  7261. {
  7262. public $tableSchema;
  7263. public $columns;
  7264. public $relations=array();
  7265. public $attributeDefaults=array();
  7266. private $_model;
  7267. public function __construct($model)
  7268. {
  7269. $this->_model=$model;
  7270. $tableName=$model->tableName();
  7271. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  7272. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  7273. array('{class}'=>get_class($model),'{table}'=>$tableName)));
  7274. if($table->primaryKey===null)
  7275. $table->primaryKey=$model->primaryKey();
  7276. $this->tableSchema=$table;
  7277. $this->columns=$table->columns;
  7278. foreach($table->columns as $name=>$column)
  7279. {
  7280. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  7281. $this->attributeDefaults[$name]=$column->defaultValue;
  7282. }
  7283. foreach($model->relations() as $name=>$config)
  7284. {
  7285. $this->addRelation($name,$config);
  7286. }
  7287. }
  7288. public function addRelation($name,$config)
  7289. {
  7290. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  7291. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  7292. else
  7293. throw new CDbException(Yii::t('yii','Active record "{class}" has an invalid configuration for relation "{relation}". It must specify the relation type, the related active record class and the foreign key.', array('{class}'=>get_class($this->_model),'{relation}'=>$name)));
  7294. }
  7295. public function hasRelation($name)
  7296. {
  7297. return isset($this->relations[$name]);
  7298. }
  7299. public function removeRelation($name)
  7300. {
  7301. unset($this->relations[$name]);
  7302. }
  7303. }
  7304. class CDbConnection extends CApplicationComponent
  7305. {
  7306. public $connectionString;
  7307. public $username='';
  7308. public $password='';
  7309. public $schemaCachingDuration=0;
  7310. public $schemaCachingExclude=array();
  7311. public $schemaCacheID='cache';
  7312. public $autoConnect=true;
  7313. public $charset;
  7314. public $emulatePrepare=false;
  7315. public $enableParamLogging=false;
  7316. public $enableProfiling=false;
  7317. public $tablePrefix;
  7318. public $initSQLs;
  7319. private $_attributes=array();
  7320. private $_active=false;
  7321. private $_pdo;
  7322. private $_transaction;
  7323. private $_schema;
  7324. public function __construct($dsn='',$username='',$password='')
  7325. {
  7326. $this->connectionString=$dsn;
  7327. $this->username=$username;
  7328. $this->password=$password;
  7329. }
  7330. public function __sleep()
  7331. {
  7332. $this->close();
  7333. return array_keys(get_object_vars($this));
  7334. }
  7335. public static function getAvailableDrivers()
  7336. {
  7337. return PDO::getAvailableDrivers();
  7338. }
  7339. public function init()
  7340. {
  7341. parent::init();
  7342. if($this->autoConnect)
  7343. $this->setActive(true);
  7344. }
  7345. public function getActive()
  7346. {
  7347. return $this->_active;
  7348. }
  7349. public function setActive($value)
  7350. {
  7351. if($value!=$this->_active)
  7352. {
  7353. if($value)
  7354. $this->open();
  7355. else
  7356. $this->close();
  7357. }
  7358. }
  7359. protected function open()
  7360. {
  7361. if($this->_pdo===null)
  7362. {
  7363. if(empty($this->connectionString))
  7364. throw new CDbException(Yii::t('yii','CDbConnection.connectionString cannot be empty.'));
  7365. try
  7366. {
  7367. $this->_pdo=$this->createPdoInstance();
  7368. $this->initConnection($this->_pdo);
  7369. $this->_active=true;
  7370. }
  7371. catch(PDOException $e)
  7372. {
  7373. if(YII_DEBUG)
  7374. {
  7375. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection: {error}',
  7376. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$e->errorInfo);
  7377. }
  7378. else
  7379. {
  7380. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  7381. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'),(int)$e->getCode(),$e->errorInfo);
  7382. }
  7383. }
  7384. }
  7385. }
  7386. protected function close()
  7387. {
  7388. $this->_pdo=null;
  7389. $this->_active=false;
  7390. $this->_schema=null;
  7391. }
  7392. protected function createPdoInstance()
  7393. {
  7394. $pdoClass='PDO';
  7395. if(($pos=strpos($this->connectionString,':'))!==false)
  7396. {
  7397. $driver=strtolower(substr($this->connectionString,0,$pos));
  7398. if($driver==='mssql' || $driver==='dblib')
  7399. $pdoClass='CMssqlPdoAdapter';
  7400. }
  7401. return new $pdoClass($this->connectionString,$this->username,
  7402. $this->password,$this->_attributes);
  7403. }
  7404. protected function initConnection($pdo)
  7405. {
  7406. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  7407. if($this->emulatePrepare && constant('PDO::ATTR_EMULATE_PREPARES'))
  7408. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,true);
  7409. if($this->charset!==null)
  7410. {
  7411. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  7412. if(in_array($driver,array('pgsql','mysql','mysqli')))
  7413. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  7414. }
  7415. if($this->initSQLs!==null)
  7416. {
  7417. foreach($this->initSQLs as $sql)
  7418. $pdo->exec($sql);
  7419. }
  7420. }
  7421. public function getPdoInstance()
  7422. {
  7423. return $this->_pdo;
  7424. }
  7425. public function createCommand($sql)
  7426. {
  7427. if($this->getActive())
  7428. return new CDbCommand($this,$sql);
  7429. else
  7430. throw new CDbException(Yii::t('yii','CDbConnection is inactive and cannot perform any DB operations.'));
  7431. }
  7432. public function getCurrentTransaction()
  7433. {
  7434. if($this->_transaction!==null)
  7435. {
  7436. if($this->_transaction->getActive())
  7437. return $this->_transaction;
  7438. }
  7439. return null;
  7440. }
  7441. public function beginTransaction()
  7442. {
  7443. if($this->getActive())
  7444. {
  7445. $this->_pdo->beginTransaction();
  7446. return $this->_transaction=new CDbTransaction($this);
  7447. }
  7448. else
  7449. throw new CDbException(Yii::t('yii','CDbConnection is inactive and cannot perform any DB operations.'));
  7450. }
  7451. public function getSchema()
  7452. {
  7453. if($this->_schema!==null)
  7454. return $this->_schema;
  7455. else
  7456. {
  7457. if(!$this->getActive())
  7458. throw new CDbException(Yii::t('yii','CDbConnection is inactive and cannot perform any DB operations.'));
  7459. $driver=$this->getDriverName();
  7460. switch(strtolower($driver))
  7461. {
  7462. case 'pgsql': // PostgreSQL
  7463. return $this->_schema=new CPgsqlSchema($this);
  7464. case 'mysqli': // MySQL
  7465. case 'mysql':
  7466. return $this->_schema=new CMysqlSchema($this);
  7467. case 'sqlite': // sqlite 3
  7468. case 'sqlite2': // sqlite 2
  7469. return $this->_schema=new CSqliteSchema($this);
  7470. case 'mssql': // Mssql driver on windows hosts
  7471. case 'dblib': // dblib drivers on linux (and maybe others os) hosts
  7472. case 'sqlsrv':
  7473. return $this->_schema=new CMssqlSchema($this);
  7474. case 'oci': // Oracle driver
  7475. return $this->_schema=new COciSchema($this);
  7476. case 'ibm':
  7477. default:
  7478. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  7479. array('{driver}'=>$driver)));
  7480. }
  7481. }
  7482. }
  7483. public function getCommandBuilder()
  7484. {
  7485. return $this->getSchema()->getCommandBuilder();
  7486. }
  7487. public function getLastInsertID($sequenceName='')
  7488. {
  7489. if($this->getActive())
  7490. return $this->_pdo->lastInsertId($sequenceName);
  7491. else
  7492. throw new CDbException(Yii::t('yii','CDbConnection is inactive and cannot perform any DB operations.'));
  7493. }
  7494. public function quoteValue($str)
  7495. {
  7496. if($this->getActive())
  7497. return $this->_pdo->quote($str);
  7498. else
  7499. throw new CDbException(Yii::t('yii','CDbConnection is inactive and cannot perform any DB operations.'));
  7500. }
  7501. public function quoteTableName($name)
  7502. {
  7503. return $this->getSchema()->quoteTableName($name);
  7504. }
  7505. public function quoteColumnName($name)
  7506. {
  7507. return $this->getSchema()->quoteColumnName($name);
  7508. }
  7509. public function getPdoType($type)
  7510. {
  7511. static $map=array
  7512. (
  7513. 'boolean'=>PDO::PARAM_BOOL,
  7514. 'integer'=>PDO::PARAM_INT,
  7515. 'string'=>PDO::PARAM_STR,
  7516. 'NULL'=>PDO::PARAM_NULL,
  7517. );
  7518. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  7519. }
  7520. public function getColumnCase()
  7521. {
  7522. return $this->getAttribute(PDO::ATTR_CASE);
  7523. }
  7524. public function setColumnCase($value)
  7525. {
  7526. $this->setAttribute(PDO::ATTR_CASE,$value);
  7527. }
  7528. public function getNullConversion()
  7529. {
  7530. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  7531. }
  7532. public function setNullConversion($value)
  7533. {
  7534. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  7535. }
  7536. public function getAutoCommit()
  7537. {
  7538. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  7539. }
  7540. public function setAutoCommit($value)
  7541. {
  7542. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  7543. }
  7544. public function getPersistent()
  7545. {
  7546. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  7547. }
  7548. public function setPersistent($value)
  7549. {
  7550. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  7551. }
  7552. public function getDriverName()
  7553. {
  7554. return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  7555. }
  7556. public function getClientVersion()
  7557. {
  7558. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  7559. }
  7560. public function getConnectionStatus()
  7561. {
  7562. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  7563. }
  7564. public function getPrefetch()
  7565. {
  7566. return $this->getAttribute(PDO::ATTR_PREFETCH);
  7567. }
  7568. public function getServerInfo()
  7569. {
  7570. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  7571. }
  7572. public function getServerVersion()
  7573. {
  7574. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  7575. }
  7576. public function getTimeout()
  7577. {
  7578. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  7579. }
  7580. public function getAttribute($name)
  7581. {
  7582. if($this->getActive())
  7583. return $this->_pdo->getAttribute($name);
  7584. else
  7585. throw new CDbException(Yii::t('yii','CDbConnection is inactive and cannot perform any DB operations.'));
  7586. }
  7587. public function setAttribute($name,$value)
  7588. {
  7589. if($this->_pdo instanceof PDO)
  7590. $this->_pdo->setAttribute($name,$value);
  7591. else
  7592. $this->_attributes[$name]=$value;
  7593. }
  7594. public function getStats()
  7595. {
  7596. $logger=Yii::getLogger();
  7597. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  7598. $count=count($timings);
  7599. $time=array_sum($timings);
  7600. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  7601. $count+=count($timings);
  7602. $time+=array_sum($timings);
  7603. return array($count,$time);
  7604. }
  7605. }
  7606. abstract class CDbSchema extends CComponent
  7607. {
  7608. private $_tableNames=array();
  7609. private $_tables=array();
  7610. private $_connection;
  7611. private $_builder;
  7612. private $_cacheExclude=array();
  7613. abstract protected function createTable($name);
  7614. public function __construct($conn)
  7615. {
  7616. $conn->setActive(true);
  7617. $this->_connection=$conn;
  7618. foreach($conn->schemaCachingExclude as $name)
  7619. $this->_cacheExclude[$name]=true;
  7620. }
  7621. public function getDbConnection()
  7622. {
  7623. return $this->_connection;
  7624. }
  7625. public function getTable($name)
  7626. {
  7627. if(isset($this->_tables[$name]))
  7628. return $this->_tables[$name];
  7629. else
  7630. {
  7631. if($this->_connection->tablePrefix!='' && strpos($name,'{{')!==false)
  7632. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  7633. else
  7634. $realName=$name;
  7635. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  7636. {
  7637. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  7638. if(($table=$cache->get($key))===false)
  7639. {
  7640. $table=$this->createTable($realName);
  7641. if($table!==null)
  7642. $cache->set($key,$table,$duration);
  7643. }
  7644. return $this->_tables[$name]=$table;
  7645. }
  7646. else
  7647. return $this->_tables[$name]=$this->createTable($realName);
  7648. }
  7649. }
  7650. public function getTables($schema='')
  7651. {
  7652. $tables=array();
  7653. foreach($this->getTableNames($schema) as $name)
  7654. {
  7655. if(($table=$this->getTable($name))!==null)
  7656. $tables[$name]=$table;
  7657. }
  7658. return $tables;
  7659. }
  7660. public function getTableNames($schema='')
  7661. {
  7662. if(!isset($this->_tableNames[$schema]))
  7663. $this->_tableNames[$schema]=$this->findTableNames($schema);
  7664. return $this->_tableNames[$schema];
  7665. }
  7666. public function getCommandBuilder()
  7667. {
  7668. if($this->_builder!==null)
  7669. return $this->_builder;
  7670. else
  7671. return $this->_builder=$this->createCommandBuilder();
  7672. }
  7673. public function refresh()
  7674. {
  7675. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  7676. {
  7677. foreach(array_keys($this->_tables) as $name)
  7678. {
  7679. if(!isset($this->_cacheExclude[$name]))
  7680. {
  7681. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  7682. $cache->delete($key);
  7683. }
  7684. }
  7685. }
  7686. $this->_tables=array();
  7687. $this->_tableNames=array();
  7688. $this->_builder=null;
  7689. }
  7690. public function quoteTableName($name)
  7691. {
  7692. return "'".$name."'";
  7693. }
  7694. public function quoteColumnName($name)
  7695. {
  7696. return '"'.$name.'"';
  7697. }
  7698. public function compareTableNames($name1,$name2)
  7699. {
  7700. $name1=str_replace(array('"','`',"'"),'',$name1);
  7701. $name2=str_replace(array('"','`',"'"),'',$name2);
  7702. if(($pos=strrpos($name1,'.'))!==false)
  7703. $name1=substr($name1,$pos+1);
  7704. if(($pos=strrpos($name2,'.'))!==false)
  7705. $name2=substr($name2,$pos+1);
  7706. if($this->_connection->tablePrefix!==null)
  7707. {
  7708. if(strpos($name1,'{')!==false)
  7709. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  7710. if(strpos($name2,'{')!==false)
  7711. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  7712. }
  7713. return $name1===$name2;
  7714. }
  7715. public function resetSequence($table,$value=null)
  7716. {
  7717. throw new CDbException(Yii::t('yii','Resetting PK sequence is not supported.'));
  7718. }
  7719. public function checkIntegrity($check=true,$schema='')
  7720. {
  7721. throw new CDbException(Yii::t('yii','Setting integrity check is not supported.'));
  7722. }
  7723. protected function createCommandBuilder()
  7724. {
  7725. return new CDbCommandBuilder($this);
  7726. }
  7727. protected function findTableNames($schema='')
  7728. {
  7729. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  7730. array('{class}'=>get_class($this))));
  7731. }
  7732. }
  7733. class CSqliteSchema extends CDbSchema
  7734. {
  7735. public function resetSequence($table,$value=null)
  7736. {
  7737. if($table->sequenceName!==null)
  7738. {
  7739. if($value===null)
  7740. $value=$this->getDbConnection()->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")->queryScalar();
  7741. else
  7742. $value=(int)$value-1;
  7743. $this->getDbConnection()->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")->execute();
  7744. }
  7745. }
  7746. public function checkIntegrity($check=true,$schema='')
  7747. {
  7748. // SQLite doesn't enforce integrity
  7749. return;
  7750. }
  7751. protected function findTableNames($schema='')
  7752. {
  7753. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  7754. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  7755. }
  7756. protected function createCommandBuilder()
  7757. {
  7758. return new CSqliteCommandBuilder($this);
  7759. }
  7760. protected function createTable($name)
  7761. {
  7762. $table=new CDbTableSchema;
  7763. $table->name=$name;
  7764. $table->rawName=$this->quoteTableName($name);
  7765. if($this->findColumns($table))
  7766. {
  7767. $this->findConstraints($table);
  7768. return $table;
  7769. }
  7770. else
  7771. return null;
  7772. }
  7773. protected function findColumns($table)
  7774. {
  7775. $sql="PRAGMA table_info({$table->rawName})";
  7776. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  7777. if(empty($columns))
  7778. return false;
  7779. foreach($columns as $column)
  7780. {
  7781. $c=$this->createColumn($column);
  7782. $table->columns[$c->name]=$c;
  7783. if($c->isPrimaryKey)
  7784. {
  7785. if($table->primaryKey===null)
  7786. $table->primaryKey=$c->name;
  7787. else if(is_string($table->primaryKey))
  7788. $table->primaryKey=array($table->primaryKey,$c->name);
  7789. else
  7790. $table->primaryKey[]=$c->name;
  7791. }
  7792. }
  7793. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  7794. $table->sequenceName='';
  7795. return true;
  7796. }
  7797. protected function findConstraints($table)
  7798. {
  7799. $foreignKeys=array();
  7800. $sql="PRAGMA foreign_key_list({$table->rawName})";
  7801. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  7802. foreach($keys as $key)
  7803. {
  7804. $column=$table->columns[$key['from']];
  7805. $column->isForeignKey=true;
  7806. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  7807. }
  7808. $table->foreignKeys=$foreignKeys;
  7809. }
  7810. protected function createColumn($column)
  7811. {
  7812. $c=new CSqliteColumnSchema;
  7813. $c->name=$column['name'];
  7814. $c->rawName=$this->quoteColumnName($c->name);
  7815. $c->allowNull=!$column['notnull'];
  7816. $c->isPrimaryKey=$column['pk']!=0;
  7817. $c->isForeignKey=false;
  7818. $c->init(strtolower($column['type']),$column['dflt_value']);
  7819. return $c;
  7820. }
  7821. }
  7822. class CDbTableSchema extends CComponent
  7823. {
  7824. public $name;
  7825. public $rawName;
  7826. public $primaryKey;
  7827. public $sequenceName;
  7828. public $foreignKeys=array();
  7829. public $columns=array();
  7830. public function getColumn($name)
  7831. {
  7832. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  7833. }
  7834. public function getColumnNames()
  7835. {
  7836. return array_keys($this->columns);
  7837. }
  7838. }
  7839. class CDbCommand extends CComponent
  7840. {
  7841. private $_connection;
  7842. private $_text='';
  7843. private $_statement=null;
  7844. private $_params=array();
  7845. public function __construct(CDbConnection $connection,$text)
  7846. {
  7847. $this->_connection=$connection;
  7848. $this->setText($text);
  7849. }
  7850. public function __sleep()
  7851. {
  7852. $this->_statement=null;
  7853. return array_keys(get_object_vars($this));
  7854. }
  7855. public function getText()
  7856. {
  7857. return $this->_text;
  7858. }
  7859. public function setText($value)
  7860. {
  7861. if($this->_connection->tablePrefix!==null)
  7862. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  7863. else
  7864. $this->_text=$value;
  7865. $this->cancel();
  7866. }
  7867. public function getConnection()
  7868. {
  7869. return $this->_connection;
  7870. }
  7871. public function getPdoStatement()
  7872. {
  7873. return $this->_statement;
  7874. }
  7875. public function prepare()
  7876. {
  7877. if($this->_statement==null)
  7878. {
  7879. try
  7880. {
  7881. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  7882. $this->_params=array();
  7883. }
  7884. catch(Exception $e)
  7885. {
  7886. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  7887. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  7888. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  7889. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  7890. }
  7891. }
  7892. }
  7893. public function cancel()
  7894. {
  7895. $this->_statement=null;
  7896. }
  7897. public function bindParam($name, &$value, $dataType=null, $length=null)
  7898. {
  7899. $this->prepare();
  7900. if($dataType===null)
  7901. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  7902. else if($length===null)
  7903. $this->_statement->bindParam($name,$value,$dataType);
  7904. else
  7905. $this->_statement->bindParam($name,$value,$dataType,$length);
  7906. if($this->_connection->enableParamLogging)
  7907. $this->_params[$name]=&$value;
  7908. return $this;
  7909. }
  7910. public function bindValue($name, $value, $dataType=null)
  7911. {
  7912. $this->prepare();
  7913. if($dataType===null)
  7914. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  7915. else
  7916. $this->_statement->bindValue($name,$value,$dataType);
  7917. if($this->_connection->enableParamLogging)
  7918. $this->_params[$name]=var_export($value,true);
  7919. return $this;
  7920. }
  7921. public function bindValues($values)
  7922. {
  7923. $this->prepare();
  7924. foreach($values as $name=>$value)
  7925. {
  7926. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  7927. if($this->_connection->enableParamLogging)
  7928. $this->_params[$name]=var_export($value,true);
  7929. }
  7930. return $this;
  7931. }
  7932. public function execute($params=array())
  7933. {
  7934. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_params,$params))!==array())
  7935. {
  7936. $p=array();
  7937. foreach($pars as $name=>$value)
  7938. $p[$name]=$name.'='.$value;
  7939. $par='. Bound with ' .implode(', ',$p);
  7940. }
  7941. else
  7942. $par='';
  7943. try
  7944. {
  7945. if($this->_connection->enableProfiling)
  7946. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  7947. $this->prepare();
  7948. if($params===array())
  7949. $this->_statement->execute();
  7950. else
  7951. $this->_statement->execute($params);
  7952. $n=$this->_statement->rowCount();
  7953. if($this->_connection->enableProfiling)
  7954. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  7955. return $n;
  7956. }
  7957. catch(Exception $e)
  7958. {
  7959. if($this->_connection->enableProfiling)
  7960. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  7961. Yii::log('Error in executing SQL: '.$this->getText().$par,CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  7962. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  7963. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  7964. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  7965. }
  7966. }
  7967. public function query($params=array())
  7968. {
  7969. return $this->queryInternal('',0,$params);
  7970. }
  7971. public function queryAll($fetchAssociative=true,$params=array())
  7972. {
  7973. return $this->queryInternal('fetchAll',$fetchAssociative ? PDO::FETCH_ASSOC : PDO::FETCH_NUM, $params);
  7974. }
  7975. public function queryRow($fetchAssociative=true,$params=array())
  7976. {
  7977. return $this->queryInternal('fetch',$fetchAssociative ? PDO::FETCH_ASSOC : PDO::FETCH_NUM, $params);
  7978. }
  7979. public function queryScalar($params=array())
  7980. {
  7981. $result=$this->queryInternal('fetchColumn',0,$params);
  7982. if(is_resource($result) && get_resource_type($result)==='stream')
  7983. return stream_get_contents($result);
  7984. else
  7985. return $result;
  7986. }
  7987. public function queryColumn($params=array())
  7988. {
  7989. return $this->queryInternal('fetchAll',PDO::FETCH_COLUMN,$params);
  7990. }
  7991. private function queryInternal($method,$mode,$params=array())
  7992. {
  7993. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_params,$params))!==array())
  7994. {
  7995. $p=array();
  7996. foreach($pars as $name=>$value)
  7997. $p[$name]=$name.'='.$value;
  7998. $par='. Bound with '.implode(', ',$p);
  7999. }
  8000. else
  8001. $par='';
  8002. try
  8003. {
  8004. if($this->_connection->enableProfiling)
  8005. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8006. $this->prepare();
  8007. if($params===array())
  8008. $this->_statement->execute();
  8009. else
  8010. $this->_statement->execute($params);
  8011. if($method==='')
  8012. $result=new CDbDataReader($this);
  8013. else
  8014. {
  8015. $result=$this->_statement->{$method}($mode);
  8016. $this->_statement->closeCursor();
  8017. }
  8018. if($this->_connection->enableProfiling)
  8019. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8020. return $result;
  8021. }
  8022. catch(Exception $e)
  8023. {
  8024. if($this->_connection->enableProfiling)
  8025. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8026. Yii::log('Error in querying SQL: '.$this->getText().$par,CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8027. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8028. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8029. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  8030. }
  8031. }
  8032. }
  8033. class CDbColumnSchema extends CComponent
  8034. {
  8035. public $name;
  8036. public $rawName;
  8037. public $allowNull;
  8038. public $dbType;
  8039. public $type;
  8040. public $defaultValue;
  8041. public $size;
  8042. public $precision;
  8043. public $scale;
  8044. public $isPrimaryKey;
  8045. public $isForeignKey;
  8046. public function init($dbType, $defaultValue)
  8047. {
  8048. $this->dbType=$dbType;
  8049. $this->extractType($dbType);
  8050. $this->extractLimit($dbType);
  8051. if($defaultValue!==null)
  8052. $this->extractDefault($defaultValue);
  8053. }
  8054. protected function extractType($dbType)
  8055. {
  8056. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  8057. $this->type='integer';
  8058. else if(stripos($dbType,'bool')!==false)
  8059. $this->type='boolean';
  8060. else if(preg_match('/(real|floa|doub)/i',$dbType))
  8061. $this->type='double';
  8062. else
  8063. $this->type='string';
  8064. }
  8065. protected function extractLimit($dbType)
  8066. {
  8067. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  8068. {
  8069. $values=explode(',',$matches[1]);
  8070. $this->size=$this->precision=(int)$values[0];
  8071. if(isset($values[1]))
  8072. $this->scale=(int)$values[1];
  8073. }
  8074. }
  8075. protected function extractDefault($defaultValue)
  8076. {
  8077. $this->defaultValue=$this->typecast($defaultValue);
  8078. }
  8079. public function typecast($value)
  8080. {
  8081. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  8082. return $value;
  8083. if($value==='')
  8084. return $this->type==='string' ? '' : null;
  8085. switch($this->type)
  8086. {
  8087. case 'string': return (string)$value;
  8088. case 'integer': return (integer)$value;
  8089. case 'boolean': return (boolean)$value;
  8090. case 'double':
  8091. default: return $value;
  8092. }
  8093. }
  8094. }
  8095. class CSqliteColumnSchema extends CDbColumnSchema
  8096. {
  8097. protected function extractDefault($defaultValue)
  8098. {
  8099. if($this->type==='string') // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  8100. $this->defaultValue=trim($defaultValue,"'\"");
  8101. else
  8102. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  8103. }
  8104. }
  8105. abstract class CValidator extends CComponent
  8106. {
  8107. public static $builtInValidators=array(
  8108. 'required'=>'CRequiredValidator',
  8109. 'filter'=>'CFilterValidator',
  8110. 'match'=>'CRegularExpressionValidator',
  8111. 'email'=>'CEmailValidator',
  8112. 'url'=>'CUrlValidator',
  8113. 'unique'=>'CUniqueValidator',
  8114. 'compare'=>'CCompareValidator',
  8115. 'length'=>'CStringValidator',
  8116. 'in'=>'CRangeValidator',
  8117. 'numerical'=>'CNumberValidator',
  8118. 'captcha'=>'CCaptchaValidator',
  8119. 'type'=>'CTypeValidator',
  8120. 'file'=>'CFileValidator',
  8121. 'default'=>'CDefaultValueValidator',
  8122. 'exist'=>'CExistValidator',
  8123. 'boolean'=>'CBooleanValidator',
  8124. 'safe'=>'CSafeValidator',
  8125. 'unsafe'=>'CUnsafeValidator',
  8126. );
  8127. public $attributes;
  8128. public $message;
  8129. public $skipOnError=false;
  8130. public $on;
  8131. public $safe=true;
  8132. abstract protected function validateAttribute($object,$attribute);
  8133. public static function createValidator($name,$object,$attributes,$params)
  8134. {
  8135. if(is_string($attributes))
  8136. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  8137. if(isset($params['on']))
  8138. {
  8139. if(is_array($params['on']))
  8140. $on=$params['on'];
  8141. else
  8142. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  8143. }
  8144. else
  8145. $on=array();
  8146. if(method_exists($object,$name))
  8147. {
  8148. $validator=new CInlineValidator;
  8149. $validator->attributes=$attributes;
  8150. $validator->method=$name;
  8151. $validator->params=$params;
  8152. if(isset($params['skipOnError']))
  8153. $validator->skipOnError=$params['skipOnError'];
  8154. }
  8155. else
  8156. {
  8157. $params['attributes']=$attributes;
  8158. if(isset(self::$builtInValidators[$name]))
  8159. $className=Yii::import(self::$builtInValidators[$name],true);
  8160. else
  8161. $className=Yii::import($name,true);
  8162. $validator=new $className;
  8163. foreach($params as $name=>$value)
  8164. $validator->$name=$value;
  8165. }
  8166. $validator->on=empty($on) ? array() : array_combine($on,$on);
  8167. return $validator;
  8168. }
  8169. public function validate($object,$attributes=null)
  8170. {
  8171. if(is_array($attributes))
  8172. $attributes=array_intersect($this->attributes,$attributes);
  8173. else
  8174. $attributes=$this->attributes;
  8175. foreach($attributes as $attribute)
  8176. {
  8177. if(!$this->skipOnError || !$object->hasErrors($attribute))
  8178. $this->validateAttribute($object,$attribute);
  8179. }
  8180. }
  8181. public function applyTo($scenario)
  8182. {
  8183. return empty($this->on) || isset($this->on[$scenario]);
  8184. }
  8185. protected function addError($object,$attribute,$message,$params=array())
  8186. {
  8187. $params['{attribute}']=$object->getAttributeLabel($attribute);
  8188. $object->addError($attribute,strtr($message,$params));
  8189. }
  8190. protected function isEmpty($value,$trim=false)
  8191. {
  8192. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  8193. }
  8194. }
  8195. class CStringValidator extends CValidator
  8196. {
  8197. public $max;
  8198. public $min;
  8199. public $is;
  8200. public $tooShort;
  8201. public $tooLong;
  8202. public $allowEmpty=true;
  8203. public $encoding=false;
  8204. protected function validateAttribute($object,$attribute)
  8205. {
  8206. $value=$object->$attribute;
  8207. if($this->allowEmpty && $this->isEmpty($value))
  8208. return;
  8209. if($this->encoding!==false && function_exists('mb_strlen'))
  8210. $length=mb_strlen($value,$this->encoding);
  8211. else
  8212. $length=strlen($value);
  8213. if($this->min!==null && $length<$this->min)
  8214. {
  8215. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  8216. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  8217. }
  8218. if($this->max!==null && $length>$this->max)
  8219. {
  8220. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  8221. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  8222. }
  8223. if($this->is!==null && $length!==$this->is)
  8224. {
  8225. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  8226. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  8227. }
  8228. }
  8229. }
  8230. class CRequiredValidator extends CValidator
  8231. {
  8232. public $requiredValue;
  8233. public $strict=false;
  8234. protected function validateAttribute($object,$attribute)
  8235. {
  8236. $value=$object->$attribute;
  8237. if($this->requiredValue!==null)
  8238. {
  8239. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  8240. {
  8241. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  8242. array('{value}'=>$this->requiredValue));
  8243. $this->addError($object,$attribute,$message);
  8244. }
  8245. }
  8246. else if($this->isEmpty($value,true))
  8247. {
  8248. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  8249. $this->addError($object,$attribute,$message);
  8250. }
  8251. }
  8252. }
  8253. class CNumberValidator extends CValidator
  8254. {
  8255. public $integerOnly=false;
  8256. public $allowEmpty=true;
  8257. public $max;
  8258. public $min;
  8259. public $tooBig;
  8260. public $tooSmall;
  8261. protected function validateAttribute($object,$attribute)
  8262. {
  8263. $value=$object->$attribute;
  8264. if($this->allowEmpty && $this->isEmpty($value))
  8265. return;
  8266. if($this->integerOnly)
  8267. {
  8268. if(!preg_match('/^\s*[+-]?\d+\s*$/',"$value"))
  8269. {
  8270. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  8271. $this->addError($object,$attribute,$message);
  8272. }
  8273. }
  8274. else
  8275. {
  8276. if(!preg_match('/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/',"$value"))
  8277. {
  8278. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  8279. $this->addError($object,$attribute,$message);
  8280. }
  8281. }
  8282. if($this->min!==null && $value<$this->min)
  8283. {
  8284. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  8285. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  8286. }
  8287. if($this->max!==null && $value>$this->max)
  8288. {
  8289. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  8290. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  8291. }
  8292. }
  8293. }
  8294. class CListIterator implements Iterator
  8295. {
  8296. private $_d;
  8297. private $_i;
  8298. private $_c;
  8299. public function __construct(&$data)
  8300. {
  8301. $this->_d=&$data;
  8302. $this->_i=0;
  8303. $this->_c=count($this->_d);
  8304. }
  8305. public function rewind()
  8306. {
  8307. $this->_i=0;
  8308. }
  8309. public function key()
  8310. {
  8311. return $this->_i;
  8312. }
  8313. public function current()
  8314. {
  8315. return $this->_d[$this->_i];
  8316. }
  8317. public function next()
  8318. {
  8319. $this->_i++;
  8320. }
  8321. public function valid()
  8322. {
  8323. return $this->_i<$this->_c;
  8324. }
  8325. }
  8326. interface IApplicationComponent
  8327. {
  8328. public function init();
  8329. public function getIsInitialized();
  8330. }
  8331. interface ICache
  8332. {
  8333. public function get($id);
  8334. public function mget($ids);
  8335. public function set($id,$value,$expire=0,$dependency=null);
  8336. public function add($id,$value,$expire=0,$dependency=null);
  8337. public function delete($id);
  8338. public function flush();
  8339. }
  8340. interface ICacheDependency
  8341. {
  8342. public function evaluateDependency();
  8343. public function getHasChanged();
  8344. }
  8345. interface IStatePersister
  8346. {
  8347. public function load();
  8348. public function save($state);
  8349. }
  8350. interface IFilter
  8351. {
  8352. public function filter($filterChain);
  8353. }
  8354. interface IAction
  8355. {
  8356. public function run();
  8357. public function getId();
  8358. public function getController();
  8359. }
  8360. interface IWebServiceProvider
  8361. {
  8362. public function beforeWebMethod($service);
  8363. public function afterWebMethod($service);
  8364. }
  8365. interface IViewRenderer
  8366. {
  8367. public function renderFile($context,$file,$data,$return);
  8368. }
  8369. interface IUserIdentity
  8370. {
  8371. public function authenticate();
  8372. public function getIsAuthenticated();
  8373. public function getId();
  8374. public function getName();
  8375. public function getPersistentStates();
  8376. }
  8377. interface IWebUser
  8378. {
  8379. public function getId();
  8380. public function getName();
  8381. public function getIsGuest();
  8382. public function checkAccess($operation,$params=array());
  8383. }
  8384. interface IAuthManager
  8385. {
  8386. public function checkAccess($itemName,$userId,$params=array());
  8387. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  8388. public function removeAuthItem($name);
  8389. public function getAuthItems($type=null,$userId=null);
  8390. public function getAuthItem($name);
  8391. public function saveAuthItem($item,$oldName=null);
  8392. public function addItemChild($itemName,$childName);
  8393. public function removeItemChild($itemName,$childName);
  8394. public function hasItemChild($itemName,$childName);
  8395. public function getItemChildren($itemName);
  8396. public function assign($itemName,$userId,$bizRule=null,$data=null);
  8397. public function revoke($itemName,$userId);
  8398. public function isAssigned($itemName,$userId);
  8399. public function getAuthAssignment($itemName,$userId);
  8400. public function getAuthAssignments($userId);
  8401. public function saveAuthAssignment($assignment);
  8402. public function clearAll();
  8403. public function clearAuthAssignments();
  8404. public function save();
  8405. public function executeBizRule($bizRule,$params,$data);
  8406. }
  8407. interface IBehavior
  8408. {
  8409. public function attach($component);
  8410. public function detach($component);
  8411. public function getEnabled();
  8412. public function setEnabled($value);
  8413. }
  8414. interface IWidgetFactory
  8415. {
  8416. public function createWidget($owner,$className,$properties=array());
  8417. }
  8418. interface IDataProvider
  8419. {
  8420. public function getId();
  8421. public function getItemCount($refresh=false);
  8422. public function getTotalItemCount($refresh=false);
  8423. public function getData($refresh=false);
  8424. public function getKeys($refresh=false);
  8425. public function getSort();
  8426. public function getPagination();
  8427. }
  8428. ?>