PageRenderTime 57ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 1ms

/yii/framework/yiilite.php

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