PageRenderTime 111ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/framework/yiilite.php

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