PageRenderTime 90ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/framework/yiilite.php

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