PageRenderTime 63ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 2ms

/Yii/framework/yiilite.php

https://bitbucket.org/lyubomirv/scrumtool
PHP | 10030 lines | 9975 code | 2 blank | 53 comment | 815 complexity | 5b8742470e4dbb1473e1dae026fe0aee MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, LGPL-2.1
  1. <?php
  2. /**
  3. * Yii bootstrap file.
  4. *
  5. * This file is automatically generated using 'build lite' command.
  6. * It is the result of merging commonly used Yii class files with
  7. * comments and trace statements removed away.
  8. *
  9. * By using this file instead of yii.php, an Yii application may
  10. * improve performance due to the reduction of PHP parsing time.
  11. * The performance improvement is especially obvious when PHP APC extension
  12. * is enabled.
  13. *
  14. * DO NOT modify this file manually.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @link http://www.yiiframework.com/
  18. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  19. * @license http://www.yiiframework.com/license/
  20. * @version $Id: yiilite.php 3526 2012-01-01 03:18:43Z qiang.xue $
  21. * @since 1.0
  22. */
  23. defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME',microtime(true));
  24. defined('YII_DEBUG') or define('YII_DEBUG',false);
  25. defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',0);
  26. defined('YII_ENABLE_EXCEPTION_HANDLER') or define('YII_ENABLE_EXCEPTION_HANDLER',true);
  27. defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER',true);
  28. defined('YII_PATH') or define('YII_PATH',dirname(__FILE__));
  29. defined('YII_ZII_PATH') or define('YII_ZII_PATH',YII_PATH.DIRECTORY_SEPARATOR.'zii');
  30. class YiiBase
  31. {
  32. public static $classMap=array();
  33. public static $enableIncludePath=true;
  34. private static $_aliases=array('system'=>YII_PATH,'zii'=>YII_ZII_PATH); // alias => path
  35. private static $_imports=array(); // alias => class name or directory
  36. private static $_includePaths; // list of include paths
  37. private static $_app;
  38. private static $_logger;
  39. public static function getVersion()
  40. {
  41. return '1.1.9';
  42. }
  43. public static function createWebApplication($config=null)
  44. {
  45. return self::createApplication('CWebApplication',$config);
  46. }
  47. public static function createConsoleApplication($config=null)
  48. {
  49. return self::createApplication('CConsoleApplication',$config);
  50. }
  51. public static function createApplication($class,$config=null)
  52. {
  53. return new $class($config);
  54. }
  55. public static function app()
  56. {
  57. return self::$_app;
  58. }
  59. public static function setApplication($app)
  60. {
  61. if(self::$_app===null || $app===null)
  62. self::$_app=$app;
  63. else
  64. throw new CException(Yii::t('yii','Yii application can only be created once.'));
  65. }
  66. public static function getFrameworkPath()
  67. {
  68. return YII_PATH;
  69. }
  70. public static function createComponent($config)
  71. {
  72. if(is_string($config))
  73. {
  74. $type=$config;
  75. $config=array();
  76. }
  77. else if(isset($config['class']))
  78. {
  79. $type=$config['class'];
  80. unset($config['class']);
  81. }
  82. else
  83. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  84. if(!class_exists($type,false))
  85. $type=Yii::import($type,true);
  86. if(($n=func_num_args())>1)
  87. {
  88. $args=func_get_args();
  89. if($n===2)
  90. $object=new $type($args[1]);
  91. else if($n===3)
  92. $object=new $type($args[1],$args[2]);
  93. else if($n===4)
  94. $object=new $type($args[1],$args[2],$args[3]);
  95. else
  96. {
  97. unset($args[0]);
  98. $class=new ReflectionClass($type);
  99. // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
  100. // $object=$class->newInstanceArgs($args);
  101. $object=call_user_func_array(array($class,'newInstance'),$args);
  102. }
  103. }
  104. else
  105. $object=new $type;
  106. foreach($config as $key=>$value)
  107. $object->$key=$value;
  108. return $object;
  109. }
  110. public static function import($alias,$forceInclude=false)
  111. {
  112. if(isset(self::$_imports[$alias])) // previously imported
  113. return self::$_imports[$alias];
  114. if(class_exists($alias,false) || interface_exists($alias,false))
  115. return self::$_imports[$alias]=$alias;
  116. if(($pos=strrpos($alias,'\\'))!==false) // a class name in PHP 5.3 namespace format
  117. {
  118. $namespace=str_replace('\\','.',ltrim(substr($alias,0,$pos),'\\'));
  119. if(($path=self::getPathOfAlias($namespace))!==false)
  120. {
  121. $classFile=$path.DIRECTORY_SEPARATOR.substr($alias,$pos+1).'.php';
  122. if($forceInclude)
  123. {
  124. if(is_file($classFile))
  125. require($classFile);
  126. else
  127. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file.',array('{alias}'=>$alias)));
  128. self::$_imports[$alias]=$alias;
  129. }
  130. else
  131. self::$classMap[$alias]=$classFile;
  132. return $alias;
  133. }
  134. else
  135. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory.',
  136. array('{alias}'=>$namespace)));
  137. }
  138. if(($pos=strrpos($alias,'.'))===false) // a simple class name
  139. {
  140. if($forceInclude && self::autoload($alias))
  141. self::$_imports[$alias]=$alias;
  142. return $alias;
  143. }
  144. $className=(string)substr($alias,$pos+1);
  145. $isClass=$className!=='*';
  146. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  147. return self::$_imports[$alias]=$className;
  148. if(($path=self::getPathOfAlias($alias))!==false)
  149. {
  150. if($isClass)
  151. {
  152. if($forceInclude)
  153. {
  154. if(is_file($path.'.php'))
  155. require($path.'.php');
  156. else
  157. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file.',array('{alias}'=>$alias)));
  158. self::$_imports[$alias]=$className;
  159. }
  160. else
  161. self::$classMap[$className]=$path.'.php';
  162. return $className;
  163. }
  164. else // a directory
  165. {
  166. if(self::$_includePaths===null)
  167. {
  168. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  169. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  170. unset(self::$_includePaths[$pos]);
  171. }
  172. array_unshift(self::$_includePaths,$path);
  173. if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  174. self::$enableIncludePath=false;
  175. return self::$_imports[$alias]=$path;
  176. }
  177. }
  178. else
  179. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  180. array('{alias}'=>$alias)));
  181. }
  182. public static function getPathOfAlias($alias)
  183. {
  184. if(isset(self::$_aliases[$alias]))
  185. return self::$_aliases[$alias];
  186. else if(($pos=strpos($alias,'.'))!==false)
  187. {
  188. $rootAlias=substr($alias,0,$pos);
  189. if(isset(self::$_aliases[$rootAlias]))
  190. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  191. else if(self::$_app instanceof CWebApplication)
  192. {
  193. if(self::$_app->findModule($rootAlias)!==null)
  194. return self::getPathOfAlias($alias);
  195. }
  196. }
  197. return false;
  198. }
  199. public static function setPathOfAlias($alias,$path)
  200. {
  201. if(empty($path))
  202. unset(self::$_aliases[$alias]);
  203. else
  204. self::$_aliases[$alias]=rtrim($path,'\\/');
  205. }
  206. public static function autoload($className)
  207. {
  208. // use include so that the error PHP file may appear
  209. if(isset(self::$classMap[$className]))
  210. include(self::$classMap[$className]);
  211. else if(isset(self::$_coreClasses[$className]))
  212. include(YII_PATH.self::$_coreClasses[$className]);
  213. else
  214. {
  215. // include class file relying on include_path
  216. if(strpos($className,'\\')===false) // class without namespace
  217. {
  218. if(self::$enableIncludePath===false)
  219. {
  220. foreach(self::$_includePaths as $path)
  221. {
  222. $classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
  223. if(is_file($classFile))
  224. {
  225. include($classFile);
  226. break;
  227. }
  228. }
  229. }
  230. else
  231. include($className.'.php');
  232. }
  233. else // class name with namespace in PHP 5.3
  234. {
  235. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  236. if(($path=self::getPathOfAlias($namespace))!==false)
  237. include($path.'.php');
  238. else
  239. return false;
  240. }
  241. return class_exists($className,false) || interface_exists($className,false);
  242. }
  243. return true;
  244. }
  245. public static function trace($msg,$category='application')
  246. {
  247. if(YII_DEBUG)
  248. self::log($msg,CLogger::LEVEL_TRACE,$category);
  249. }
  250. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  251. {
  252. if(self::$_logger===null)
  253. self::$_logger=new CLogger;
  254. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  255. {
  256. $traces=debug_backtrace();
  257. $count=0;
  258. foreach($traces as $trace)
  259. {
  260. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  261. {
  262. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  263. if(++$count>=YII_TRACE_LEVEL)
  264. break;
  265. }
  266. }
  267. }
  268. self::$_logger->log($msg,$level,$category);
  269. }
  270. public static function beginProfile($token,$category='application')
  271. {
  272. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  273. }
  274. public static function endProfile($token,$category='application')
  275. {
  276. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  277. }
  278. public static function getLogger()
  279. {
  280. if(self::$_logger!==null)
  281. return self::$_logger;
  282. else
  283. return self::$_logger=new CLogger;
  284. }
  285. public static function setLogger($logger)
  286. {
  287. self::$_logger=$logger;
  288. }
  289. public static function powered()
  290. {
  291. return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
  292. }
  293. public static function t($category,$message,$params=array(),$source=null,$language=null)
  294. {
  295. if(self::$_app!==null)
  296. {
  297. if($source===null)
  298. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  299. if(($source=self::$_app->getComponent($source))!==null)
  300. $message=$source->translate($category,$message,$language);
  301. }
  302. if($params===array())
  303. return $message;
  304. if(!is_array($params))
  305. $params=array($params);
  306. if(isset($params[0])) // number choice
  307. {
  308. if(strpos($message,'|')!==false)
  309. {
  310. if(strpos($message,'#')===false)
  311. {
  312. $chunks=explode('|',$message);
  313. $expressions=self::$_app->getLocale($language)->getPluralRules();
  314. if($n=min(count($chunks),count($expressions)))
  315. {
  316. for($i=0;$i<$n;$i++)
  317. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  318. $message=implode('|',$chunks);
  319. }
  320. }
  321. $message=CChoiceFormat::format($message,$params[0]);
  322. }
  323. if(!isset($params['{n}']))
  324. $params['{n}']=$params[0];
  325. unset($params[0]);
  326. }
  327. return $params!==array() ? strtr($message,$params) : $message;
  328. }
  329. public static function registerAutoloader($callback, $append=false)
  330. {
  331. if($append)
  332. {
  333. self::$enableIncludePath=false;
  334. spl_autoload_register($callback);
  335. }
  336. else
  337. {
  338. spl_autoload_unregister(array('YiiBase','autoload'));
  339. spl_autoload_register($callback);
  340. spl_autoload_register(array('YiiBase','autoload'));
  341. }
  342. }
  343. private static $_coreClasses=array(
  344. 'CApplication' => '/base/CApplication.php',
  345. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  346. 'CBehavior' => '/base/CBehavior.php',
  347. 'CComponent' => '/base/CComponent.php',
  348. 'CErrorEvent' => '/base/CErrorEvent.php',
  349. 'CErrorHandler' => '/base/CErrorHandler.php',
  350. 'CException' => '/base/CException.php',
  351. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  352. 'CHttpException' => '/base/CHttpException.php',
  353. 'CModel' => '/base/CModel.php',
  354. 'CModelBehavior' => '/base/CModelBehavior.php',
  355. 'CModelEvent' => '/base/CModelEvent.php',
  356. 'CModule' => '/base/CModule.php',
  357. 'CSecurityManager' => '/base/CSecurityManager.php',
  358. 'CStatePersister' => '/base/CStatePersister.php',
  359. 'CApcCache' => '/caching/CApcCache.php',
  360. 'CCache' => '/caching/CCache.php',
  361. 'CDbCache' => '/caching/CDbCache.php',
  362. 'CDummyCache' => '/caching/CDummyCache.php',
  363. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  364. 'CFileCache' => '/caching/CFileCache.php',
  365. 'CMemCache' => '/caching/CMemCache.php',
  366. 'CWinCache' => '/caching/CWinCache.php',
  367. 'CXCache' => '/caching/CXCache.php',
  368. 'CZendDataCache' => '/caching/CZendDataCache.php',
  369. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  370. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  371. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  372. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  373. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  374. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  375. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  376. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  377. 'CConfiguration' => '/collections/CConfiguration.php',
  378. 'CList' => '/collections/CList.php',
  379. 'CListIterator' => '/collections/CListIterator.php',
  380. 'CMap' => '/collections/CMap.php',
  381. 'CMapIterator' => '/collections/CMapIterator.php',
  382. 'CQueue' => '/collections/CQueue.php',
  383. 'CQueueIterator' => '/collections/CQueueIterator.php',
  384. 'CStack' => '/collections/CStack.php',
  385. 'CStackIterator' => '/collections/CStackIterator.php',
  386. 'CTypedList' => '/collections/CTypedList.php',
  387. 'CTypedMap' => '/collections/CTypedMap.php',
  388. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  389. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  390. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  391. 'CHelpCommand' => '/console/CHelpCommand.php',
  392. 'CDbCommand' => '/db/CDbCommand.php',
  393. 'CDbConnection' => '/db/CDbConnection.php',
  394. 'CDbDataReader' => '/db/CDbDataReader.php',
  395. 'CDbException' => '/db/CDbException.php',
  396. 'CDbMigration' => '/db/CDbMigration.php',
  397. 'CDbTransaction' => '/db/CDbTransaction.php',
  398. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  399. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  400. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  401. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  402. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  403. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  404. 'CDbExpression' => '/db/schema/CDbExpression.php',
  405. 'CDbSchema' => '/db/schema/CDbSchema.php',
  406. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  407. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  408. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  409. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  410. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  411. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  412. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  413. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  414. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  415. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  416. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  417. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  418. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  419. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  420. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  421. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  422. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  423. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  424. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  425. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  426. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  427. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  428. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  429. 'CLocale' => '/i18n/CLocale.php',
  430. 'CMessageSource' => '/i18n/CMessageSource.php',
  431. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  432. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  433. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  434. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  435. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  436. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  437. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  438. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  439. 'CLogFilter' => '/logging/CLogFilter.php',
  440. 'CLogRoute' => '/logging/CLogRoute.php',
  441. 'CLogRouter' => '/logging/CLogRouter.php',
  442. 'CLogger' => '/logging/CLogger.php',
  443. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  444. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  445. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  446. 'CFileHelper' => '/utils/CFileHelper.php',
  447. 'CFormatter' => '/utils/CFormatter.php',
  448. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  449. 'CPropertyValue' => '/utils/CPropertyValue.php',
  450. 'CTimestamp' => '/utils/CTimestamp.php',
  451. 'CVarDumper' => '/utils/CVarDumper.php',
  452. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  453. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  454. 'CCompareValidator' => '/validators/CCompareValidator.php',
  455. 'CDateValidator' => '/validators/CDateValidator.php',
  456. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  457. 'CEmailValidator' => '/validators/CEmailValidator.php',
  458. 'CExistValidator' => '/validators/CExistValidator.php',
  459. 'CFileValidator' => '/validators/CFileValidator.php',
  460. 'CFilterValidator' => '/validators/CFilterValidator.php',
  461. 'CInlineValidator' => '/validators/CInlineValidator.php',
  462. 'CNumberValidator' => '/validators/CNumberValidator.php',
  463. 'CRangeValidator' => '/validators/CRangeValidator.php',
  464. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  465. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  466. 'CSafeValidator' => '/validators/CSafeValidator.php',
  467. 'CStringValidator' => '/validators/CStringValidator.php',
  468. 'CTypeValidator' => '/validators/CTypeValidator.php',
  469. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  470. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  471. 'CUrlValidator' => '/validators/CUrlValidator.php',
  472. 'CValidator' => '/validators/CValidator.php',
  473. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  474. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  475. 'CAssetManager' => '/web/CAssetManager.php',
  476. 'CBaseController' => '/web/CBaseController.php',
  477. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  478. 'CClientScript' => '/web/CClientScript.php',
  479. 'CController' => '/web/CController.php',
  480. 'CDataProvider' => '/web/CDataProvider.php',
  481. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  482. 'CExtController' => '/web/CExtController.php',
  483. 'CFormModel' => '/web/CFormModel.php',
  484. 'CHttpCookie' => '/web/CHttpCookie.php',
  485. 'CHttpRequest' => '/web/CHttpRequest.php',
  486. 'CHttpSession' => '/web/CHttpSession.php',
  487. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  488. 'COutputEvent' => '/web/COutputEvent.php',
  489. 'CPagination' => '/web/CPagination.php',
  490. 'CSort' => '/web/CSort.php',
  491. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  492. 'CTheme' => '/web/CTheme.php',
  493. 'CThemeManager' => '/web/CThemeManager.php',
  494. 'CUploadedFile' => '/web/CUploadedFile.php',
  495. 'CUrlManager' => '/web/CUrlManager.php',
  496. 'CWebApplication' => '/web/CWebApplication.php',
  497. 'CWebModule' => '/web/CWebModule.php',
  498. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  499. 'CAction' => '/web/actions/CAction.php',
  500. 'CInlineAction' => '/web/actions/CInlineAction.php',
  501. 'CViewAction' => '/web/actions/CViewAction.php',
  502. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  503. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  504. 'CAuthItem' => '/web/auth/CAuthItem.php',
  505. 'CAuthManager' => '/web/auth/CAuthManager.php',
  506. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  507. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  508. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  509. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  510. 'CWebUser' => '/web/auth/CWebUser.php',
  511. 'CFilter' => '/web/filters/CFilter.php',
  512. 'CFilterChain' => '/web/filters/CFilterChain.php',
  513. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  514. 'CForm' => '/web/form/CForm.php',
  515. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  516. 'CFormElement' => '/web/form/CFormElement.php',
  517. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  518. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  519. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  520. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  521. 'CHtml' => '/web/helpers/CHtml.php',
  522. 'CJSON' => '/web/helpers/CJSON.php',
  523. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  524. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  525. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  526. 'CWebService' => '/web/services/CWebService.php',
  527. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  528. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  529. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  530. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  531. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  532. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  533. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  534. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  535. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  536. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  537. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  538. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  539. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  540. 'COutputCache' => '/web/widgets/COutputCache.php',
  541. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  542. 'CStarRating' => '/web/widgets/CStarRating.php',
  543. 'CTabView' => '/web/widgets/CTabView.php',
  544. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  545. 'CTreeView' => '/web/widgets/CTreeView.php',
  546. 'CWidget' => '/web/widgets/CWidget.php',
  547. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  548. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  549. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  550. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  551. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  552. );
  553. }
  554. spl_autoload_register(array('YiiBase','autoload'));
  555. class Yii extends YiiBase
  556. {
  557. }
  558. class CComponent
  559. {
  560. private $_e;
  561. private $_m;
  562. public function __get($name)
  563. {
  564. $getter='get'.$name;
  565. if(method_exists($this,$getter))
  566. return $this->$getter();
  567. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  568. {
  569. // duplicating getEventHandlers() here for performance
  570. $name=strtolower($name);
  571. if(!isset($this->_e[$name]))
  572. $this->_e[$name]=new CList;
  573. return $this->_e[$name];
  574. }
  575. else if(isset($this->_m[$name]))
  576. return $this->_m[$name];
  577. else if(is_array($this->_m))
  578. {
  579. foreach($this->_m as $object)
  580. {
  581. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  582. return $object->$name;
  583. }
  584. }
  585. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  586. array('{class}'=>get_class($this), '{property}'=>$name)));
  587. }
  588. public function __set($name,$value)
  589. {
  590. $setter='set'.$name;
  591. if(method_exists($this,$setter))
  592. return $this->$setter($value);
  593. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  594. {
  595. // duplicating getEventHandlers() here for performance
  596. $name=strtolower($name);
  597. if(!isset($this->_e[$name]))
  598. $this->_e[$name]=new CList;
  599. return $this->_e[$name]->add($value);
  600. }
  601. else if(is_array($this->_m))
  602. {
  603. foreach($this->_m as $object)
  604. {
  605. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  606. return $object->$name=$value;
  607. }
  608. }
  609. if(method_exists($this,'get'.$name))
  610. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  611. array('{class}'=>get_class($this), '{property}'=>$name)));
  612. else
  613. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  614. array('{class}'=>get_class($this), '{property}'=>$name)));
  615. }
  616. public function __isset($name)
  617. {
  618. $getter='get'.$name;
  619. if(method_exists($this,$getter))
  620. return $this->$getter()!==null;
  621. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  622. {
  623. $name=strtolower($name);
  624. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  625. }
  626. else if(is_array($this->_m))
  627. {
  628. if(isset($this->_m[$name]))
  629. return true;
  630. foreach($this->_m as $object)
  631. {
  632. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  633. return $object->$name!==null;
  634. }
  635. }
  636. return false;
  637. }
  638. public function __unset($name)
  639. {
  640. $setter='set'.$name;
  641. if(method_exists($this,$setter))
  642. $this->$setter(null);
  643. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  644. unset($this->_e[strtolower($name)]);
  645. else if(is_array($this->_m))
  646. {
  647. if(isset($this->_m[$name]))
  648. $this->detachBehavior($name);
  649. else
  650. {
  651. foreach($this->_m as $object)
  652. {
  653. if($object->getEnabled())
  654. {
  655. if(property_exists($object,$name))
  656. return $object->$name=null;
  657. else if($object->canSetProperty($name))
  658. return $object->$setter(null);
  659. }
  660. }
  661. }
  662. }
  663. else if(method_exists($this,'get'.$name))
  664. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  665. array('{class}'=>get_class($this), '{property}'=>$name)));
  666. }
  667. public function __call($name,$parameters)
  668. {
  669. if($this->_m!==null)
  670. {
  671. foreach($this->_m as $object)
  672. {
  673. if($object->getEnabled() && method_exists($object,$name))
  674. return call_user_func_array(array($object,$name),$parameters);
  675. }
  676. }
  677. if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)
  678. return call_user_func_array($this->$name, $parameters);
  679. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  680. array('{class}'=>get_class($this), '{name}'=>$name)));
  681. }
  682. public function asa($behavior)
  683. {
  684. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  685. }
  686. public function attachBehaviors($behaviors)
  687. {
  688. foreach($behaviors as $name=>$behavior)
  689. $this->attachBehavior($name,$behavior);
  690. }
  691. public function detachBehaviors()
  692. {
  693. if($this->_m!==null)
  694. {
  695. foreach($this->_m as $name=>$behavior)
  696. $this->detachBehavior($name);
  697. $this->_m=null;
  698. }
  699. }
  700. public function attachBehavior($name,$behavior)
  701. {
  702. if(!($behavior instanceof IBehavior))
  703. $behavior=Yii::createComponent($behavior);
  704. $behavior->setEnabled(true);
  705. $behavior->attach($this);
  706. return $this->_m[$name]=$behavior;
  707. }
  708. public function detachBehavior($name)
  709. {
  710. if(isset($this->_m[$name]))
  711. {
  712. $this->_m[$name]->detach($this);
  713. $behavior=$this->_m[$name];
  714. unset($this->_m[$name]);
  715. return $behavior;
  716. }
  717. }
  718. public function enableBehaviors()
  719. {
  720. if($this->_m!==null)
  721. {
  722. foreach($this->_m as $behavior)
  723. $behavior->setEnabled(true);
  724. }
  725. }
  726. public function disableBehaviors()
  727. {
  728. if($this->_m!==null)
  729. {
  730. foreach($this->_m as $behavior)
  731. $behavior->setEnabled(false);
  732. }
  733. }
  734. public function enableBehavior($name)
  735. {
  736. if(isset($this->_m[$name]))
  737. $this->_m[$name]->setEnabled(true);
  738. }
  739. public function disableBehavior($name)
  740. {
  741. if(isset($this->_m[$name]))
  742. $this->_m[$name]->setEnabled(false);
  743. }
  744. public function hasProperty($name)
  745. {
  746. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  747. }
  748. public function canGetProperty($name)
  749. {
  750. return method_exists($this,'get'.$name);
  751. }
  752. public function canSetProperty($name)
  753. {
  754. return method_exists($this,'set'.$name);
  755. }
  756. public function hasEvent($name)
  757. {
  758. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  759. }
  760. public function hasEventHandler($name)
  761. {
  762. $name=strtolower($name);
  763. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  764. }
  765. public function getEventHandlers($name)
  766. {
  767. if($this->hasEvent($name))
  768. {
  769. $name=strtolower($name);
  770. if(!isset($this->_e[$name]))
  771. $this->_e[$name]=new CList;
  772. return $this->_e[$name];
  773. }
  774. else
  775. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  776. array('{class}'=>get_class($this), '{event}'=>$name)));
  777. }
  778. public function attachEventHandler($name,$handler)
  779. {
  780. $this->getEventHandlers($name)->add($handler);
  781. }
  782. public function detachEventHandler($name,$handler)
  783. {
  784. if($this->hasEventHandler($name))
  785. return $this->getEventHandlers($name)->remove($handler)!==false;
  786. else
  787. return false;
  788. }
  789. public function raiseEvent($name,$event)
  790. {
  791. $name=strtolower($name);
  792. if(isset($this->_e[$name]))
  793. {
  794. foreach($this->_e[$name] as $handler)
  795. {
  796. if(is_string($handler))
  797. call_user_func($handler,$event);
  798. else if(is_callable($handler,true))
  799. {
  800. if(is_array($handler))
  801. {
  802. // an array: 0 - object, 1 - method name
  803. list($object,$method)=$handler;
  804. if(is_string($object)) // static method call
  805. call_user_func($handler,$event);
  806. else if(method_exists($object,$method))
  807. $object->$method($event);
  808. else
  809. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  810. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  811. }
  812. else // PHP 5.3: anonymous function
  813. call_user_func($handler,$event);
  814. }
  815. else
  816. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  817. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  818. // stop further handling if param.handled is set true
  819. if(($event instanceof CEvent) && $event->handled)
  820. return;
  821. }
  822. }
  823. else if(YII_DEBUG && !$this->hasEvent($name))
  824. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  825. array('{class}'=>get_class($this), '{event}'=>$name)));
  826. }
  827. public function evaluateExpression($_expression_,$_data_=array())
  828. {
  829. if(is_string($_expression_))
  830. {
  831. extract($_data_);
  832. return eval('return '.$_expression_.';');
  833. }
  834. else
  835. {
  836. $_data_[]=$this;
  837. return call_user_func_array($_expression_, $_data_);
  838. }
  839. }
  840. }
  841. class CEvent extends CComponent
  842. {
  843. public $sender;
  844. public $handled=false;
  845. public $params;
  846. public function __construct($sender=null,$params=null)
  847. {
  848. $this->sender=$sender;
  849. $this->params=$params;
  850. }
  851. }
  852. class CEnumerable
  853. {
  854. }
  855. abstract class CModule extends CComponent
  856. {
  857. public $preload=array();
  858. public $behaviors=array();
  859. private $_id;
  860. private $_parentModule;
  861. private $_basePath;
  862. private $_modulePath;
  863. private $_params;
  864. private $_modules=array();
  865. private $_moduleConfig=array();
  866. private $_components=array();
  867. private $_componentConfig=array();
  868. public function __construct($id,$parent,$config=null)
  869. {
  870. $this->_id=$id;
  871. $this->_parentModule=$parent;
  872. // set basePath at early as possible to avoid trouble
  873. if(is_string($config))
  874. $config=require($config);
  875. if(isset($config['basePath']))
  876. {
  877. $this->setBasePath($config['basePath']);
  878. unset($config['basePath']);
  879. }
  880. Yii::setPathOfAlias($id,$this->getBasePath());
  881. $this->preinit();
  882. $this->configure($config);
  883. $this->attachBehaviors($this->behaviors);
  884. $this->preloadComponents();
  885. $this->init();
  886. }
  887. public function __get($name)
  888. {
  889. if($this->hasComponent($name))
  890. return $this->getComponent($name);
  891. else
  892. return parent::__get($name);
  893. }
  894. public function __isset($name)
  895. {
  896. if($this->hasComponent($name))
  897. return $this->getComponent($name)!==null;
  898. else
  899. return parent::__isset($name);
  900. }
  901. public function getId()
  902. {
  903. return $this->_id;
  904. }
  905. public function setId($id)
  906. {
  907. $this->_id=$id;
  908. }
  909. public function getBasePath()
  910. {
  911. if($this->_basePath===null)
  912. {
  913. $class=new ReflectionClass(get_class($this));
  914. $this->_basePath=dirname($class->getFileName());
  915. }
  916. return $this->_basePath;
  917. }
  918. public function setBasePath($path)
  919. {
  920. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  921. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  922. array('{path}'=>$path)));
  923. }
  924. public function getParams()
  925. {
  926. if($this->_params!==null)
  927. return $this->_params;
  928. else
  929. {
  930. $this->_params=new CAttributeCollection;
  931. $this->_params->caseSensitive=true;
  932. return $this->_params;
  933. }
  934. }
  935. public function setParams($value)
  936. {
  937. $params=$this->getParams();
  938. foreach($value as $k=>$v)
  939. $params->add($k,$v);
  940. }
  941. public function getModulePath()
  942. {
  943. if($this->_modulePath!==null)
  944. return $this->_modulePath;
  945. else
  946. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  947. }
  948. public function setModulePath($value)
  949. {
  950. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  951. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  952. array('{path}'=>$value)));
  953. }
  954. public function setImport($aliases)
  955. {
  956. foreach($aliases as $alias)
  957. Yii::import($alias);
  958. }
  959. public function setAliases($mappings)
  960. {
  961. foreach($mappings as $name=>$alias)
  962. {
  963. if(($path=Yii::getPathOfAlias($alias))!==false)
  964. Yii::setPathOfAlias($name,$path);
  965. else
  966. Yii::setPathOfAlias($name,$alias);
  967. }
  968. }
  969. public function getParentModule()
  970. {
  971. return $this->_parentModule;
  972. }
  973. public function getModule($id)
  974. {
  975. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  976. return $this->_modules[$id];
  977. else if(isset($this->_moduleConfig[$id]))
  978. {
  979. $config=$this->_moduleConfig[$id];
  980. if(!isset($config['enabled']) || $config['enabled'])
  981. {
  982. $class=$config['class'];
  983. unset($config['class'], $config['enabled']);
  984. if($this===Yii::app())
  985. $module=Yii::createComponent($class,$id,null,$config);
  986. else
  987. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  988. return $this->_modules[$id]=$module;
  989. }
  990. }
  991. }
  992. public function hasModule($id)
  993. {
  994. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  995. }
  996. public function getModules()
  997. {
  998. return $this->_moduleConfig;
  999. }
  1000. public function setModules($modules)
  1001. {
  1002. foreach($modules as $id=>$module)
  1003. {
  1004. if(is_int($id))
  1005. {
  1006. $id=$module;
  1007. $module=array();
  1008. }
  1009. if(!isset($module['class']))
  1010. {
  1011. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1012. $module['class']=$id.'.'.ucfirst($id).'Module';
  1013. }
  1014. if(isset($this->_moduleConfig[$id]))
  1015. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1016. else
  1017. $this->_moduleConfig[$id]=$module;
  1018. }
  1019. }
  1020. public function hasComponent($id)
  1021. {
  1022. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1023. }
  1024. public function getComponent($id,$createIfNull=true)
  1025. {
  1026. if(isset($this->_components[$id]))
  1027. return $this->_components[$id];
  1028. else if(isset($this->_componentConfig[$id]) && $createIfNull)
  1029. {
  1030. $config=$this->_componentConfig[$id];
  1031. if(!isset($config['enabled']) || $config['enabled'])
  1032. {
  1033. unset($config['enabled']);
  1034. $component=Yii::createComponent($config);
  1035. $component->init();
  1036. return $this->_components[$id]=$component;
  1037. }
  1038. }
  1039. }
  1040. public function setComponent($id,$component)
  1041. {
  1042. if($component===null)
  1043. unset($this->_components[$id]);
  1044. else
  1045. {
  1046. $this->_components[$id]=$component;
  1047. if(!$component->getIsInitialized())
  1048. $component->init();
  1049. }
  1050. }
  1051. public function getComponents($loadedOnly=true)
  1052. {
  1053. if($loadedOnly)
  1054. return $this->_components;
  1055. else
  1056. return array_merge($this->_componentConfig, $this->_components);
  1057. }
  1058. public function setComponents($components,$merge=true)
  1059. {
  1060. foreach($components as $id=>$component)
  1061. {
  1062. if($component instanceof IApplicationComponent)
  1063. $this->setComponent($id,$component);
  1064. else if(isset($this->_componentConfig[$id]) && $merge)
  1065. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1066. else
  1067. $this->_componentConfig[$id]=$component;
  1068. }
  1069. }
  1070. public function configure($config)
  1071. {
  1072. if(is_array($config))
  1073. {
  1074. foreach($config as $key=>$value)
  1075. $this->$key=$value;
  1076. }
  1077. }
  1078. protected function preloadComponents()
  1079. {
  1080. foreach($this->preload as $id)
  1081. $this->getComponent($id);
  1082. }
  1083. protected function preinit()
  1084. {
  1085. }
  1086. protected function init()
  1087. {
  1088. }
  1089. }
  1090. abstract class CApplication extends CModule
  1091. {
  1092. public $name='My Application';
  1093. public $charset='UTF-8';
  1094. public $sourceLanguage='en_us';
  1095. private $_id;
  1096. private $_basePath;
  1097. private $_runtimePath;
  1098. private $_extensionPath;
  1099. private $_globalState;
  1100. private $_stateChanged;
  1101. private $_ended=false;
  1102. private $_language;
  1103. private $_homeUrl;
  1104. abstract public function processRequest();
  1105. public function __construct($config=null)
  1106. {
  1107. Yii::setApplication($this);
  1108. // set basePath at early as possible to avoid trouble
  1109. if(is_string($config))
  1110. $config=require($config);
  1111. if(isset($config['basePath']))
  1112. {
  1113. $this->setBasePath($config['basePath']);
  1114. unset($config['basePath']);
  1115. }
  1116. else
  1117. $this->setBasePath('protected');
  1118. Yii::setPathOfAlias('application',$this->getBasePath());
  1119. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1120. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1121. $this->preinit();
  1122. $this->initSystemHandlers();
  1123. $this->registerCoreComponents();
  1124. $this->configure($config);
  1125. $this->attachBehaviors($this->behaviors);
  1126. $this->preloadComponents();
  1127. $this->init();
  1128. }
  1129. public function run()
  1130. {
  1131. if($this->hasEventHandler('onBeginRequest'))
  1132. $this->onBeginRequest(new CEvent($this));
  1133. $this->processRequest();
  1134. if($this->hasEventHandler('onEndRequest'))
  1135. $this->onEndRequest(new CEvent($this));
  1136. }
  1137. public function end($status=0, $exit=true)
  1138. {
  1139. if($this->hasEventHandler('onEndRequest'))
  1140. $this->onEndRequest(new CEvent($this));
  1141. if($exit)
  1142. exit($status);
  1143. }
  1144. public function onBeginRequest($event)
  1145. {
  1146. $this->raiseEvent('onBeginRequest',$event);
  1147. }
  1148. public function onEndRequest($event)
  1149. {
  1150. if(!$this->_ended)
  1151. {
  1152. $this->_ended=true;
  1153. $this->raiseEvent('onEndRequest',$event);
  1154. }
  1155. }
  1156. public function getId()
  1157. {
  1158. if($this->_id!==null)
  1159. return $this->_id;
  1160. else
  1161. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1162. }
  1163. public function setId($id)
  1164. {
  1165. $this->_id=$id;
  1166. }
  1167. public function getBasePath()
  1168. {
  1169. return $this->_basePath;
  1170. }
  1171. public function setBasePath($path)
  1172. {
  1173. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1174. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1175. array('{path}'=>$path)));
  1176. }
  1177. public function getRuntimePath()
  1178. {
  1179. if($this->_runtimePath!==null)
  1180. return $this->_runtimePath;
  1181. else
  1182. {
  1183. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1184. return $this->_runtimePath;
  1185. }
  1186. }
  1187. public function setRuntimePath($path)
  1188. {
  1189. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1190. throw new CException(Yii::t('yii','Application runtime path "{path}" is not valid. Please make sure it is a directory writable by the Web server process.',
  1191. array('{path}'=>$path)));
  1192. $this->_runtimePath=$runtimePath;
  1193. }
  1194. public function getExtensionPath()
  1195. {
  1196. return Yii::getPathOfAlias('ext');
  1197. }
  1198. public function setExtensionPath($path)
  1199. {
  1200. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1201. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1202. array('{path}'=>$path)));
  1203. Yii::setPathOfAlias('ext',$extensionPath);
  1204. }
  1205. public function getLanguage()
  1206. {
  1207. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1208. }
  1209. public function setLanguage($language)
  1210. {
  1211. $this->_language=$language;
  1212. }
  1213. public function getTimeZone()
  1214. {
  1215. return date_default_timezone_get();
  1216. }
  1217. public function setTimeZone($value)
  1218. {
  1219. date_default_timezone_set($value);
  1220. }
  1221. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1222. {
  1223. if($srcLanguage===null)
  1224. $srcLanguage=$this->sourceLanguage;
  1225. if($language===null)
  1226. $language=$this->getLanguage();
  1227. if($language===$srcLanguage)
  1228. return $srcFile;
  1229. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1230. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1231. }
  1232. public function getLocale($localeID=null)
  1233. {
  1234. return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID);
  1235. }
  1236. public function getLocaleDataPath()
  1237. {
  1238. return CLocale::$dataPath===null ? Yii::getPathOfAlias('system.i18n.data') : CLocale::$dataPath;
  1239. }
  1240. public function setLocaleDataPath($value)
  1241. {
  1242. CLocale::$dataPath=$value;
  1243. }
  1244. public function getNumberFormatter()
  1245. {
  1246. return $this->getLocale()->getNumberFormatter();
  1247. }
  1248. public function getDateFormatter()
  1249. {
  1250. return $this->getLocale()->getDateFormatter();
  1251. }
  1252. public function getDb()
  1253. {
  1254. return $this->getComponent('db');
  1255. }
  1256. public function getErrorHandler()
  1257. {
  1258. return $this->getComponent('errorHandler');
  1259. }
  1260. public function getSecurityManager()
  1261. {
  1262. return $this->getComponent('securityManager');
  1263. }
  1264. public function getStatePersister()
  1265. {
  1266. return $this->getComponent('statePersister');
  1267. }
  1268. public function getCache()
  1269. {
  1270. return $this->getComponent('cache');
  1271. }
  1272. public function getCoreMessages()
  1273. {
  1274. return $this->getComponent('coreMessages');
  1275. }
  1276. public function getMessages()
  1277. {
  1278. return $this->getComponent('messages');
  1279. }
  1280. public function getRequest()
  1281. {
  1282. return $this->getComponent('request');
  1283. }
  1284. public function getUrlManager()
  1285. {
  1286. return $this->getComponent('urlManager');
  1287. }
  1288. public function getController()
  1289. {
  1290. return null;
  1291. }
  1292. public function createUrl($route,$params=array(),$ampersand='&')
  1293. {
  1294. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1295. }
  1296. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1297. {
  1298. $url=$this->createUrl($route,$params,$ampersand);
  1299. if(strpos($url,'http')===0)
  1300. return $url;
  1301. else
  1302. return $this->getRequest()->getHostInfo($schema).$url;
  1303. }
  1304. public function getBaseUrl($absolute=false)
  1305. {
  1306. return $this->getRequest()->getBaseUrl($absolute);
  1307. }
  1308. public function getHomeUrl()
  1309. {
  1310. if($this->_homeUrl===null)
  1311. {
  1312. if($this->getUrlManager()->showScriptName)
  1313. return $this->getRequest()->getScriptUrl();
  1314. else
  1315. return $this->getRequest()->getBaseUrl().'/';
  1316. }
  1317. else
  1318. return $this->_homeUrl;
  1319. }
  1320. public function setHomeUrl($value)
  1321. {
  1322. $this->_homeUrl=$value;
  1323. }
  1324. public function getGlobalState($key,$defaultValue=null)
  1325. {
  1326. if($this->_globalState===null)
  1327. $this->loadGlobalState();
  1328. if(isset($this->_globalState[$key]))
  1329. return $this->_globalState[$key];
  1330. else
  1331. return $defaultValue;
  1332. }
  1333. public function setGlobalState($key,$value,$defaultValue=null)
  1334. {
  1335. if($this->_globalState===null)
  1336. $this->loadGlobalState();
  1337. $changed=$this->_stateChanged;
  1338. if($value===$defaultValue)
  1339. {
  1340. if(isset($this->_globalState[$key]))
  1341. {
  1342. unset($this->_globalState[$key]);
  1343. $this->_stateChanged=true;
  1344. }
  1345. }
  1346. else if(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1347. {
  1348. $this->_globalState[$key]=$value;
  1349. $this->_stateChanged=true;
  1350. }
  1351. if($this->_stateChanged!==$changed)
  1352. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1353. }
  1354. public function clearGlobalState($key)
  1355. {
  1356. $this->setGlobalState($key,true,true);
  1357. }
  1358. public function loadGlobalState()
  1359. {
  1360. $persister=$this->getStatePersister();
  1361. if(($this->_globalState=$persister->load())===null)
  1362. $this->_globalState=array();
  1363. $this->_stateChanged=false;
  1364. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1365. }
  1366. public function saveGlobalState()
  1367. {
  1368. if($this->_stateChanged)
  1369. {
  1370. $this->_stateChanged=false;
  1371. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1372. $this->getStatePersister()->save($this->_globalState);
  1373. }
  1374. }
  1375. public function handleException($exception)
  1376. {
  1377. // disable error capturing to avoid recursive errors
  1378. restore_error_handler();
  1379. restore_exception_handler();
  1380. $category='exception.'.get_class($exception);
  1381. if($exception instanceof CHttpException)
  1382. $category.='.'.$exception->statusCode;
  1383. // php <5.2 doesn't support string conversion auto-magically
  1384. $message=$exception->__toString();
  1385. if(isset($_SERVER['REQUEST_URI']))
  1386. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  1387. if(isset($_SERVER['HTTP_REFERER']))
  1388. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  1389. $message.="\n---";
  1390. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1391. try
  1392. {
  1393. $event=new CExceptionEvent($this,$exception);
  1394. $this->onException($event);
  1395. if(!$event->handled)
  1396. {
  1397. // try an error handler
  1398. if(($handler=$this->getErrorHandler())!==null)
  1399. $handler->handle($event);
  1400. else
  1401. $this->displayException($exception);
  1402. }
  1403. }
  1404. catch(Exception $e)
  1405. {
  1406. $this->displayException($e);
  1407. }
  1408. try
  1409. {
  1410. $this->end(1);
  1411. }
  1412. catch(Exception $e)
  1413. {
  1414. // use the most primitive way to log error
  1415. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1416. $msg .= $e->getTraceAsString()."\n";
  1417. $msg .= "Previous exception:\n";
  1418. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1419. $msg .= $exception->getTraceAsString()."\n";
  1420. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1421. error_log($msg);
  1422. exit(1);
  1423. }
  1424. }
  1425. public function handleError($code,$message,$file,$line)
  1426. {
  1427. if($code & error_reporting())
  1428. {
  1429. // disable error capturing to avoid recursive errors
  1430. restore_error_handler();
  1431. restore_exception_handler();
  1432. $log="$message ($file:$line)\nStack trace:\n";
  1433. $trace=debug_backtrace();
  1434. // skip the first 3 stacks as they do not tell the error position
  1435. if(count($trace)>3)
  1436. $trace=array_slice($trace,3);
  1437. foreach($trace as $i=>$t)
  1438. {
  1439. if(!isset($t['file']))
  1440. $t['file']='unknown';
  1441. if(!isset($t['line']))
  1442. $t['line']=0;
  1443. if(!isset($t['function']))
  1444. $t['function']='unknown';
  1445. $log.="#$i {$t['file']}({$t['line']}): ";
  1446. if(isset($t['object']) && is_object($t['object']))
  1447. $log.=get_class($t['object']).'->';
  1448. $log.="{$t['function']}()\n";
  1449. }
  1450. if(isset($_SERVER['REQUEST_URI']))
  1451. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1452. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1453. try
  1454. {
  1455. Yii::import('CErrorEvent',true);
  1456. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1457. $this->onError($event);
  1458. if(!$event->handled)
  1459. {
  1460. // try an error handler
  1461. if(($handler=$this->getErrorHandler())!==null)
  1462. $handler->handle($event);
  1463. else
  1464. $this->displayError($code,$message,$file,$line);
  1465. }
  1466. }
  1467. catch(Exception $e)
  1468. {
  1469. $this->displayException($e);
  1470. }
  1471. try
  1472. {
  1473. $this->end(1);
  1474. }
  1475. catch(Exception $e)
  1476. {
  1477. // use the most primitive way to log error
  1478. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1479. $msg .= $e->getTraceAsString()."\n";
  1480. $msg .= "Previous error:\n";
  1481. $msg .= $log."\n";
  1482. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1483. error_log($msg);
  1484. exit(1);
  1485. }
  1486. }
  1487. }
  1488. public function onException($event)
  1489. {
  1490. $this->raiseEvent('onException',$event);
  1491. }
  1492. public function onError($event)
  1493. {
  1494. $this->raiseEvent('onError',$event);
  1495. }
  1496. public function displayError($code,$message,$file,$line)
  1497. {
  1498. if(YII_DEBUG)
  1499. {
  1500. echo "<h1>PHP Error [$code]</h1>\n";
  1501. echo "<p>$message ($file:$line)</p>\n";
  1502. echo '<pre>';
  1503. $trace=debug_backtrace();
  1504. // skip the first 3 stacks as they do not tell the error position
  1505. if(count($trace)>3)
  1506. $trace=array_slice($trace,3);
  1507. foreach($trace as $i=>$t)
  1508. {
  1509. if(!isset($t['file']))
  1510. $t['file']='unknown';
  1511. if(!isset($t['line']))
  1512. $t['line']=0;
  1513. if(!isset($t['function']))
  1514. $t['function']='unknown';
  1515. echo "#$i {$t['file']}({$t['line']}): ";
  1516. if(isset($t['object']) && is_object($t['object']))
  1517. echo get_class($t['object']).'->';
  1518. echo "{$t['function']}()\n";
  1519. }
  1520. echo '</pre>';
  1521. }
  1522. else
  1523. {
  1524. echo "<h1>PHP Error [$code]</h1>\n";
  1525. echo "<p>$message</p>\n";
  1526. }
  1527. }
  1528. public function displayException($exception)
  1529. {
  1530. if(YII_DEBUG)
  1531. {
  1532. echo '<h1>'.get_class($exception)."</h1>\n";
  1533. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1534. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1535. }
  1536. else
  1537. {
  1538. echo '<h1>'.get_class($exception)."</h1>\n";
  1539. echo '<p>'.$exception->getMessage().'</p>';
  1540. }
  1541. }
  1542. protected function initSystemHandlers()
  1543. {
  1544. if(YII_ENABLE_EXCEPTION_HANDLER)
  1545. set_exception_handler(array($this,'handleException'));
  1546. if(YII_ENABLE_ERROR_HANDLER)
  1547. set_error_handler(array($this,'handleError'),error_reporting());
  1548. }
  1549. protected function registerCoreComponents()
  1550. {
  1551. $components=array(
  1552. 'coreMessages'=>array(
  1553. 'class'=>'CPhpMessageSource',
  1554. 'language'=>'en_us',
  1555. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1556. ),
  1557. 'db'=>array(
  1558. 'class'=>'CDbConnection',
  1559. ),
  1560. 'messages'=>array(
  1561. 'class'=>'CPhpMessageSource',
  1562. ),
  1563. 'errorHandler'=>array(
  1564. 'class'=>'CErrorHandler',
  1565. ),
  1566. 'securityManager'=>array(
  1567. 'class'=>'CSecurityManager',
  1568. ),
  1569. 'statePersister'=>array(
  1570. 'class'=>'CStatePersister',
  1571. ),
  1572. 'urlManager'=>array(
  1573. 'class'=>'CUrlManager',
  1574. ),
  1575. 'request'=>array(
  1576. 'class'=>'CHttpRequest',
  1577. ),
  1578. 'format'=>array(
  1579. 'class'=>'CFormatter',
  1580. ),
  1581. );
  1582. $this->setComponents($components);
  1583. }
  1584. }
  1585. class CWebApplication extends CApplication
  1586. {
  1587. public $defaultController='site';
  1588. public $layout='main';
  1589. public $controllerMap=array();
  1590. public $catchAllRequest;
  1591. private $_controllerPath;
  1592. private $_viewPath;
  1593. private $_systemViewPath;
  1594. private $_layoutPath;
  1595. private $_controller;
  1596. private $_theme;
  1597. public function processRequest()
  1598. {
  1599. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1600. {
  1601. $route=$this->catchAllRequest[0];
  1602. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1603. $_GET[$name]=$value;
  1604. }
  1605. else
  1606. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1607. $this->runController($route);
  1608. }
  1609. protected function registerCoreComponents()
  1610. {
  1611. parent::registerCoreComponents();
  1612. $components=array(
  1613. 'session'=>array(
  1614. 'class'=>'CHttpSession',
  1615. ),
  1616. 'assetManager'=>array(
  1617. 'class'=>'CAssetManager',
  1618. ),
  1619. 'user'=>array(
  1620. 'class'=>'CWebUser',
  1621. ),
  1622. 'themeManager'=>array(
  1623. 'class'=>'CThemeManager',
  1624. ),
  1625. 'authManager'=>array(
  1626. 'class'=>'CPhpAuthManager',
  1627. ),
  1628. 'clientScript'=>array(
  1629. 'class'=>'CClientScript',
  1630. ),
  1631. 'widgetFactory'=>array(
  1632. 'class'=>'CWidgetFactory',
  1633. ),
  1634. );
  1635. $this->setComponents($components);
  1636. }
  1637. public function getAuthManager()
  1638. {
  1639. return $this->getComponent('authManager');
  1640. }
  1641. public function getAssetManager()
  1642. {
  1643. return $this->getComponent('assetManager');
  1644. }
  1645. public function getSession()
  1646. {
  1647. return $this->getComponent('session');
  1648. }
  1649. public function getUser()
  1650. {
  1651. return $this->getComponent('user');
  1652. }
  1653. public function getViewRenderer()
  1654. {
  1655. return $this->getComponent('viewRenderer');
  1656. }
  1657. public function getClientScript()
  1658. {
  1659. return $this->getComponent('clientScript');
  1660. }
  1661. public function getWidgetFactory()
  1662. {
  1663. return $this->getComponent('widgetFactory');
  1664. }
  1665. public function getThemeManager()
  1666. {
  1667. return $this->getComponent('themeManager');
  1668. }
  1669. public function getTheme()
  1670. {
  1671. if(is_string($this->_theme))
  1672. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1673. return $this->_theme;
  1674. }
  1675. public function setTheme($value)
  1676. {
  1677. $this->_theme=$value;
  1678. }
  1679. public function runController($route)
  1680. {
  1681. if(($ca=$this->createController($route))!==null)
  1682. {
  1683. list($controller,$actionID)=$ca;
  1684. $oldController=$this->_controller;
  1685. $this->_controller=$controller;
  1686. $controller->init();
  1687. $controller->run($actionID);
  1688. $this->_controller=$oldController;
  1689. }
  1690. else
  1691. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1692. array('{route}'=>$route===''?$this->defaultController:$route)));
  1693. }
  1694. public function createController($route,$owner=null)
  1695. {
  1696. if($owner===null)
  1697. $owner=$this;
  1698. if(($route=trim($route,'/'))==='')
  1699. $route=$owner->defaultController;
  1700. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1701. $route.='/';
  1702. while(($pos=strpos($route,'/'))!==false)
  1703. {
  1704. $id=substr($route,0,$pos);
  1705. if(!preg_match('/^\w+$/',$id))
  1706. return null;
  1707. if(!$caseSensitive)
  1708. $id=strtolower($id);
  1709. $route=(string)substr($route,$pos+1);
  1710. if(!isset($basePath)) // first segment
  1711. {
  1712. if(isset($owner->controllerMap[$id]))
  1713. {
  1714. return array(
  1715. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1716. $this->parseActionParams($route),
  1717. );
  1718. }
  1719. if(($module=$owner->getModule($id))!==null)
  1720. return $this->createController($route,$module);
  1721. $basePath=$owner->getControllerPath();
  1722. $controllerID='';
  1723. }
  1724. else
  1725. $controllerID.='/';
  1726. $className=ucfirst($id).'Controller';
  1727. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1728. if(is_file($classFile))
  1729. {
  1730. if(!class_exists($className,false))
  1731. require($classFile);
  1732. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1733. {
  1734. $id[0]=strtolower($id[0]);
  1735. return array(
  1736. new $className($controllerID.$id,$owner===$this?null:$owner),
  1737. $this->parseActionParams($route),
  1738. );
  1739. }
  1740. return null;
  1741. }
  1742. $controllerID.=$id;
  1743. $basePath.=DIRECTORY_SEPARATOR.$id;
  1744. }
  1745. }
  1746. protected function parseActionParams($pathInfo)
  1747. {
  1748. if(($pos=strpos($pathInfo,'/'))!==false)
  1749. {
  1750. $manager=$this->getUrlManager();
  1751. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1752. $actionID=substr($pathInfo,0,$pos);
  1753. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1754. }
  1755. else
  1756. return $pathInfo;
  1757. }
  1758. public function getController()
  1759. {
  1760. return $this->_controller;
  1761. }
  1762. public function setController($value)
  1763. {
  1764. $this->_controller=$value;
  1765. }
  1766. public function getControllerPath()
  1767. {
  1768. if($this->_controllerPath!==null)
  1769. return $this->_controllerPath;
  1770. else
  1771. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1772. }
  1773. public function setControllerPath($value)
  1774. {
  1775. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1776. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1777. array('{path}'=>$value)));
  1778. }
  1779. public function getViewPath()
  1780. {
  1781. if($this->_viewPath!==null)
  1782. return $this->_viewPath;
  1783. else
  1784. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1785. }
  1786. public function setViewPath($path)
  1787. {
  1788. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1789. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1790. array('{path}'=>$path)));
  1791. }
  1792. public function getSystemViewPath()
  1793. {
  1794. if($this->_systemViewPath!==null)
  1795. return $this->_systemViewPath;
  1796. else
  1797. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1798. }
  1799. public function setSystemViewPath($path)
  1800. {
  1801. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1802. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1803. array('{path}'=>$path)));
  1804. }
  1805. public function getLayoutPath()
  1806. {
  1807. if($this->_layoutPath!==null)
  1808. return $this->_layoutPath;
  1809. else
  1810. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1811. }
  1812. public function setLayoutPath($path)
  1813. {
  1814. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1815. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1816. array('{path}'=>$path)));
  1817. }
  1818. public function beforeControllerAction($controller,$action)
  1819. {
  1820. return true;
  1821. }
  1822. public function afterControllerAction($controller,$action)
  1823. {
  1824. }
  1825. public function findModule($id)
  1826. {
  1827. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1828. {
  1829. do
  1830. {
  1831. if(($m=$module->getModule($id))!==null)
  1832. return $m;
  1833. } while(($module=$module->getParentModule())!==null);
  1834. }
  1835. if(($m=$this->getModule($id))!==null)
  1836. return $m;
  1837. }
  1838. protected function init()
  1839. {
  1840. parent::init();
  1841. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1842. $this->getRequest();
  1843. }
  1844. }
  1845. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1846. {
  1847. private $_d=array();
  1848. private $_r=false;
  1849. public function __construct($data=null,$readOnly=false)
  1850. {
  1851. if($data!==null)
  1852. $this->copyFrom($data);
  1853. $this->setReadOnly($readOnly);
  1854. }
  1855. public function getReadOnly()
  1856. {
  1857. return $this->_r;
  1858. }
  1859. protected function setReadOnly($value)
  1860. {
  1861. $this->_r=$value;
  1862. }
  1863. public function getIterator()
  1864. {
  1865. return new CMapIterator($this->_d);
  1866. }
  1867. public function count()
  1868. {
  1869. return $this->getCount();
  1870. }
  1871. public function getCount()
  1872. {
  1873. return count($this->_d);
  1874. }
  1875. public function getKeys()
  1876. {
  1877. return array_keys($this->_d);
  1878. }
  1879. public function itemAt($key)
  1880. {
  1881. if(isset($this->_d[$key]))
  1882. return $this->_d[$key];
  1883. else
  1884. return null;
  1885. }
  1886. public function add($key,$value)
  1887. {
  1888. if(!$this->_r)
  1889. {
  1890. if($key===null)
  1891. $this->_d[]=$value;
  1892. else
  1893. $this->_d[$key]=$value;
  1894. }
  1895. else
  1896. throw new CException(Yii::t('yii','The map is read only.'));
  1897. }
  1898. public function remove($key)
  1899. {
  1900. if(!$this->_r)
  1901. {
  1902. if(isset($this->_d[$key]))
  1903. {
  1904. $value=$this->_d[$key];
  1905. unset($this->_d[$key]);
  1906. return $value;
  1907. }
  1908. else
  1909. {
  1910. // it is possible the value is null, which is not detected by isset
  1911. unset($this->_d[$key]);
  1912. return null;
  1913. }
  1914. }
  1915. else
  1916. throw new CException(Yii::t('yii','The map is read only.'));
  1917. }
  1918. public function clear()
  1919. {
  1920. foreach(array_keys($this->_d) as $key)
  1921. $this->remove($key);
  1922. }
  1923. public function contains($key)
  1924. {
  1925. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  1926. }
  1927. public function toArray()
  1928. {
  1929. return $this->_d;
  1930. }
  1931. public function copyFrom($data)
  1932. {
  1933. if(is_array($data) || $data instanceof Traversable)
  1934. {
  1935. if($this->getCount()>0)
  1936. $this->clear();
  1937. if($data instanceof CMap)
  1938. $data=$data->_d;
  1939. foreach($data as $key=>$value)
  1940. $this->add($key,$value);
  1941. }
  1942. else if($data!==null)
  1943. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1944. }
  1945. public function mergeWith($data,$recursive=true)
  1946. {
  1947. if(is_array($data) || $data instanceof Traversable)
  1948. {
  1949. if($data instanceof CMap)
  1950. $data=$data->_d;
  1951. if($recursive)
  1952. {
  1953. if($data instanceof Traversable)
  1954. {
  1955. $d=array();
  1956. foreach($data as $key=>$value)
  1957. $d[$key]=$value;
  1958. $this->_d=self::mergeArray($this->_d,$d);
  1959. }
  1960. else
  1961. $this->_d=self::mergeArray($this->_d,$data);
  1962. }
  1963. else
  1964. {
  1965. foreach($data as $key=>$value)
  1966. $this->add($key,$value);
  1967. }
  1968. }
  1969. else if($data!==null)
  1970. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1971. }
  1972. public static function mergeArray($a,$b)
  1973. {
  1974. $args=func_get_args();
  1975. $res=array_shift($args);
  1976. while(!empty($args))
  1977. {
  1978. $next=array_shift($args);
  1979. foreach($next as $k => $v)
  1980. {
  1981. if(is_integer($k))
  1982. isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
  1983. else if(is_array($v) && isset($res[$k]) && is_array($res[$k]))
  1984. $res[$k]=self::mergeArray($res[$k],$v);
  1985. else
  1986. $res[$k]=$v;
  1987. }
  1988. }
  1989. return $res;
  1990. }
  1991. public function offsetExists($offset)
  1992. {
  1993. return $this->contains($offset);
  1994. }
  1995. public function offsetGet($offset)
  1996. {
  1997. return $this->itemAt($offset);
  1998. }
  1999. public function offsetSet($offset,$item)
  2000. {
  2001. $this->add($offset,$item);
  2002. }
  2003. public function offsetUnset($offset)
  2004. {
  2005. $this->remove($offset);
  2006. }
  2007. }
  2008. class CLogger extends CComponent
  2009. {
  2010. const LEVEL_TRACE='trace';
  2011. const LEVEL_WARNING='warning';
  2012. const LEVEL_ERROR='error';
  2013. const LEVEL_INFO='info';
  2014. const LEVEL_PROFILE='profile';
  2015. public $autoFlush=10000;
  2016. public $autoDump=false;
  2017. private $_logs=array();
  2018. private $_logCount=0;
  2019. private $_levels;
  2020. private $_categories;
  2021. private $_timings;
  2022. private $_processing = false;
  2023. public function log($message,$level='info',$category='application')
  2024. {
  2025. $this->_logs[]=array($message,$level,$category,microtime(true));
  2026. $this->_logCount++;
  2027. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
  2028. {
  2029. $this->_processing=true;
  2030. $this->flush($this->autoDump);
  2031. $this->_processing=false;
  2032. }
  2033. }
  2034. public function getLogs($levels='',$categories='')
  2035. {
  2036. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2037. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2038. if(empty($levels) && empty($categories))
  2039. return $this->_logs;
  2040. else if(empty($levels))
  2041. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByCategory'))));
  2042. else if(empty($categories))
  2043. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  2044. else
  2045. {
  2046. $ret=array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  2047. return array_values(array_filter(array_filter($ret,array($this,'filterByCategory'))));
  2048. }
  2049. }
  2050. private function filterByCategory($value)
  2051. {
  2052. foreach($this->_categories as $category)
  2053. {
  2054. $cat=strtolower($value[2]);
  2055. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2056. return $value;
  2057. }
  2058. return false;
  2059. }
  2060. private function filterByLevel($value)
  2061. {
  2062. return in_array(strtolower($value[1]),$this->_levels)?$value:false;
  2063. }
  2064. public function getExecutionTime()
  2065. {
  2066. return microtime(true)-YII_BEGIN_TIME;
  2067. }
  2068. public function getMemoryUsage()
  2069. {
  2070. if(function_exists('memory_get_usage'))
  2071. return memory_get_usage();
  2072. else
  2073. {
  2074. $output=array();
  2075. if(strncmp(PHP_OS,'WIN',3)===0)
  2076. {
  2077. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2078. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2079. }
  2080. else
  2081. {
  2082. $pid=getmypid();
  2083. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2084. $output=explode(" ",$output[0]);
  2085. return isset($output[1]) ? $output[1]*1024 : 0;
  2086. }
  2087. }
  2088. }
  2089. public function getProfilingResults($token=null,$category=null,$refresh=false)
  2090. {
  2091. if($this->_timings===null || $refresh)
  2092. $this->calculateTimings();
  2093. if($token===null && $category===null)
  2094. return $this->_timings;
  2095. $results=array();
  2096. foreach($this->_timings as $timing)
  2097. {
  2098. if(($category===null || $timing[1]===$category) && ($token===null || $timing[0]===$token))
  2099. $results[]=$timing[2];
  2100. }
  2101. return $results;
  2102. }
  2103. private function calculateTimings()
  2104. {
  2105. $this->_timings=array();
  2106. $stack=array();
  2107. foreach($this->_logs as $log)
  2108. {
  2109. if($log[1]!==CLogger::LEVEL_PROFILE)
  2110. continue;
  2111. list($message,$level,$category,$timestamp)=$log;
  2112. if(!strncasecmp($message,'begin:',6))
  2113. {
  2114. $log[0]=substr($message,6);
  2115. $stack[]=$log;
  2116. }
  2117. else if(!strncasecmp($message,'end:',4))
  2118. {
  2119. $token=substr($message,4);
  2120. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2121. {
  2122. $delta=$log[3]-$last[3];
  2123. $this->_timings[]=array($message,$category,$delta);
  2124. }
  2125. else
  2126. 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.',
  2127. array('{token}'=>$token)));
  2128. }
  2129. }
  2130. $now=microtime(true);
  2131. while(($last=array_pop($stack))!==null)
  2132. {
  2133. $delta=$now-$last[3];
  2134. $this->_timings[]=array($last[0],$last[2],$delta);
  2135. }
  2136. }
  2137. public function flush($dumpLogs=false)
  2138. {
  2139. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2140. $this->_logs=array();
  2141. $this->_logCount=0;
  2142. }
  2143. public function onFlush($event)
  2144. {
  2145. $this->raiseEvent('onFlush', $event);
  2146. }
  2147. }
  2148. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2149. {
  2150. public $behaviors=array();
  2151. private $_initialized=false;
  2152. public function init()
  2153. {
  2154. $this->attachBehaviors($this->behaviors);
  2155. $this->_initialized=true;
  2156. }
  2157. public function getIsInitialized()
  2158. {
  2159. return $this->_initialized;
  2160. }
  2161. }
  2162. class CHttpRequest extends CApplicationComponent
  2163. {
  2164. public $enableCookieValidation=false;
  2165. public $enableCsrfValidation=false;
  2166. public $csrfTokenName='YII_CSRF_TOKEN';
  2167. public $csrfCookie;
  2168. private $_requestUri;
  2169. private $_pathInfo;
  2170. private $_scriptFile;
  2171. private $_scriptUrl;
  2172. private $_hostInfo;
  2173. private $_baseUrl;
  2174. private $_cookies;
  2175. private $_preferredLanguage;
  2176. private $_csrfToken;
  2177. private $_deleteParams;
  2178. private $_putParams;
  2179. public function init()
  2180. {
  2181. parent::init();
  2182. $this->normalizeRequest();
  2183. }
  2184. protected function normalizeRequest()
  2185. {
  2186. // normalize request
  2187. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2188. {
  2189. if(isset($_GET))
  2190. $_GET=$this->stripSlashes($_GET);
  2191. if(isset($_POST))
  2192. $_POST=$this->stripSlashes($_POST);
  2193. if(isset($_REQUEST))
  2194. $_REQUEST=$this->stripSlashes($_REQUEST);
  2195. if(isset($_COOKIE))
  2196. $_COOKIE=$this->stripSlashes($_COOKIE);
  2197. }
  2198. if($this->enableCsrfValidation)
  2199. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2200. }
  2201. public function stripSlashes(&$data)
  2202. {
  2203. return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
  2204. }
  2205. public function getParam($name,$defaultValue=null)
  2206. {
  2207. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2208. }
  2209. public function getQuery($name,$defaultValue=null)
  2210. {
  2211. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2212. }
  2213. public function getPost($name,$defaultValue=null)
  2214. {
  2215. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2216. }
  2217. public function getDelete($name,$defaultValue=null)
  2218. {
  2219. if($this->_deleteParams===null)
  2220. $this->_deleteParams=$this->getIsDeleteRequest() ? $this->getRestParams() : array();
  2221. return isset($this->_deleteParams[$name]) ? $this->_deleteParams[$name] : $defaultValue;
  2222. }
  2223. public function getPut($name,$defaultValue=null)
  2224. {
  2225. if($this->_putParams===null)
  2226. $this->_putParams=$this->getIsPutRequest() ? $this->getRestParams() : array();
  2227. return isset($this->_putParams[$name]) ? $this->_putParams[$name] : $defaultValue;
  2228. }
  2229. protected function getRestParams()
  2230. {
  2231. $result=array();
  2232. if(function_exists('mb_parse_str'))
  2233. mb_parse_str(file_get_contents('php://input'), $result);
  2234. else
  2235. parse_str(file_get_contents('php://input'), $result);
  2236. return $result;
  2237. }
  2238. public function getUrl()
  2239. {
  2240. return $this->getRequestUri();
  2241. }
  2242. public function getHostInfo($schema='')
  2243. {
  2244. if($this->_hostInfo===null)
  2245. {
  2246. if($secure=$this->getIsSecureConnection())
  2247. $http='https';
  2248. else
  2249. $http='http';
  2250. if(isset($_SERVER['HTTP_HOST']))
  2251. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2252. else
  2253. {
  2254. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2255. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2256. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2257. $this->_hostInfo.=':'.$port;
  2258. }
  2259. }
  2260. if($schema!=='')
  2261. {
  2262. $secure=$this->getIsSecureConnection();
  2263. if($secure && $schema==='https' || !$secure && $schema==='http')
  2264. return $this->_hostInfo;
  2265. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2266. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2267. $port=':'.$port;
  2268. else
  2269. $port='';
  2270. $pos=strpos($this->_hostInfo,':');
  2271. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2272. }
  2273. else
  2274. return $this->_hostInfo;
  2275. }
  2276. public function setHostInfo($value)
  2277. {
  2278. $this->_hostInfo=rtrim($value,'/');
  2279. }
  2280. public function getBaseUrl($absolute=false)
  2281. {
  2282. if($this->_baseUrl===null)
  2283. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2284. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2285. }
  2286. public function setBaseUrl($value)
  2287. {
  2288. $this->_baseUrl=$value;
  2289. }
  2290. public function getScriptUrl()
  2291. {
  2292. if($this->_scriptUrl===null)
  2293. {
  2294. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2295. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2296. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2297. else if(basename($_SERVER['PHP_SELF'])===$scriptName)
  2298. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2299. else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2300. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2301. else if(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2302. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2303. else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2304. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2305. else
  2306. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2307. }
  2308. return $this->_scriptUrl;
  2309. }
  2310. public function setScriptUrl($value)
  2311. {
  2312. $this->_scriptUrl='/'.trim($value,'/');
  2313. }
  2314. public function getPathInfo()
  2315. {
  2316. if($this->_pathInfo===null)
  2317. {
  2318. $pathInfo=$this->getRequestUri();
  2319. if(($pos=strpos($pathInfo,'?'))!==false)
  2320. $pathInfo=substr($pathInfo,0,$pos);
  2321. $pathInfo=$this->urldecode($pathInfo);
  2322. $scriptUrl=$this->getScriptUrl();
  2323. $baseUrl=$this->getBaseUrl();
  2324. if(strpos($pathInfo,$scriptUrl)===0)
  2325. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2326. else if($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2327. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2328. else if(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2329. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2330. else
  2331. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2332. $this->_pathInfo=trim($pathInfo,'/');
  2333. }
  2334. return $this->_pathInfo;
  2335. }
  2336. private function urldecode($str)
  2337. {
  2338. $str = urldecode($str);
  2339. // is it UTF-8?
  2340. // http://w3.org/International/questions/qa-forms-utf-8.html
  2341. if(preg_match('%^(?:
  2342. [\x09\x0A\x0D\x20-\x7E] # ASCII
  2343. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  2344. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  2345. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  2346. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  2347. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  2348. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  2349. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  2350. )*$%xs', $str))
  2351. {
  2352. return $str;
  2353. }
  2354. else
  2355. {
  2356. return utf8_encode($str);
  2357. }
  2358. }
  2359. public function getRequestUri()
  2360. {
  2361. if($this->_requestUri===null)
  2362. {
  2363. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2364. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2365. else if(isset($_SERVER['REQUEST_URI']))
  2366. {
  2367. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2368. if(!empty($_SERVER['HTTP_HOST']))
  2369. {
  2370. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2371. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2372. }
  2373. else
  2374. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2375. }
  2376. else if(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2377. {
  2378. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2379. if(!empty($_SERVER['QUERY_STRING']))
  2380. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2381. }
  2382. else
  2383. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2384. }
  2385. return $this->_requestUri;
  2386. }
  2387. public function getQueryString()
  2388. {
  2389. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2390. }
  2391. public function getIsSecureConnection()
  2392. {
  2393. return isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'],'on');
  2394. }
  2395. public function getRequestType()
  2396. {
  2397. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2398. }
  2399. public function getIsPostRequest()
  2400. {
  2401. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2402. }
  2403. public function getIsDeleteRequest()
  2404. {
  2405. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE');
  2406. }
  2407. public function getIsPutRequest()
  2408. {
  2409. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT');
  2410. }
  2411. public function getIsAjaxRequest()
  2412. {
  2413. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2414. }
  2415. public function getServerName()
  2416. {
  2417. return $_SERVER['SERVER_NAME'];
  2418. }
  2419. public function getServerPort()
  2420. {
  2421. return $_SERVER['SERVER_PORT'];
  2422. }
  2423. public function getUrlReferrer()
  2424. {
  2425. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2426. }
  2427. public function getUserAgent()
  2428. {
  2429. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2430. }
  2431. public function getUserHostAddress()
  2432. {
  2433. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2434. }
  2435. public function getUserHost()
  2436. {
  2437. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2438. }
  2439. public function getScriptFile()
  2440. {
  2441. if($this->_scriptFile!==null)
  2442. return $this->_scriptFile;
  2443. else
  2444. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2445. }
  2446. public function getBrowser($userAgent=null)
  2447. {
  2448. return get_browser($userAgent,true);
  2449. }
  2450. public function getAcceptTypes()
  2451. {
  2452. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2453. }
  2454. private $_port;
  2455. public function getPort()
  2456. {
  2457. if($this->_port===null)
  2458. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2459. return $this->_port;
  2460. }
  2461. public function setPort($value)
  2462. {
  2463. $this->_port=(int)$value;
  2464. $this->_hostInfo=null;
  2465. }
  2466. private $_securePort;
  2467. public function getSecurePort()
  2468. {
  2469. if($this->_securePort===null)
  2470. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2471. return $this->_securePort;
  2472. }
  2473. public function setSecurePort($value)
  2474. {
  2475. $this->_securePort=(int)$value;
  2476. $this->_hostInfo=null;
  2477. }
  2478. public function getCookies()
  2479. {
  2480. if($this->_cookies!==null)
  2481. return $this->_cookies;
  2482. else
  2483. return $this->_cookies=new CCookieCollection($this);
  2484. }
  2485. public function redirect($url,$terminate=true,$statusCode=302)
  2486. {
  2487. if(strpos($url,'/')===0)
  2488. $url=$this->getHostInfo().$url;
  2489. header('Location: '.$url, true, $statusCode);
  2490. if($terminate)
  2491. Yii::app()->end();
  2492. }
  2493. public function getPreferredLanguage()
  2494. {
  2495. if($this->_preferredLanguage===null)
  2496. {
  2497. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && ($n=preg_match_all('/([\w\-_]+)\s*(;\s*q\s*=\s*(\d*\.\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))>0)
  2498. {
  2499. $languages=array();
  2500. for($i=0;$i<$n;++$i)
  2501. $languages[$matches[1][$i]]=empty($matches[3][$i]) ? 1.0 : floatval($matches[3][$i]);
  2502. arsort($languages);
  2503. foreach($languages as $language=>$pref)
  2504. return $this->_preferredLanguage=CLocale::getCanonicalID($language);
  2505. }
  2506. return $this->_preferredLanguage=false;
  2507. }
  2508. return $this->_preferredLanguage;
  2509. }
  2510. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2511. {
  2512. if($mimeType===null)
  2513. {
  2514. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2515. $mimeType='text/plain';
  2516. }
  2517. header('Pragma: public');
  2518. header('Expires: 0');
  2519. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2520. header("Content-type: $mimeType");
  2521. if(ob_get_length()===false)
  2522. header('Content-Length: '.(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content)));
  2523. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2524. header('Content-Transfer-Encoding: binary');
  2525. if($terminate)
  2526. {
  2527. // clean up the application first because the file downloading could take long time
  2528. // which may cause timeout of some resources (such as DB connection)
  2529. Yii::app()->end(0,false);
  2530. echo $content;
  2531. exit(0);
  2532. }
  2533. else
  2534. echo $content;
  2535. }
  2536. public function xSendFile($filePath, $options=array())
  2537. {
  2538. if(!is_file($filePath))
  2539. return false;
  2540. if(!isset($options['forceDownload']) || $options['forceDownload'])
  2541. $disposition='attachment';
  2542. else
  2543. $disposition='inline';
  2544. if(!isset($options['saveName']))
  2545. $options['saveName']=basename($filePath);
  2546. if(!isset($options['mimeType']))
  2547. {
  2548. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2549. $options['mimeType']='text/plain';
  2550. }
  2551. if(!isset($options['xHeader']))
  2552. $options['xHeader']='X-Sendfile';
  2553. header('Content-type: '.$options['mimeType']);
  2554. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  2555. header(trim($options['xHeader']).': '.$filePath);
  2556. if(!isset($options['terminate']) || $options['terminate'])
  2557. Yii::app()->end();
  2558. return true;
  2559. }
  2560. public function getCsrfToken()
  2561. {
  2562. if($this->_csrfToken===null)
  2563. {
  2564. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2565. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2566. {
  2567. $cookie=$this->createCsrfCookie();
  2568. $this->_csrfToken=$cookie->value;
  2569. $this->getCookies()->add($cookie->name,$cookie);
  2570. }
  2571. }
  2572. return $this->_csrfToken;
  2573. }
  2574. protected function createCsrfCookie()
  2575. {
  2576. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2577. if(is_array($this->csrfCookie))
  2578. {
  2579. foreach($this->csrfCookie as $name=>$value)
  2580. $cookie->$name=$value;
  2581. }
  2582. return $cookie;
  2583. }
  2584. public function validateCsrfToken($event)
  2585. {
  2586. if($this->getIsPostRequest())
  2587. {
  2588. // only validate POST requests
  2589. $cookies=$this->getCookies();
  2590. if($cookies->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName]))
  2591. {
  2592. $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value;
  2593. $tokenFromPost=$_POST[$this->csrfTokenName];
  2594. $valid=$tokenFromCookie===$tokenFromPost;
  2595. }
  2596. else
  2597. $valid=false;
  2598. if(!$valid)
  2599. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2600. }
  2601. }
  2602. }
  2603. class CCookieCollection extends CMap
  2604. {
  2605. private $_request;
  2606. private $_initialized=false;
  2607. public function __construct(CHttpRequest $request)
  2608. {
  2609. $this->_request=$request;
  2610. $this->copyfrom($this->getCookies());
  2611. $this->_initialized=true;
  2612. }
  2613. public function getRequest()
  2614. {
  2615. return $this->_request;
  2616. }
  2617. protected function getCookies()
  2618. {
  2619. $cookies=array();
  2620. if($this->_request->enableCookieValidation)
  2621. {
  2622. $sm=Yii::app()->getSecurityManager();
  2623. foreach($_COOKIE as $name=>$value)
  2624. {
  2625. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  2626. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  2627. }
  2628. }
  2629. else
  2630. {
  2631. foreach($_COOKIE as $name=>$value)
  2632. $cookies[$name]=new CHttpCookie($name,$value);
  2633. }
  2634. return $cookies;
  2635. }
  2636. public function add($name,$cookie)
  2637. {
  2638. if($cookie instanceof CHttpCookie)
  2639. {
  2640. $this->remove($name);
  2641. parent::add($name,$cookie);
  2642. if($this->_initialized)
  2643. $this->addCookie($cookie);
  2644. }
  2645. else
  2646. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  2647. }
  2648. public function remove($name)
  2649. {
  2650. if(($cookie=parent::remove($name))!==null)
  2651. {
  2652. if($this->_initialized)
  2653. $this->removeCookie($cookie);
  2654. }
  2655. return $cookie;
  2656. }
  2657. protected function addCookie($cookie)
  2658. {
  2659. $value=$cookie->value;
  2660. if($this->_request->enableCookieValidation)
  2661. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  2662. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2663. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2664. else
  2665. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  2666. }
  2667. protected function removeCookie($cookie)
  2668. {
  2669. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2670. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2671. else
  2672. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure);
  2673. }
  2674. }
  2675. class CUrlManager extends CApplicationComponent
  2676. {
  2677. const CACHE_KEY='Yii.CUrlManager.rules';
  2678. const GET_FORMAT='get';
  2679. const PATH_FORMAT='path';
  2680. public $rules=array();
  2681. public $urlSuffix='';
  2682. public $showScriptName=true;
  2683. public $appendParams=true;
  2684. public $routeVar='r';
  2685. public $caseSensitive=true;
  2686. public $matchValue=false;
  2687. public $cacheID='cache';
  2688. public $useStrictParsing=false;
  2689. public $urlRuleClass='CUrlRule';
  2690. private $_urlFormat=self::GET_FORMAT;
  2691. private $_rules=array();
  2692. private $_baseUrl;
  2693. public function init()
  2694. {
  2695. parent::init();
  2696. $this->processRules();
  2697. }
  2698. protected function processRules()
  2699. {
  2700. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  2701. return;
  2702. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  2703. {
  2704. $hash=md5(serialize($this->rules));
  2705. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  2706. {
  2707. $this->_rules=$data[0];
  2708. return;
  2709. }
  2710. }
  2711. foreach($this->rules as $pattern=>$route)
  2712. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2713. if(isset($cache))
  2714. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  2715. }
  2716. public function addRules($rules, $append=true)
  2717. {
  2718. if ($append)
  2719. {
  2720. foreach($rules as $pattern=>$route)
  2721. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2722. }
  2723. else
  2724. {
  2725. foreach($rules as $pattern=>$route)
  2726. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  2727. }
  2728. }
  2729. protected function createUrlRule($route,$pattern)
  2730. {
  2731. if(is_array($route) && isset($route['class']))
  2732. return $route;
  2733. else
  2734. return new $this->urlRuleClass($route,$pattern);
  2735. }
  2736. public function createUrl($route,$params=array(),$ampersand='&')
  2737. {
  2738. unset($params[$this->routeVar]);
  2739. foreach($params as $i=>$param)
  2740. if($param===null)
  2741. $params[$i]='';
  2742. if(isset($params['#']))
  2743. {
  2744. $anchor='#'.$params['#'];
  2745. unset($params['#']);
  2746. }
  2747. else
  2748. $anchor='';
  2749. $route=trim($route,'/');
  2750. foreach($this->_rules as $i=>$rule)
  2751. {
  2752. if(is_array($rule))
  2753. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2754. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  2755. {
  2756. if($rule->hasHostInfo)
  2757. return $url==='' ? '/'.$anchor : $url.$anchor;
  2758. else
  2759. return $this->getBaseUrl().'/'.$url.$anchor;
  2760. }
  2761. }
  2762. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  2763. }
  2764. protected function createUrlDefault($route,$params,$ampersand)
  2765. {
  2766. if($this->getUrlFormat()===self::PATH_FORMAT)
  2767. {
  2768. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  2769. if($this->appendParams)
  2770. {
  2771. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  2772. return $route==='' ? $url : $url.$this->urlSuffix;
  2773. }
  2774. else
  2775. {
  2776. if($route!=='')
  2777. $url.=$this->urlSuffix;
  2778. $query=$this->createPathInfo($params,'=',$ampersand);
  2779. return $query==='' ? $url : $url.'?'.$query;
  2780. }
  2781. }
  2782. else
  2783. {
  2784. $url=$this->getBaseUrl();
  2785. if(!$this->showScriptName)
  2786. $url.='/';
  2787. if($route!=='')
  2788. {
  2789. $url.='?'.$this->routeVar.'='.$route;
  2790. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2791. $url.=$ampersand.$query;
  2792. }
  2793. else if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2794. $url.='?'.$query;
  2795. return $url;
  2796. }
  2797. }
  2798. public function parseUrl($request)
  2799. {
  2800. if($this->getUrlFormat()===self::PATH_FORMAT)
  2801. {
  2802. $rawPathInfo=$request->getPathInfo();
  2803. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  2804. foreach($this->_rules as $i=>$rule)
  2805. {
  2806. if(is_array($rule))
  2807. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2808. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  2809. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  2810. }
  2811. if($this->useStrictParsing)
  2812. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  2813. array('{route}'=>$pathInfo)));
  2814. else
  2815. return $pathInfo;
  2816. }
  2817. else if(isset($_GET[$this->routeVar]))
  2818. return $_GET[$this->routeVar];
  2819. else if(isset($_POST[$this->routeVar]))
  2820. return $_POST[$this->routeVar];
  2821. else
  2822. return '';
  2823. }
  2824. public function parsePathInfo($pathInfo)
  2825. {
  2826. if($pathInfo==='')
  2827. return;
  2828. $segs=explode('/',$pathInfo.'/');
  2829. $n=count($segs);
  2830. for($i=0;$i<$n-1;$i+=2)
  2831. {
  2832. $key=$segs[$i];
  2833. if($key==='') continue;
  2834. $value=$segs[$i+1];
  2835. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  2836. {
  2837. $name=substr($key,0,$pos);
  2838. for($j=$m-1;$j>=0;--$j)
  2839. {
  2840. if($matches[1][$j]==='')
  2841. $value=array($value);
  2842. else
  2843. $value=array($matches[1][$j]=>$value);
  2844. }
  2845. if(isset($_GET[$name]) && is_array($_GET[$name]))
  2846. $value=CMap::mergeArray($_GET[$name],$value);
  2847. $_REQUEST[$name]=$_GET[$name]=$value;
  2848. }
  2849. else
  2850. $_REQUEST[$key]=$_GET[$key]=$value;
  2851. }
  2852. }
  2853. public function createPathInfo($params,$equal,$ampersand, $key=null)
  2854. {
  2855. $pairs = array();
  2856. foreach($params as $k => $v)
  2857. {
  2858. if ($key!==null)
  2859. $k = $key.'['.$k.']';
  2860. if (is_array($v))
  2861. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  2862. else
  2863. $pairs[]=urlencode($k).$equal.urlencode($v);
  2864. }
  2865. return implode($ampersand,$pairs);
  2866. }
  2867. public function removeUrlSuffix($pathInfo,$urlSuffix)
  2868. {
  2869. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  2870. return substr($pathInfo,0,-strlen($urlSuffix));
  2871. else
  2872. return $pathInfo;
  2873. }
  2874. public function getBaseUrl()
  2875. {
  2876. if($this->_baseUrl!==null)
  2877. return $this->_baseUrl;
  2878. else
  2879. {
  2880. if($this->showScriptName)
  2881. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  2882. else
  2883. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  2884. return $this->_baseUrl;
  2885. }
  2886. }
  2887. public function setBaseUrl($value)
  2888. {
  2889. $this->_baseUrl=$value;
  2890. }
  2891. public function getUrlFormat()
  2892. {
  2893. return $this->_urlFormat;
  2894. }
  2895. public function setUrlFormat($value)
  2896. {
  2897. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  2898. $this->_urlFormat=$value;
  2899. else
  2900. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  2901. }
  2902. }
  2903. abstract class CBaseUrlRule extends CComponent
  2904. {
  2905. public $hasHostInfo=false;
  2906. abstract public function createUrl($manager,$route,$params,$ampersand);
  2907. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  2908. }
  2909. class CUrlRule extends CBaseUrlRule
  2910. {
  2911. public $urlSuffix;
  2912. public $caseSensitive;
  2913. public $defaultParams=array();
  2914. public $matchValue;
  2915. public $verb;
  2916. public $parsingOnly=false;
  2917. public $route;
  2918. public $references=array();
  2919. public $routePattern;
  2920. public $pattern;
  2921. public $template;
  2922. public $params=array();
  2923. public $append;
  2924. public $hasHostInfo;
  2925. public function __construct($route,$pattern)
  2926. {
  2927. if(is_array($route))
  2928. {
  2929. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  2930. {
  2931. if(isset($route[$name]))
  2932. $this->$name=$route[$name];
  2933. }
  2934. if(isset($route['pattern']))
  2935. $pattern=$route['pattern'];
  2936. $route=$route[0];
  2937. }
  2938. $this->route=trim($route,'/');
  2939. $tr2['/']=$tr['/']='\\/';
  2940. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  2941. {
  2942. foreach($matches2[1] as $name)
  2943. $this->references[$name]="<$name>";
  2944. }
  2945. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  2946. if($this->verb!==null)
  2947. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  2948. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  2949. {
  2950. $tokens=array_combine($matches[1],$matches[2]);
  2951. foreach($tokens as $name=>$value)
  2952. {
  2953. if($value==='')
  2954. $value='[^\/]+';
  2955. $tr["<$name>"]="(?P<$name>$value)";
  2956. if(isset($this->references[$name]))
  2957. $tr2["<$name>"]=$tr["<$name>"];
  2958. else
  2959. $this->params[$name]=$value;
  2960. }
  2961. }
  2962. $p=rtrim($pattern,'*');
  2963. $this->append=$p!==$pattern;
  2964. $p=trim($p,'/');
  2965. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  2966. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  2967. if($this->append)
  2968. $this->pattern.='/u';
  2969. else
  2970. $this->pattern.='$/u';
  2971. if($this->references!==array())
  2972. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  2973. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  2974. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  2975. array('{route}'=>$route,'{pattern}'=>$pattern)));
  2976. }
  2977. public function createUrl($manager,$route,$params,$ampersand)
  2978. {
  2979. if($this->parsingOnly)
  2980. return false;
  2981. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  2982. $case='';
  2983. else
  2984. $case='i';
  2985. $tr=array();
  2986. if($route!==$this->route)
  2987. {
  2988. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  2989. {
  2990. foreach($this->references as $key=>$name)
  2991. $tr[$name]=$matches[$key];
  2992. }
  2993. else
  2994. return false;
  2995. }
  2996. foreach($this->defaultParams as $key=>$value)
  2997. {
  2998. if(isset($params[$key]))
  2999. {
  3000. if($params[$key]==$value)
  3001. unset($params[$key]);
  3002. else
  3003. return false;
  3004. }
  3005. }
  3006. foreach($this->params as $key=>$value)
  3007. if(!isset($params[$key]))
  3008. return false;
  3009. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  3010. {
  3011. foreach($this->params as $key=>$value)
  3012. {
  3013. if(!preg_match('/'.$value.'/'.$case,$params[$key]))
  3014. return false;
  3015. }
  3016. }
  3017. foreach($this->params as $key=>$value)
  3018. {
  3019. $tr["<$key>"]=urlencode($params[$key]);
  3020. unset($params[$key]);
  3021. }
  3022. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3023. $url=strtr($this->template,$tr);
  3024. if($this->hasHostInfo)
  3025. {
  3026. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  3027. if(stripos($url,$hostInfo)===0)
  3028. $url=substr($url,strlen($hostInfo));
  3029. }
  3030. if(empty($params))
  3031. return $url!=='' ? $url.$suffix : $url;
  3032. if($this->append)
  3033. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  3034. else
  3035. {
  3036. if($url!=='')
  3037. $url.=$suffix;
  3038. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  3039. }
  3040. return $url;
  3041. }
  3042. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  3043. {
  3044. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  3045. return false;
  3046. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3047. $case='';
  3048. else
  3049. $case='i';
  3050. if($this->urlSuffix!==null)
  3051. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3052. // URL suffix required, but not found in the requested URL
  3053. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3054. {
  3055. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3056. if($urlSuffix!='' && $urlSuffix!=='/')
  3057. return false;
  3058. }
  3059. if($this->hasHostInfo)
  3060. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3061. $pathInfo.='/';
  3062. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3063. {
  3064. foreach($this->defaultParams as $name=>$value)
  3065. {
  3066. if(!isset($_GET[$name]))
  3067. $_REQUEST[$name]=$_GET[$name]=$value;
  3068. }
  3069. $tr=array();
  3070. foreach($matches as $key=>$value)
  3071. {
  3072. if(isset($this->references[$key]))
  3073. $tr[$this->references[$key]]=$value;
  3074. else if(isset($this->params[$key]))
  3075. $_REQUEST[$key]=$_GET[$key]=$value;
  3076. }
  3077. if($pathInfo!==$matches[0]) // there're additional GET params
  3078. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3079. if($this->routePattern!==null)
  3080. return strtr($this->route,$tr);
  3081. else
  3082. return $this->route;
  3083. }
  3084. else
  3085. return false;
  3086. }
  3087. }
  3088. abstract class CBaseController extends CComponent
  3089. {
  3090. private $_widgetStack=array();
  3091. abstract public function getViewFile($viewName);
  3092. public function renderFile($viewFile,$data=null,$return=false)
  3093. {
  3094. $widgetCount=count($this->_widgetStack);
  3095. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3096. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3097. else
  3098. $content=$this->renderInternal($viewFile,$data,$return);
  3099. if(count($this->_widgetStack)===$widgetCount)
  3100. return $content;
  3101. else
  3102. {
  3103. $widget=end($this->_widgetStack);
  3104. 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.',
  3105. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3106. }
  3107. }
  3108. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3109. {
  3110. // we use special variable names here to avoid conflict when extracting data
  3111. if(is_array($_data_))
  3112. extract($_data_,EXTR_PREFIX_SAME,'data');
  3113. else
  3114. $data=$_data_;
  3115. if($_return_)
  3116. {
  3117. ob_start();
  3118. ob_implicit_flush(false);
  3119. require($_viewFile_);
  3120. return ob_get_clean();
  3121. }
  3122. else
  3123. require($_viewFile_);
  3124. }
  3125. public function createWidget($className,$properties=array())
  3126. {
  3127. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3128. $widget->init();
  3129. return $widget;
  3130. }
  3131. public function widget($className,$properties=array(),$captureOutput=false)
  3132. {
  3133. if($captureOutput)
  3134. {
  3135. ob_start();
  3136. ob_implicit_flush(false);
  3137. $widget=$this->createWidget($className,$properties);
  3138. $widget->run();
  3139. return ob_get_clean();
  3140. }
  3141. else
  3142. {
  3143. $widget=$this->createWidget($className,$properties);
  3144. $widget->run();
  3145. return $widget;
  3146. }
  3147. }
  3148. public function beginWidget($className,$properties=array())
  3149. {
  3150. $widget=$this->createWidget($className,$properties);
  3151. $this->_widgetStack[]=$widget;
  3152. return $widget;
  3153. }
  3154. public function endWidget($id='')
  3155. {
  3156. if(($widget=array_pop($this->_widgetStack))!==null)
  3157. {
  3158. $widget->run();
  3159. return $widget;
  3160. }
  3161. else
  3162. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3163. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3164. }
  3165. public function beginClip($id,$properties=array())
  3166. {
  3167. $properties['id']=$id;
  3168. $this->beginWidget('CClipWidget',$properties);
  3169. }
  3170. public function endClip()
  3171. {
  3172. $this->endWidget('CClipWidget');
  3173. }
  3174. public function beginCache($id,$properties=array())
  3175. {
  3176. $properties['id']=$id;
  3177. $cache=$this->beginWidget('COutputCache',$properties);
  3178. if($cache->getIsContentCached())
  3179. {
  3180. $this->endCache();
  3181. return false;
  3182. }
  3183. else
  3184. return true;
  3185. }
  3186. public function endCache()
  3187. {
  3188. $this->endWidget('COutputCache');
  3189. }
  3190. public function beginContent($view=null,$data=array())
  3191. {
  3192. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3193. }
  3194. public function endContent()
  3195. {
  3196. $this->endWidget('CContentDecorator');
  3197. }
  3198. }
  3199. class CController extends CBaseController
  3200. {
  3201. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3202. public $layout;
  3203. public $defaultAction='index';
  3204. private $_id;
  3205. private $_action;
  3206. private $_pageTitle;
  3207. private $_cachingStack;
  3208. private $_clips;
  3209. private $_dynamicOutput;
  3210. private $_pageStates;
  3211. private $_module;
  3212. public function __construct($id,$module=null)
  3213. {
  3214. $this->_id=$id;
  3215. $this->_module=$module;
  3216. $this->attachBehaviors($this->behaviors());
  3217. }
  3218. public function init()
  3219. {
  3220. }
  3221. public function filters()
  3222. {
  3223. return array();
  3224. }
  3225. public function actions()
  3226. {
  3227. return array();
  3228. }
  3229. public function behaviors()
  3230. {
  3231. return array();
  3232. }
  3233. public function accessRules()
  3234. {
  3235. return array();
  3236. }
  3237. public function run($actionID)
  3238. {
  3239. if(($action=$this->createAction($actionID))!==null)
  3240. {
  3241. if(($parent=$this->getModule())===null)
  3242. $parent=Yii::app();
  3243. if($parent->beforeControllerAction($this,$action))
  3244. {
  3245. $this->runActionWithFilters($action,$this->filters());
  3246. $parent->afterControllerAction($this,$action);
  3247. }
  3248. }
  3249. else
  3250. $this->missingAction($actionID);
  3251. }
  3252. public function runActionWithFilters($action,$filters)
  3253. {
  3254. if(empty($filters))
  3255. $this->runAction($action);
  3256. else
  3257. {
  3258. $priorAction=$this->_action;
  3259. $this->_action=$action;
  3260. CFilterChain::create($this,$action,$filters)->run();
  3261. $this->_action=$priorAction;
  3262. }
  3263. }
  3264. public function runAction($action)
  3265. {
  3266. $priorAction=$this->_action;
  3267. $this->_action=$action;
  3268. if($this->beforeAction($action))
  3269. {
  3270. if($action->runWithParams($this->getActionParams())===false)
  3271. $this->invalidActionParams($action);
  3272. else
  3273. $this->afterAction($action);
  3274. }
  3275. $this->_action=$priorAction;
  3276. }
  3277. public function getActionParams()
  3278. {
  3279. return $_GET;
  3280. }
  3281. public function invalidActionParams($action)
  3282. {
  3283. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3284. }
  3285. public function processOutput($output)
  3286. {
  3287. Yii::app()->getClientScript()->render($output);
  3288. // if using page caching, we should delay dynamic output replacement
  3289. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3290. {
  3291. $output=$this->processDynamicOutput($output);
  3292. $this->_dynamicOutput=null;
  3293. }
  3294. if($this->_pageStates===null)
  3295. $this->_pageStates=$this->loadPageStates();
  3296. if(!empty($this->_pageStates))
  3297. $this->savePageStates($this->_pageStates,$output);
  3298. return $output;
  3299. }
  3300. public function processDynamicOutput($output)
  3301. {
  3302. if($this->_dynamicOutput)
  3303. {
  3304. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3305. }
  3306. return $output;
  3307. }
  3308. protected function replaceDynamicOutput($matches)
  3309. {
  3310. $content=$matches[0];
  3311. if(isset($this->_dynamicOutput[$matches[1]]))
  3312. {
  3313. $content=$this->_dynamicOutput[$matches[1]];
  3314. $this->_dynamicOutput[$matches[1]]=null;
  3315. }
  3316. return $content;
  3317. }
  3318. public function createAction($actionID)
  3319. {
  3320. if($actionID==='')
  3321. $actionID=$this->defaultAction;
  3322. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3323. return new CInlineAction($this,$actionID);
  3324. else
  3325. {
  3326. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3327. if($action!==null && !method_exists($action,'run'))
  3328. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3329. return $action;
  3330. }
  3331. }
  3332. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3333. {
  3334. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3335. {
  3336. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3337. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3338. }
  3339. else if($pos===false)
  3340. return null;
  3341. // the action is defined in a provider
  3342. $prefix=substr($actionID,0,$pos+1);
  3343. if(!isset($actionMap[$prefix]))
  3344. return null;
  3345. $actionID=(string)substr($actionID,$pos+1);
  3346. $provider=$actionMap[$prefix];
  3347. if(is_string($provider))
  3348. $providerType=$provider;
  3349. else if(is_array($provider) && isset($provider['class']))
  3350. {
  3351. $providerType=$provider['class'];
  3352. if(isset($provider[$actionID]))
  3353. {
  3354. if(is_string($provider[$actionID]))
  3355. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3356. else
  3357. $config=array_merge($provider[$actionID],$config);
  3358. }
  3359. }
  3360. else
  3361. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3362. $class=Yii::import($providerType,true);
  3363. $map=call_user_func(array($class,'actions'));
  3364. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3365. }
  3366. public function missingAction($actionID)
  3367. {
  3368. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3369. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3370. }
  3371. public function getAction()
  3372. {
  3373. return $this->_action;
  3374. }
  3375. public function setAction($value)
  3376. {
  3377. $this->_action=$value;
  3378. }
  3379. public function getId()
  3380. {
  3381. return $this->_id;
  3382. }
  3383. public function getUniqueId()
  3384. {
  3385. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3386. }
  3387. public function getRoute()
  3388. {
  3389. if(($action=$this->getAction())!==null)
  3390. return $this->getUniqueId().'/'.$action->getId();
  3391. else
  3392. return $this->getUniqueId();
  3393. }
  3394. public function getModule()
  3395. {
  3396. return $this->_module;
  3397. }
  3398. public function getViewPath()
  3399. {
  3400. if(($module=$this->getModule())===null)
  3401. $module=Yii::app();
  3402. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3403. }
  3404. public function getViewFile($viewName)
  3405. {
  3406. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3407. return $viewFile;
  3408. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3409. if(($module=$this->getModule())!==null)
  3410. $moduleViewPath=$module->getViewPath();
  3411. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3412. }
  3413. public function getLayoutFile($layoutName)
  3414. {
  3415. if($layoutName===false)
  3416. return false;
  3417. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3418. return $layoutFile;
  3419. if(empty($layoutName))
  3420. {
  3421. $module=$this->getModule();
  3422. while($module!==null)
  3423. {
  3424. if($module->layout===false)
  3425. return false;
  3426. if(!empty($module->layout))
  3427. break;
  3428. $module=$module->getParentModule();
  3429. }
  3430. if($module===null)
  3431. $module=Yii::app();
  3432. $layoutName=$module->layout;
  3433. }
  3434. else if(($module=$this->getModule())===null)
  3435. $module=Yii::app();
  3436. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3437. }
  3438. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3439. {
  3440. if(empty($viewName))
  3441. return false;
  3442. if($moduleViewPath===null)
  3443. $moduleViewPath=$basePath;
  3444. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3445. $extension=$renderer->fileExtension;
  3446. else
  3447. $extension='.php';
  3448. if($viewName[0]==='/')
  3449. {
  3450. if(strncmp($viewName,'//',2)===0)
  3451. $viewFile=$basePath.$viewName;
  3452. else
  3453. $viewFile=$moduleViewPath.$viewName;
  3454. }
  3455. else if(strpos($viewName,'.'))
  3456. $viewFile=Yii::getPathOfAlias($viewName);
  3457. else
  3458. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3459. if(is_file($viewFile.$extension))
  3460. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3461. else if($extension!=='.php' && is_file($viewFile.'.php'))
  3462. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3463. else
  3464. return false;
  3465. }
  3466. public function getClips()
  3467. {
  3468. if($this->_clips!==null)
  3469. return $this->_clips;
  3470. else
  3471. return $this->_clips=new CMap;
  3472. }
  3473. public function forward($route,$exit=true)
  3474. {
  3475. if(strpos($route,'/')===false)
  3476. $this->run($route);
  3477. else
  3478. {
  3479. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3480. $route=$module->getId().'/'.$route;
  3481. Yii::app()->runController($route);
  3482. }
  3483. if($exit)
  3484. Yii::app()->end();
  3485. }
  3486. public function render($view,$data=null,$return=false)
  3487. {
  3488. if($this->beforeRender($view))
  3489. {
  3490. $output=$this->renderPartial($view,$data,true);
  3491. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3492. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3493. $this->afterRender($view,$output);
  3494. $output=$this->processOutput($output);
  3495. if($return)
  3496. return $output;
  3497. else
  3498. echo $output;
  3499. }
  3500. }
  3501. protected function beforeRender($view)
  3502. {
  3503. return true;
  3504. }
  3505. protected function afterRender($view, &$output)
  3506. {
  3507. }
  3508. public function renderText($text,$return=false)
  3509. {
  3510. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3511. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3512. $text=$this->processOutput($text);
  3513. if($return)
  3514. return $text;
  3515. else
  3516. echo $text;
  3517. }
  3518. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3519. {
  3520. if(($viewFile=$this->getViewFile($view))!==false)
  3521. {
  3522. $output=$this->renderFile($viewFile,$data,true);
  3523. if($processOutput)
  3524. $output=$this->processOutput($output);
  3525. if($return)
  3526. return $output;
  3527. else
  3528. echo $output;
  3529. }
  3530. else
  3531. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3532. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3533. }
  3534. public function renderClip($name,$params=array(),$return=false)
  3535. {
  3536. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  3537. if($return)
  3538. return $text;
  3539. else
  3540. echo $text;
  3541. }
  3542. public function renderDynamic($callback)
  3543. {
  3544. $n=count($this->_dynamicOutput);
  3545. echo "<###dynamic-$n###>";
  3546. $params=func_get_args();
  3547. array_shift($params);
  3548. $this->renderDynamicInternal($callback,$params);
  3549. }
  3550. public function renderDynamicInternal($callback,$params)
  3551. {
  3552. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3553. if(is_string($callback) && method_exists($this,$callback))
  3554. $callback=array($this,$callback);
  3555. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3556. }
  3557. public function createUrl($route,$params=array(),$ampersand='&')
  3558. {
  3559. if($route==='')
  3560. $route=$this->getId().'/'.$this->getAction()->getId();
  3561. else if(strpos($route,'/')===false)
  3562. $route=$this->getId().'/'.$route;
  3563. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3564. $route=$module->getId().'/'.$route;
  3565. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3566. }
  3567. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3568. {
  3569. $url=$this->createUrl($route,$params,$ampersand);
  3570. if(strpos($url,'http')===0)
  3571. return $url;
  3572. else
  3573. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  3574. }
  3575. public function getPageTitle()
  3576. {
  3577. if($this->_pageTitle!==null)
  3578. return $this->_pageTitle;
  3579. else
  3580. {
  3581. $name=ucfirst(basename($this->getId()));
  3582. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3583. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3584. else
  3585. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3586. }
  3587. }
  3588. public function setPageTitle($value)
  3589. {
  3590. $this->_pageTitle=$value;
  3591. }
  3592. public function redirect($url,$terminate=true,$statusCode=302)
  3593. {
  3594. if(is_array($url))
  3595. {
  3596. $route=isset($url[0]) ? $url[0] : '';
  3597. $url=$this->createUrl($route,array_splice($url,1));
  3598. }
  3599. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  3600. }
  3601. public function refresh($terminate=true,$anchor='')
  3602. {
  3603. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  3604. }
  3605. public function recordCachingAction($context,$method,$params)
  3606. {
  3607. if($this->_cachingStack) // record only when there is an active output cache
  3608. {
  3609. foreach($this->_cachingStack as $cache)
  3610. $cache->recordAction($context,$method,$params);
  3611. }
  3612. }
  3613. public function getCachingStack($createIfNull=true)
  3614. {
  3615. if(!$this->_cachingStack)
  3616. $this->_cachingStack=new CStack;
  3617. return $this->_cachingStack;
  3618. }
  3619. public function isCachingStackEmpty()
  3620. {
  3621. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  3622. }
  3623. protected function beforeAction($action)
  3624. {
  3625. return true;
  3626. }
  3627. protected function afterAction($action)
  3628. {
  3629. }
  3630. public function filterPostOnly($filterChain)
  3631. {
  3632. if(Yii::app()->getRequest()->getIsPostRequest())
  3633. $filterChain->run();
  3634. else
  3635. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3636. }
  3637. public function filterAjaxOnly($filterChain)
  3638. {
  3639. if(Yii::app()->getRequest()->getIsAjaxRequest())
  3640. $filterChain->run();
  3641. else
  3642. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3643. }
  3644. public function filterAccessControl($filterChain)
  3645. {
  3646. $filter=new CAccessControlFilter;
  3647. $filter->setRules($this->accessRules());
  3648. $filter->filter($filterChain);
  3649. }
  3650. public function getPageState($name,$defaultValue=null)
  3651. {
  3652. if($this->_pageStates===null)
  3653. $this->_pageStates=$this->loadPageStates();
  3654. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  3655. }
  3656. public function setPageState($name,$value,$defaultValue=null)
  3657. {
  3658. if($this->_pageStates===null)
  3659. $this->_pageStates=$this->loadPageStates();
  3660. if($value===$defaultValue)
  3661. unset($this->_pageStates[$name]);
  3662. else
  3663. $this->_pageStates[$name]=$value;
  3664. $params=func_get_args();
  3665. $this->recordCachingAction('','setPageState',$params);
  3666. }
  3667. public function clearPageStates()
  3668. {
  3669. $this->_pageStates=array();
  3670. }
  3671. protected function loadPageStates()
  3672. {
  3673. if(!empty($_POST[self::STATE_INPUT_NAME]))
  3674. {
  3675. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  3676. {
  3677. if(extension_loaded('zlib'))
  3678. $data=@gzuncompress($data);
  3679. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  3680. return unserialize($data);
  3681. }
  3682. }
  3683. return array();
  3684. }
  3685. protected function savePageStates($states,&$output)
  3686. {
  3687. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  3688. if(extension_loaded('zlib'))
  3689. $data=gzcompress($data);
  3690. $value=base64_encode($data);
  3691. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  3692. }
  3693. }
  3694. abstract class CAction extends CComponent implements IAction
  3695. {
  3696. private $_id;
  3697. private $_controller;
  3698. public function __construct($controller,$id)
  3699. {
  3700. $this->_controller=$controller;
  3701. $this->_id=$id;
  3702. }
  3703. public function getController()
  3704. {
  3705. return $this->_controller;
  3706. }
  3707. public function getId()
  3708. {
  3709. return $this->_id;
  3710. }
  3711. public function runWithParams($params)
  3712. {
  3713. $method=new ReflectionMethod($this, 'run');
  3714. if($method->getNumberOfParameters()>0)
  3715. return $this->runWithParamsInternal($this, $method, $params);
  3716. else
  3717. return $this->run();
  3718. }
  3719. protected function runWithParamsInternal($object, $method, $params)
  3720. {
  3721. $ps=array();
  3722. foreach($method->getParameters() as $i=>$param)
  3723. {
  3724. $name=$param->getName();
  3725. if(isset($params[$name]))
  3726. {
  3727. if($param->isArray())
  3728. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  3729. else if(!is_array($params[$name]))
  3730. $ps[]=$params[$name];
  3731. else
  3732. return false;
  3733. }
  3734. else if($param->isDefaultValueAvailable())
  3735. $ps[]=$param->getDefaultValue();
  3736. else
  3737. return false;
  3738. }
  3739. $method->invokeArgs($object,$ps);
  3740. return true;
  3741. }
  3742. }
  3743. class CInlineAction extends CAction
  3744. {
  3745. public function run()
  3746. {
  3747. $method='action'.$this->getId();
  3748. $this->getController()->$method();
  3749. }
  3750. public function runWithParams($params)
  3751. {
  3752. $methodName='action'.$this->getId();
  3753. $controller=$this->getController();
  3754. $method=new ReflectionMethod($controller, $methodName);
  3755. if($method->getNumberOfParameters()>0)
  3756. return $this->runWithParamsInternal($controller, $method, $params);
  3757. else
  3758. return $controller->$methodName();
  3759. }
  3760. }
  3761. class CWebUser extends CApplicationComponent implements IWebUser
  3762. {
  3763. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  3764. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  3765. const STATES_VAR='__states';
  3766. const AUTH_TIMEOUT_VAR='__timeout';
  3767. public $allowAutoLogin=false;
  3768. public $guestName='Guest';
  3769. public $loginUrl=array('/site/login');
  3770. public $identityCookie;
  3771. public $authTimeout;
  3772. public $autoRenewCookie=false;
  3773. public $autoUpdateFlash=true;
  3774. public $loginRequiredAjaxResponse;
  3775. private $_keyPrefix;
  3776. private $_access=array();
  3777. public function __get($name)
  3778. {
  3779. if($this->hasState($name))
  3780. return $this->getState($name);
  3781. else
  3782. return parent::__get($name);
  3783. }
  3784. public function __set($name,$value)
  3785. {
  3786. if($this->hasState($name))
  3787. $this->setState($name,$value);
  3788. else
  3789. parent::__set($name,$value);
  3790. }
  3791. public function __isset($name)
  3792. {
  3793. if($this->hasState($name))
  3794. return $this->getState($name)!==null;
  3795. else
  3796. return parent::__isset($name);
  3797. }
  3798. public function __unset($name)
  3799. {
  3800. if($this->hasState($name))
  3801. $this->setState($name,null);
  3802. else
  3803. parent::__unset($name);
  3804. }
  3805. public function init()
  3806. {
  3807. parent::init();
  3808. Yii::app()->getSession()->open();
  3809. if($this->getIsGuest() && $this->allowAutoLogin)
  3810. $this->restoreFromCookie();
  3811. else if($this->autoRenewCookie && $this->allowAutoLogin)
  3812. $this->renewCookie();
  3813. if($this->autoUpdateFlash)
  3814. $this->updateFlash();
  3815. $this->updateAuthStatus();
  3816. }
  3817. public function login($identity,$duration=0)
  3818. {
  3819. $id=$identity->getId();
  3820. $states=$identity->getPersistentStates();
  3821. if($this->beforeLogin($id,$states,false))
  3822. {
  3823. $this->changeIdentity($id,$identity->getName(),$states);
  3824. if($duration>0)
  3825. {
  3826. if($this->allowAutoLogin)
  3827. $this->saveToCookie($duration);
  3828. else
  3829. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  3830. array('{class}'=>get_class($this))));
  3831. }
  3832. $this->afterLogin(false);
  3833. }
  3834. return !$this->getIsGuest();
  3835. }
  3836. public function logout($destroySession=true)
  3837. {
  3838. if($this->beforeLogout())
  3839. {
  3840. if($this->allowAutoLogin)
  3841. {
  3842. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  3843. if($this->identityCookie!==null)
  3844. {
  3845. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3846. $cookie->value=null;
  3847. $cookie->expire=0;
  3848. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  3849. }
  3850. }
  3851. if($destroySession)
  3852. Yii::app()->getSession()->destroy();
  3853. else
  3854. $this->clearStates();
  3855. $this->afterLogout();
  3856. }
  3857. }
  3858. public function getIsGuest()
  3859. {
  3860. return $this->getState('__id')===null;
  3861. }
  3862. public function getId()
  3863. {
  3864. return $this->getState('__id');
  3865. }
  3866. public function setId($value)
  3867. {
  3868. $this->setState('__id',$value);
  3869. }
  3870. public function getName()
  3871. {
  3872. if(($name=$this->getState('__name'))!==null)
  3873. return $name;
  3874. else
  3875. return $this->guestName;
  3876. }
  3877. public function setName($value)
  3878. {
  3879. $this->setState('__name',$value);
  3880. }
  3881. public function getReturnUrl($defaultUrl=null)
  3882. {
  3883. return $this->getState('__returnUrl', $defaultUrl===null ? Yii::app()->getRequest()->getScriptUrl() : CHtml::normalizeUrl($defaultUrl));
  3884. }
  3885. public function setReturnUrl($value)
  3886. {
  3887. $this->setState('__returnUrl',$value);
  3888. }
  3889. public function loginRequired()
  3890. {
  3891. $app=Yii::app();
  3892. $request=$app->getRequest();
  3893. if(!$request->getIsAjaxRequest())
  3894. $this->setReturnUrl($request->getUrl());
  3895. elseif(isset($this->loginRequiredAjaxResponse))
  3896. {
  3897. echo $this->loginRequiredAjaxResponse;
  3898. Yii::app()->end();
  3899. }
  3900. if(($url=$this->loginUrl)!==null)
  3901. {
  3902. if(is_array($url))
  3903. {
  3904. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  3905. $url=$app->createUrl($route,array_splice($url,1));
  3906. }
  3907. $request->redirect($url);
  3908. }
  3909. else
  3910. throw new CHttpException(403,Yii::t('yii','Login Required'));
  3911. }
  3912. protected function beforeLogin($id,$states,$fromCookie)
  3913. {
  3914. return true;
  3915. }
  3916. protected function afterLogin($fromCookie)
  3917. {
  3918. }
  3919. protected function beforeLogout()
  3920. {
  3921. return true;
  3922. }
  3923. protected function afterLogout()
  3924. {
  3925. }
  3926. protected function restoreFromCookie()
  3927. {
  3928. $app=Yii::app();
  3929. $request=$app->getRequest();
  3930. $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  3931. if($cookie && !empty($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  3932. {
  3933. $data=@unserialize($data);
  3934. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3935. {
  3936. list($id,$name,$duration,$states)=$data;
  3937. if($this->beforeLogin($id,$states,true))
  3938. {
  3939. $this->changeIdentity($id,$name,$states);
  3940. if($this->autoRenewCookie)
  3941. {
  3942. $cookie->expire=time()+$duration;
  3943. $request->getCookies()->add($cookie->name,$cookie);
  3944. }
  3945. $this->afterLogin(true);
  3946. }
  3947. }
  3948. }
  3949. }
  3950. protected function renewCookie()
  3951. {
  3952. $request=Yii::app()->getRequest();
  3953. $cookies=$request->getCookies();
  3954. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  3955. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  3956. {
  3957. $data=@unserialize($data);
  3958. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3959. {
  3960. $cookie->expire=time()+$data[2];
  3961. $cookies->add($cookie->name,$cookie);
  3962. }
  3963. }
  3964. }
  3965. protected function saveToCookie($duration)
  3966. {
  3967. $app=Yii::app();
  3968. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3969. $cookie->expire=time()+$duration;
  3970. $data=array(
  3971. $this->getId(),
  3972. $this->getName(),
  3973. $duration,
  3974. $this->saveIdentityStates(),
  3975. );
  3976. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  3977. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  3978. }
  3979. protected function createIdentityCookie($name)
  3980. {
  3981. $cookie=new CHttpCookie($name,'');
  3982. if(is_array($this->identityCookie))
  3983. {
  3984. foreach($this->identityCookie as $name=>$value)
  3985. $cookie->$name=$value;
  3986. }
  3987. return $cookie;
  3988. }
  3989. public function getStateKeyPrefix()
  3990. {
  3991. if($this->_keyPrefix!==null)
  3992. return $this->_keyPrefix;
  3993. else
  3994. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  3995. }
  3996. public function setStateKeyPrefix($value)
  3997. {
  3998. $this->_keyPrefix=$value;
  3999. }
  4000. public function getState($key,$defaultValue=null)
  4001. {
  4002. $key=$this->getStateKeyPrefix().$key;
  4003. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4004. }
  4005. public function setState($key,$value,$defaultValue=null)
  4006. {
  4007. $key=$this->getStateKeyPrefix().$key;
  4008. if($value===$defaultValue)
  4009. unset($_SESSION[$key]);
  4010. else
  4011. $_SESSION[$key]=$value;
  4012. }
  4013. public function hasState($key)
  4014. {
  4015. $key=$this->getStateKeyPrefix().$key;
  4016. return isset($_SESSION[$key]);
  4017. }
  4018. public function clearStates()
  4019. {
  4020. $keys=array_keys($_SESSION);
  4021. $prefix=$this->getStateKeyPrefix();
  4022. $n=strlen($prefix);
  4023. foreach($keys as $key)
  4024. {
  4025. if(!strncmp($key,$prefix,$n))
  4026. unset($_SESSION[$key]);
  4027. }
  4028. }
  4029. public function getFlashes($delete=true)
  4030. {
  4031. $flashes=array();
  4032. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  4033. $keys=array_keys($_SESSION);
  4034. $n=strlen($prefix);
  4035. foreach($keys as $key)
  4036. {
  4037. if(!strncmp($key,$prefix,$n))
  4038. {
  4039. $flashes[substr($key,$n)]=$_SESSION[$key];
  4040. if($delete)
  4041. unset($_SESSION[$key]);
  4042. }
  4043. }
  4044. if($delete)
  4045. $this->setState(self::FLASH_COUNTERS,array());
  4046. return $flashes;
  4047. }
  4048. public function getFlash($key,$defaultValue=null,$delete=true)
  4049. {
  4050. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4051. if($delete)
  4052. $this->setFlash($key,null);
  4053. return $value;
  4054. }
  4055. public function setFlash($key,$value,$defaultValue=null)
  4056. {
  4057. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4058. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4059. if($value===$defaultValue)
  4060. unset($counters[$key]);
  4061. else
  4062. $counters[$key]=0;
  4063. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4064. }
  4065. public function hasFlash($key)
  4066. {
  4067. return $this->getFlash($key, null, false)!==null;
  4068. }
  4069. protected function changeIdentity($id,$name,$states)
  4070. {
  4071. Yii::app()->getSession()->regenerateID();
  4072. $this->setId($id);
  4073. $this->setName($name);
  4074. $this->loadIdentityStates($states);
  4075. }
  4076. protected function saveIdentityStates()
  4077. {
  4078. $states=array();
  4079. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4080. $states[$name]=$this->getState($name);
  4081. return $states;
  4082. }
  4083. protected function loadIdentityStates($states)
  4084. {
  4085. $names=array();
  4086. if(is_array($states))
  4087. {
  4088. foreach($states as $name=>$value)
  4089. {
  4090. $this->setState($name,$value);
  4091. $names[$name]=true;
  4092. }
  4093. }
  4094. $this->setState(self::STATES_VAR,$names);
  4095. }
  4096. protected function updateFlash()
  4097. {
  4098. $counters=$this->getState(self::FLASH_COUNTERS);
  4099. if(!is_array($counters))
  4100. return;
  4101. foreach($counters as $key=>$count)
  4102. {
  4103. if($count)
  4104. {
  4105. unset($counters[$key]);
  4106. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4107. }
  4108. else
  4109. $counters[$key]++;
  4110. }
  4111. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4112. }
  4113. protected function updateAuthStatus()
  4114. {
  4115. if($this->authTimeout!==null && !$this->getIsGuest())
  4116. {
  4117. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4118. if ($expires!==null && $expires < time())
  4119. $this->logout(false);
  4120. else
  4121. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4122. }
  4123. }
  4124. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4125. {
  4126. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4127. return $this->_access[$operation];
  4128. else
  4129. return $this->_access[$operation]=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4130. }
  4131. }
  4132. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4133. {
  4134. public $autoStart=true;
  4135. public function init()
  4136. {
  4137. parent::init();
  4138. if($this->autoStart)
  4139. $this->open();
  4140. register_shutdown_function(array($this,'close'));
  4141. }
  4142. public function getUseCustomStorage()
  4143. {
  4144. return false;
  4145. }
  4146. public function open()
  4147. {
  4148. if($this->getUseCustomStorage())
  4149. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4150. @session_start();
  4151. if(YII_DEBUG && session_id()=='')
  4152. {
  4153. $message=Yii::t('yii','Failed to start session.');
  4154. if(function_exists('error_get_last'))
  4155. {
  4156. $error=error_get_last();
  4157. if(isset($error['message']))
  4158. $message=$error['message'];
  4159. }
  4160. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4161. }
  4162. }
  4163. public function close()
  4164. {
  4165. if(session_id()!=='')
  4166. @session_write_close();
  4167. }
  4168. public function destroy()
  4169. {
  4170. if(session_id()!=='')
  4171. {
  4172. @session_unset();
  4173. @session_destroy();
  4174. }
  4175. }
  4176. public function getIsStarted()
  4177. {
  4178. return session_id()!=='';
  4179. }
  4180. public function getSessionID()
  4181. {
  4182. return session_id();
  4183. }
  4184. public function setSessionID($value)
  4185. {
  4186. session_id($value);
  4187. }
  4188. public function regenerateID($deleteOldSession=false)
  4189. {
  4190. session_regenerate_id($deleteOldSession);
  4191. }
  4192. public function getSessionName()
  4193. {
  4194. return session_name();
  4195. }
  4196. public function setSessionName($value)
  4197. {
  4198. session_name($value);
  4199. }
  4200. public function getSavePath()
  4201. {
  4202. return session_save_path();
  4203. }
  4204. public function setSavePath($value)
  4205. {
  4206. if(is_dir($value))
  4207. session_save_path($value);
  4208. else
  4209. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4210. array('{path}'=>$value)));
  4211. }
  4212. public function getCookieParams()
  4213. {
  4214. return session_get_cookie_params();
  4215. }
  4216. public function setCookieParams($value)
  4217. {
  4218. $data=session_get_cookie_params();
  4219. extract($data);
  4220. extract($value);
  4221. if(isset($httponly))
  4222. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4223. else
  4224. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4225. }
  4226. public function getCookieMode()
  4227. {
  4228. if(ini_get('session.use_cookies')==='0')
  4229. return 'none';
  4230. else if(ini_get('session.use_only_cookies')==='0')
  4231. return 'allow';
  4232. else
  4233. return 'only';
  4234. }
  4235. public function setCookieMode($value)
  4236. {
  4237. if($value==='none')
  4238. {
  4239. ini_set('session.use_cookies','0');
  4240. ini_set('session.use_only_cookies','0');
  4241. }
  4242. else if($value==='allow')
  4243. {
  4244. ini_set('session.use_cookies','1');
  4245. ini_set('session.use_only_cookies','0');
  4246. }
  4247. else if($value==='only')
  4248. {
  4249. ini_set('session.use_cookies','1');
  4250. ini_set('session.use_only_cookies','1');
  4251. }
  4252. else
  4253. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4254. }
  4255. public function getGCProbability()
  4256. {
  4257. return (int)ini_get('session.gc_probability');
  4258. }
  4259. public function setGCProbability($value)
  4260. {
  4261. $value=(int)$value;
  4262. if($value>=0 && $value<=100)
  4263. {
  4264. ini_set('session.gc_probability',$value);
  4265. ini_set('session.gc_divisor','100');
  4266. }
  4267. else
  4268. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be an integer between 0 and 100.',
  4269. array('{value}'=>$value)));
  4270. }
  4271. public function getUseTransparentSessionID()
  4272. {
  4273. return ini_get('session.use_trans_sid')==1;
  4274. }
  4275. public function setUseTransparentSessionID($value)
  4276. {
  4277. ini_set('session.use_trans_sid',$value?'1':'0');
  4278. }
  4279. public function getTimeout()
  4280. {
  4281. return (int)ini_get('session.gc_maxlifetime');
  4282. }
  4283. public function setTimeout($value)
  4284. {
  4285. ini_set('session.gc_maxlifetime',$value);
  4286. }
  4287. public function openSession($savePath,$sessionName)
  4288. {
  4289. return true;
  4290. }
  4291. public function closeSession()
  4292. {
  4293. return true;
  4294. }
  4295. public function readSession($id)
  4296. {
  4297. return '';
  4298. }
  4299. public function writeSession($id,$data)
  4300. {
  4301. return true;
  4302. }
  4303. public function destroySession($id)
  4304. {
  4305. return true;
  4306. }
  4307. public function gcSession($maxLifetime)
  4308. {
  4309. return true;
  4310. }
  4311. //------ The following methods enable CHttpSession to be CMap-like -----
  4312. public function getIterator()
  4313. {
  4314. return new CHttpSessionIterator;
  4315. }
  4316. public function getCount()
  4317. {
  4318. return count($_SESSION);
  4319. }
  4320. public function count()
  4321. {
  4322. return $this->getCount();
  4323. }
  4324. public function getKeys()
  4325. {
  4326. return array_keys($_SESSION);
  4327. }
  4328. public function get($key,$defaultValue=null)
  4329. {
  4330. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4331. }
  4332. public function itemAt($key)
  4333. {
  4334. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4335. }
  4336. public function add($key,$value)
  4337. {
  4338. $_SESSION[$key]=$value;
  4339. }
  4340. public function remove($key)
  4341. {
  4342. if(isset($_SESSION[$key]))
  4343. {
  4344. $value=$_SESSION[$key];
  4345. unset($_SESSION[$key]);
  4346. return $value;
  4347. }
  4348. else
  4349. return null;
  4350. }
  4351. public function clear()
  4352. {
  4353. foreach(array_keys($_SESSION) as $key)
  4354. unset($_SESSION[$key]);
  4355. }
  4356. public function contains($key)
  4357. {
  4358. return isset($_SESSION[$key]);
  4359. }
  4360. public function toArray()
  4361. {
  4362. return $_SESSION;
  4363. }
  4364. public function offsetExists($offset)
  4365. {
  4366. return isset($_SESSION[$offset]);
  4367. }
  4368. public function offsetGet($offset)
  4369. {
  4370. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4371. }
  4372. public function offsetSet($offset,$item)
  4373. {
  4374. $_SESSION[$offset]=$item;
  4375. }
  4376. public function offsetUnset($offset)
  4377. {
  4378. unset($_SESSION[$offset]);
  4379. }
  4380. }
  4381. class CHtml
  4382. {
  4383. const ID_PREFIX='yt';
  4384. public static $errorSummaryCss='errorSummary';
  4385. public static $errorMessageCss='errorMessage';
  4386. public static $errorCss='error';
  4387. public static $requiredCss='required';
  4388. public static $beforeRequiredLabel='';
  4389. public static $afterRequiredLabel=' <span class="required">*</span>';
  4390. public static $count=0;
  4391. public static $liveEvents = true;
  4392. public static function encode($text)
  4393. {
  4394. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4395. }
  4396. public static function decode($text)
  4397. {
  4398. return htmlspecialchars_decode($text,ENT_QUOTES);
  4399. }
  4400. public static function encodeArray($data)
  4401. {
  4402. $d=array();
  4403. foreach($data as $key=>$value)
  4404. {
  4405. if(is_string($key))
  4406. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4407. if(is_string($value))
  4408. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4409. else if(is_array($value))
  4410. $value=self::encodeArray($value);
  4411. $d[$key]=$value;
  4412. }
  4413. return $d;
  4414. }
  4415. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4416. {
  4417. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4418. if($content===false)
  4419. return $closeTag ? $html.' />' : $html.'>';
  4420. else
  4421. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4422. }
  4423. public static function openTag($tag,$htmlOptions=array())
  4424. {
  4425. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4426. }
  4427. public static function closeTag($tag)
  4428. {
  4429. return '</'.$tag.'>';
  4430. }
  4431. public static function cdata($text)
  4432. {
  4433. return '<![CDATA[' . $text . ']]>';
  4434. }
  4435. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4436. {
  4437. if($name!==null)
  4438. $options['name']=$name;
  4439. if($httpEquiv!==null)
  4440. $options['http-equiv']=$httpEquiv;
  4441. $options['content']=$content;
  4442. return self::tag('meta',$options);
  4443. }
  4444. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4445. {
  4446. if($relation!==null)
  4447. $options['rel']=$relation;
  4448. if($type!==null)
  4449. $options['type']=$type;
  4450. if($href!==null)
  4451. $options['href']=$href;
  4452. if($media!==null)
  4453. $options['media']=$media;
  4454. return self::tag('link',$options);
  4455. }
  4456. public static function css($text,$media='')
  4457. {
  4458. if($media!=='')
  4459. $media=' media="'.$media.'"';
  4460. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4461. }
  4462. public static function refresh($seconds, $url='')
  4463. {
  4464. $content="$seconds";
  4465. if($url!=='')
  4466. $content.=';'.self::normalizeUrl($url);
  4467. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4468. }
  4469. public static function cssFile($url,$media='')
  4470. {
  4471. if($media!=='')
  4472. $media=' media="'.$media.'"';
  4473. return '<link rel="stylesheet" type="text/css" href="'.self::encode($url).'"'.$media.' />';
  4474. }
  4475. public static function script($text)
  4476. {
  4477. return "<script type=\"text/javascript\">\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</script>";
  4478. }
  4479. public static function scriptFile($url)
  4480. {
  4481. return '<script type="text/javascript" src="'.self::encode($url).'"></script>';
  4482. }
  4483. public static function form($action='',$method='post',$htmlOptions=array())
  4484. {
  4485. return self::beginForm($action,$method,$htmlOptions);
  4486. }
  4487. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4488. {
  4489. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4490. $htmlOptions['method']=$method;
  4491. $form=self::tag('form',$htmlOptions,false,false);
  4492. $hiddens=array();
  4493. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4494. {
  4495. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4496. {
  4497. if(($pos=strpos($pair,'='))!==false)
  4498. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4499. }
  4500. }
  4501. $request=Yii::app()->request;
  4502. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4503. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4504. if($hiddens!==array())
  4505. $form.="\n".self::tag('div',array('style'=>'display:none'),implode("\n",$hiddens));
  4506. return $form;
  4507. }
  4508. public static function endForm()
  4509. {
  4510. return '</form>';
  4511. }
  4512. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4513. {
  4514. return self::form($action,$method,$htmlOptions)."\n".
  4515. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4516. }
  4517. public static function pageStateField($value)
  4518. {
  4519. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4520. }
  4521. public static function link($text,$url='#',$htmlOptions=array())
  4522. {
  4523. if($url!=='')
  4524. $htmlOptions['href']=self::normalizeUrl($url);
  4525. self::clientChange('click',$htmlOptions);
  4526. return self::tag('a',$htmlOptions,$text);
  4527. }
  4528. public static function mailto($text,$email='',$htmlOptions=array())
  4529. {
  4530. if($email==='')
  4531. $email=$text;
  4532. return self::link($text,'mailto:'.$email,$htmlOptions);
  4533. }
  4534. public static function image($src,$alt='',$htmlOptions=array())
  4535. {
  4536. $htmlOptions['src']=$src;
  4537. $htmlOptions['alt']=$alt;
  4538. return self::tag('img',$htmlOptions);
  4539. }
  4540. public static function button($label='button',$htmlOptions=array())
  4541. {
  4542. if(!isset($htmlOptions['name']))
  4543. {
  4544. if(!array_key_exists('name',$htmlOptions))
  4545. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4546. }
  4547. if(!isset($htmlOptions['type']))
  4548. $htmlOptions['type']='button';
  4549. if(!isset($htmlOptions['value']))
  4550. $htmlOptions['value']=$label;
  4551. self::clientChange('click',$htmlOptions);
  4552. return self::tag('input',$htmlOptions);
  4553. }
  4554. public static function htmlButton($label='button',$htmlOptions=array())
  4555. {
  4556. if(!isset($htmlOptions['name']))
  4557. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4558. if(!isset($htmlOptions['type']))
  4559. $htmlOptions['type']='button';
  4560. self::clientChange('click',$htmlOptions);
  4561. return self::tag('button',$htmlOptions,$label);
  4562. }
  4563. public static function submitButton($label='submit',$htmlOptions=array())
  4564. {
  4565. $htmlOptions['type']='submit';
  4566. return self::button($label,$htmlOptions);
  4567. }
  4568. public static function resetButton($label='reset',$htmlOptions=array())
  4569. {
  4570. $htmlOptions['type']='reset';
  4571. return self::button($label,$htmlOptions);
  4572. }
  4573. public static function imageButton($src,$htmlOptions=array())
  4574. {
  4575. $htmlOptions['src']=$src;
  4576. $htmlOptions['type']='image';
  4577. return self::button('submit',$htmlOptions);
  4578. }
  4579. public static function linkButton($label='submit',$htmlOptions=array())
  4580. {
  4581. if(!isset($htmlOptions['submit']))
  4582. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  4583. return self::link($label,'#',$htmlOptions);
  4584. }
  4585. public static function label($label,$for,$htmlOptions=array())
  4586. {
  4587. if($for===false)
  4588. unset($htmlOptions['for']);
  4589. else
  4590. $htmlOptions['for']=$for;
  4591. if(isset($htmlOptions['required']))
  4592. {
  4593. if($htmlOptions['required'])
  4594. {
  4595. if(isset($htmlOptions['class']))
  4596. $htmlOptions['class'].=' '.self::$requiredCss;
  4597. else
  4598. $htmlOptions['class']=self::$requiredCss;
  4599. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  4600. }
  4601. unset($htmlOptions['required']);
  4602. }
  4603. return self::tag('label',$htmlOptions,$label);
  4604. }
  4605. public static function textField($name,$value='',$htmlOptions=array())
  4606. {
  4607. self::clientChange('change',$htmlOptions);
  4608. return self::inputField('text',$name,$value,$htmlOptions);
  4609. }
  4610. public static function hiddenField($name,$value='',$htmlOptions=array())
  4611. {
  4612. return self::inputField('hidden',$name,$value,$htmlOptions);
  4613. }
  4614. public static function passwordField($name,$value='',$htmlOptions=array())
  4615. {
  4616. self::clientChange('change',$htmlOptions);
  4617. return self::inputField('password',$name,$value,$htmlOptions);
  4618. }
  4619. public static function fileField($name,$value='',$htmlOptions=array())
  4620. {
  4621. return self::inputField('file',$name,$value,$htmlOptions);
  4622. }
  4623. public static function textArea($name,$value='',$htmlOptions=array())
  4624. {
  4625. $htmlOptions['name']=$name;
  4626. if(!isset($htmlOptions['id']))
  4627. $htmlOptions['id']=self::getIdByName($name);
  4628. else if($htmlOptions['id']===false)
  4629. unset($htmlOptions['id']);
  4630. self::clientChange('change',$htmlOptions);
  4631. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  4632. }
  4633. public static function radioButton($name,$checked=false,$htmlOptions=array())
  4634. {
  4635. if($checked)
  4636. $htmlOptions['checked']='checked';
  4637. else
  4638. unset($htmlOptions['checked']);
  4639. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4640. self::clientChange('click',$htmlOptions);
  4641. if(array_key_exists('uncheckValue',$htmlOptions))
  4642. {
  4643. $uncheck=$htmlOptions['uncheckValue'];
  4644. unset($htmlOptions['uncheckValue']);
  4645. }
  4646. else
  4647. $uncheck=null;
  4648. if($uncheck!==null)
  4649. {
  4650. // add a hidden field so that if the radio button is not selected, it still submits a value
  4651. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4652. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4653. else
  4654. $uncheckOptions=array('id'=>false);
  4655. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4656. }
  4657. else
  4658. $hidden='';
  4659. // add a hidden field so that if the radio button is not selected, it still submits a value
  4660. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  4661. }
  4662. public static function checkBox($name,$checked=false,$htmlOptions=array())
  4663. {
  4664. if($checked)
  4665. $htmlOptions['checked']='checked';
  4666. else
  4667. unset($htmlOptions['checked']);
  4668. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4669. self::clientChange('click',$htmlOptions);
  4670. if(array_key_exists('uncheckValue',$htmlOptions))
  4671. {
  4672. $uncheck=$htmlOptions['uncheckValue'];
  4673. unset($htmlOptions['uncheckValue']);
  4674. }
  4675. else
  4676. $uncheck=null;
  4677. if($uncheck!==null)
  4678. {
  4679. // add a hidden field so that if the radio button is not selected, it still submits a value
  4680. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4681. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4682. else
  4683. $uncheckOptions=array('id'=>false);
  4684. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4685. }
  4686. else
  4687. $hidden='';
  4688. // add a hidden field so that if the checkbox is not selected, it still submits a value
  4689. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  4690. }
  4691. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  4692. {
  4693. $htmlOptions['name']=$name;
  4694. if(!isset($htmlOptions['id']))
  4695. $htmlOptions['id']=self::getIdByName($name);
  4696. else if($htmlOptions['id']===false)
  4697. unset($htmlOptions['id']);
  4698. self::clientChange('change',$htmlOptions);
  4699. $options="\n".self::listOptions($select,$data,$htmlOptions);
  4700. return self::tag('select',$htmlOptions,$options);
  4701. }
  4702. public static function listBox($name,$select,$data,$htmlOptions=array())
  4703. {
  4704. if(!isset($htmlOptions['size']))
  4705. $htmlOptions['size']=4;
  4706. if(isset($htmlOptions['multiple']))
  4707. {
  4708. if(substr($name,-2)!=='[]')
  4709. $name.='[]';
  4710. }
  4711. return self::dropDownList($name,$select,$data,$htmlOptions);
  4712. }
  4713. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  4714. {
  4715. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4716. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4717. unset($htmlOptions['template'],$htmlOptions['separator']);
  4718. if(substr($name,-2)!=='[]')
  4719. $name.='[]';
  4720. if(isset($htmlOptions['checkAll']))
  4721. {
  4722. $checkAllLabel=$htmlOptions['checkAll'];
  4723. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  4724. }
  4725. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  4726. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4727. unset($htmlOptions['labelOptions']);
  4728. $items=array();
  4729. $baseID=self::getIdByName($name);
  4730. $id=0;
  4731. $checkAll=true;
  4732. foreach($data as $value=>$label)
  4733. {
  4734. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  4735. $checkAll=$checkAll && $checked;
  4736. $htmlOptions['value']=$value;
  4737. $htmlOptions['id']=$baseID.'_'.$id++;
  4738. $option=self::checkBox($name,$checked,$htmlOptions);
  4739. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4740. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4741. }
  4742. if(isset($checkAllLabel))
  4743. {
  4744. $htmlOptions['value']=1;
  4745. $htmlOptions['id']=$id=$baseID.'_all';
  4746. $option=self::checkBox($id,$checkAll,$htmlOptions);
  4747. $label=self::label($checkAllLabel,$id,$labelOptions);
  4748. $item=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4749. if($checkAllLast)
  4750. $items[]=$item;
  4751. else
  4752. array_unshift($items,$item);
  4753. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  4754. $js=<<<EOD
  4755. $('#$id').click(function() {
  4756. $("input[name='$name']").prop('checked', this.checked);
  4757. });
  4758. $("input[name='$name']").click(function() {
  4759. $('#$id').prop('checked', !$("input[name='$name']:not(:checked)").length);
  4760. });
  4761. $('#$id').prop('checked', !$("input[name='$name']:not(:checked)").length);
  4762. EOD;
  4763. $cs=Yii::app()->getClientScript();
  4764. $cs->registerCoreScript('jquery');
  4765. $cs->registerScript($id,$js);
  4766. }
  4767. return self::tag('span',array('id'=>$baseID),implode($separator,$items));
  4768. }
  4769. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  4770. {
  4771. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4772. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4773. unset($htmlOptions['template'],$htmlOptions['separator']);
  4774. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4775. unset($htmlOptions['labelOptions']);
  4776. $items=array();
  4777. $baseID=self::getIdByName($name);
  4778. $id=0;
  4779. foreach($data as $value=>$label)
  4780. {
  4781. $checked=!strcmp($value,$select);
  4782. $htmlOptions['value']=$value;
  4783. $htmlOptions['id']=$baseID.'_'.$id++;
  4784. $option=self::radioButton($name,$checked,$htmlOptions);
  4785. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4786. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4787. }
  4788. return self::tag('span',array('id'=>$baseID),implode($separator,$items));
  4789. }
  4790. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  4791. {
  4792. if(!isset($htmlOptions['href']))
  4793. $htmlOptions['href']='#';
  4794. $ajaxOptions['url']=$url;
  4795. $htmlOptions['ajax']=$ajaxOptions;
  4796. self::clientChange('click',$htmlOptions);
  4797. return self::tag('a',$htmlOptions,$text);
  4798. }
  4799. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4800. {
  4801. $ajaxOptions['url']=$url;
  4802. $htmlOptions['ajax']=$ajaxOptions;
  4803. return self::button($label,$htmlOptions);
  4804. }
  4805. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4806. {
  4807. $ajaxOptions['type']='POST';
  4808. $htmlOptions['type']='submit';
  4809. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  4810. }
  4811. public static function ajax($options)
  4812. {
  4813. Yii::app()->getClientScript()->registerCoreScript('jquery');
  4814. if(!isset($options['url']))
  4815. $options['url']='js:location.href';
  4816. else
  4817. $options['url']=self::normalizeUrl($options['url']);
  4818. if(!isset($options['cache']))
  4819. $options['cache']=false;
  4820. if(!isset($options['data']) && isset($options['type']))
  4821. $options['data']='js:jQuery(this).parents("form").serialize()';
  4822. foreach(array('beforeSend','complete','error','success') as $name)
  4823. {
  4824. if(isset($options[$name]) && strpos($options[$name],'js:')!==0)
  4825. $options[$name]='js:'.$options[$name];
  4826. }
  4827. if(isset($options['update']))
  4828. {
  4829. if(!isset($options['success']))
  4830. $options['success']='js:function(html){jQuery("'.$options['update'].'").html(html)}';
  4831. unset($options['update']);
  4832. }
  4833. if(isset($options['replace']))
  4834. {
  4835. if(!isset($options['success']))
  4836. $options['success']='js:function(html){jQuery("'.$options['replace'].'").replaceWith(html)}';
  4837. unset($options['replace']);
  4838. }
  4839. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  4840. }
  4841. public static function asset($path,$hashByName=false)
  4842. {
  4843. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  4844. }
  4845. public static function normalizeUrl($url)
  4846. {
  4847. if(is_array($url))
  4848. {
  4849. if(isset($url[0]))
  4850. {
  4851. if(($c=Yii::app()->getController())!==null)
  4852. $url=$c->createUrl($url[0],array_splice($url,1));
  4853. else
  4854. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  4855. }
  4856. else
  4857. $url='';
  4858. }
  4859. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  4860. }
  4861. protected static function inputField($type,$name,$value,$htmlOptions)
  4862. {
  4863. $htmlOptions['type']=$type;
  4864. $htmlOptions['value']=$value;
  4865. $htmlOptions['name']=$name;
  4866. if(!isset($htmlOptions['id']))
  4867. $htmlOptions['id']=self::getIdByName($name);
  4868. else if($htmlOptions['id']===false)
  4869. unset($htmlOptions['id']);
  4870. return self::tag('input',$htmlOptions);
  4871. }
  4872. public static function activeLabel($model,$attribute,$htmlOptions=array())
  4873. {
  4874. if(isset($htmlOptions['for']))
  4875. {
  4876. $for=$htmlOptions['for'];
  4877. unset($htmlOptions['for']);
  4878. }
  4879. else
  4880. $for=self::getIdByName(self::resolveName($model,$attribute));
  4881. if(isset($htmlOptions['label']))
  4882. {
  4883. if(($label=$htmlOptions['label'])===false)
  4884. return '';
  4885. unset($htmlOptions['label']);
  4886. }
  4887. else
  4888. $label=$model->getAttributeLabel($attribute);
  4889. if($model->hasErrors($attribute))
  4890. self::addErrorCss($htmlOptions);
  4891. return self::label($label,$for,$htmlOptions);
  4892. }
  4893. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  4894. {
  4895. $realAttribute=$attribute;
  4896. self::resolveName($model,$attribute); // strip off square brackets if any
  4897. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  4898. return self::activeLabel($model,$realAttribute,$htmlOptions);
  4899. }
  4900. public static function activeTextField($model,$attribute,$htmlOptions=array())
  4901. {
  4902. self::resolveNameID($model,$attribute,$htmlOptions);
  4903. self::clientChange('change',$htmlOptions);
  4904. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  4905. }
  4906. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  4907. {
  4908. self::resolveNameID($model,$attribute,$htmlOptions);
  4909. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  4910. }
  4911. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  4912. {
  4913. self::resolveNameID($model,$attribute,$htmlOptions);
  4914. self::clientChange('change',$htmlOptions);
  4915. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  4916. }
  4917. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  4918. {
  4919. self::resolveNameID($model,$attribute,$htmlOptions);
  4920. self::clientChange('change',$htmlOptions);
  4921. if($model->hasErrors($attribute))
  4922. self::addErrorCss($htmlOptions);
  4923. $text=self::resolveValue($model,$attribute);
  4924. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  4925. }
  4926. public static function activeFileField($model,$attribute,$htmlOptions=array())
  4927. {
  4928. self::resolveNameID($model,$attribute,$htmlOptions);
  4929. // add a hidden field so that if a model only has a file field, we can
  4930. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  4931. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4932. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  4933. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  4934. }
  4935. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  4936. {
  4937. self::resolveNameID($model,$attribute,$htmlOptions);
  4938. if(!isset($htmlOptions['value']))
  4939. $htmlOptions['value']=1;
  4940. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  4941. $htmlOptions['checked']='checked';
  4942. self::clientChange('click',$htmlOptions);
  4943. if(array_key_exists('uncheckValue',$htmlOptions))
  4944. {
  4945. $uncheck=$htmlOptions['uncheckValue'];
  4946. unset($htmlOptions['uncheckValue']);
  4947. }
  4948. else
  4949. $uncheck='0';
  4950. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4951. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  4952. // add a hidden field so that if the radio button is not selected, it still submits a value
  4953. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  4954. }
  4955. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  4956. {
  4957. self::resolveNameID($model,$attribute,$htmlOptions);
  4958. if(!isset($htmlOptions['value']))
  4959. $htmlOptions['value']=1;
  4960. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  4961. $htmlOptions['checked']='checked';
  4962. self::clientChange('click',$htmlOptions);
  4963. if(array_key_exists('uncheckValue',$htmlOptions))
  4964. {
  4965. $uncheck=$htmlOptions['uncheckValue'];
  4966. unset($htmlOptions['uncheckValue']);
  4967. }
  4968. else
  4969. $uncheck='0';
  4970. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4971. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  4972. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  4973. }
  4974. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  4975. {
  4976. self::resolveNameID($model,$attribute,$htmlOptions);
  4977. $selection=self::resolveValue($model,$attribute);
  4978. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  4979. self::clientChange('change',$htmlOptions);
  4980. if($model->hasErrors($attribute))
  4981. self::addErrorCss($htmlOptions);
  4982. if(isset($htmlOptions['multiple']))
  4983. {
  4984. if(substr($htmlOptions['name'],-2)!=='[]')
  4985. $htmlOptions['name'].='[]';
  4986. }
  4987. return self::tag('select',$htmlOptions,$options);
  4988. }
  4989. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  4990. {
  4991. if(!isset($htmlOptions['size']))
  4992. $htmlOptions['size']=4;
  4993. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  4994. }
  4995. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  4996. {
  4997. self::resolveNameID($model,$attribute,$htmlOptions);
  4998. $selection=self::resolveValue($model,$attribute);
  4999. if($model->hasErrors($attribute))
  5000. self::addErrorCss($htmlOptions);
  5001. $name=$htmlOptions['name'];
  5002. unset($htmlOptions['name']);
  5003. if(array_key_exists('uncheckValue',$htmlOptions))
  5004. {
  5005. $uncheck=$htmlOptions['uncheckValue'];
  5006. unset($htmlOptions['uncheckValue']);
  5007. }
  5008. else
  5009. $uncheck='';
  5010. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5011. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5012. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  5013. }
  5014. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  5015. {
  5016. self::resolveNameID($model,$attribute,$htmlOptions);
  5017. $selection=self::resolveValue($model,$attribute);
  5018. if($model->hasErrors($attribute))
  5019. self::addErrorCss($htmlOptions);
  5020. $name=$htmlOptions['name'];
  5021. unset($htmlOptions['name']);
  5022. if(array_key_exists('uncheckValue',$htmlOptions))
  5023. {
  5024. $uncheck=$htmlOptions['uncheckValue'];
  5025. unset($htmlOptions['uncheckValue']);
  5026. }
  5027. else
  5028. $uncheck='';
  5029. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5030. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5031. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  5032. }
  5033. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  5034. {
  5035. $content='';
  5036. if(!is_array($model))
  5037. $model=array($model);
  5038. if(isset($htmlOptions['firstError']))
  5039. {
  5040. $firstError=$htmlOptions['firstError'];
  5041. unset($htmlOptions['firstError']);
  5042. }
  5043. else
  5044. $firstError=false;
  5045. foreach($model as $m)
  5046. {
  5047. foreach($m->getErrors() as $errors)
  5048. {
  5049. foreach($errors as $error)
  5050. {
  5051. if($error!='')
  5052. $content.="<li>$error</li>\n";
  5053. if($firstError)
  5054. break;
  5055. }
  5056. }
  5057. }
  5058. if($content!=='')
  5059. {
  5060. if($header===null)
  5061. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5062. if(!isset($htmlOptions['class']))
  5063. $htmlOptions['class']=self::$errorSummaryCss;
  5064. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5065. }
  5066. else
  5067. return '';
  5068. }
  5069. public static function error($model,$attribute,$htmlOptions=array())
  5070. {
  5071. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5072. $error=$model->getError($attribute);
  5073. if($error!='')
  5074. {
  5075. if(!isset($htmlOptions['class']))
  5076. $htmlOptions['class']=self::$errorMessageCss;
  5077. return self::tag('div',$htmlOptions,$error);
  5078. }
  5079. else
  5080. return '';
  5081. }
  5082. public static function listData($models,$valueField,$textField,$groupField='')
  5083. {
  5084. $listData=array();
  5085. if($groupField==='')
  5086. {
  5087. foreach($models as $model)
  5088. {
  5089. $value=self::value($model,$valueField);
  5090. $text=self::value($model,$textField);
  5091. $listData[$value]=$text;
  5092. }
  5093. }
  5094. else
  5095. {
  5096. foreach($models as $model)
  5097. {
  5098. $group=self::value($model,$groupField);
  5099. $value=self::value($model,$valueField);
  5100. $text=self::value($model,$textField);
  5101. $listData[$group][$value]=$text;
  5102. }
  5103. }
  5104. return $listData;
  5105. }
  5106. public static function value($model,$attribute,$defaultValue=null)
  5107. {
  5108. foreach(explode('.',$attribute) as $name)
  5109. {
  5110. if(is_object($model))
  5111. $model=$model->$name;
  5112. else if(is_array($model) && isset($model[$name]))
  5113. $model=$model[$name];
  5114. else
  5115. return $defaultValue;
  5116. }
  5117. return $model;
  5118. }
  5119. public static function getIdByName($name)
  5120. {
  5121. return str_replace(array('[]', '][', '[', ']'), array('', '_', '_', ''), $name);
  5122. }
  5123. public static function activeId($model,$attribute)
  5124. {
  5125. return self::getIdByName(self::activeName($model,$attribute));
  5126. }
  5127. public static function activeName($model,$attribute)
  5128. {
  5129. $a=$attribute; // because the attribute name may be changed by resolveName
  5130. return self::resolveName($model,$a);
  5131. }
  5132. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5133. {
  5134. $htmlOptions['type']=$type;
  5135. if($type==='text' || $type==='password')
  5136. {
  5137. if(!isset($htmlOptions['maxlength']))
  5138. {
  5139. foreach($model->getValidators($attribute) as $validator)
  5140. {
  5141. if($validator instanceof CStringValidator && $validator->max!==null)
  5142. {
  5143. $htmlOptions['maxlength']=$validator->max;
  5144. break;
  5145. }
  5146. }
  5147. }
  5148. else if($htmlOptions['maxlength']===false)
  5149. unset($htmlOptions['maxlength']);
  5150. }
  5151. if($type==='file')
  5152. unset($htmlOptions['value']);
  5153. else if(!isset($htmlOptions['value']))
  5154. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5155. if($model->hasErrors($attribute))
  5156. self::addErrorCss($htmlOptions);
  5157. return self::tag('input',$htmlOptions);
  5158. }
  5159. public static function listOptions($selection,$listData,&$htmlOptions)
  5160. {
  5161. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5162. $content='';
  5163. if(isset($htmlOptions['prompt']))
  5164. {
  5165. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5166. unset($htmlOptions['prompt']);
  5167. }
  5168. if(isset($htmlOptions['empty']))
  5169. {
  5170. if(!is_array($htmlOptions['empty']))
  5171. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5172. foreach($htmlOptions['empty'] as $value=>$label)
  5173. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5174. unset($htmlOptions['empty']);
  5175. }
  5176. if(isset($htmlOptions['options']))
  5177. {
  5178. $options=$htmlOptions['options'];
  5179. unset($htmlOptions['options']);
  5180. }
  5181. else
  5182. $options=array();
  5183. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  5184. if(is_array($selection))
  5185. {
  5186. foreach($selection as $i=>$item)
  5187. {
  5188. if(is_object($item))
  5189. $selection[$i]=$item->$key;
  5190. }
  5191. }
  5192. else if(is_object($selection))
  5193. $selection=$selection->$key;
  5194. foreach($listData as $key=>$value)
  5195. {
  5196. if(is_array($value))
  5197. {
  5198. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  5199. $dummy=array('options'=>$options);
  5200. if(isset($htmlOptions['encode']))
  5201. $dummy['encode']=$htmlOptions['encode'];
  5202. $content.=self::listOptions($selection,$value,$dummy);
  5203. $content.='</optgroup>'."\n";
  5204. }
  5205. else
  5206. {
  5207. $attributes=array('value'=>(string)$key, 'encode'=>!$raw);
  5208. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  5209. $attributes['selected']='selected';
  5210. if(isset($options[$key]))
  5211. $attributes=array_merge($attributes,$options[$key]);
  5212. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  5213. }
  5214. }
  5215. unset($htmlOptions['key']);
  5216. return $content;
  5217. }
  5218. protected static function clientChange($event,&$htmlOptions)
  5219. {
  5220. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  5221. return;
  5222. if(isset($htmlOptions['live']))
  5223. {
  5224. $live=$htmlOptions['live'];
  5225. unset($htmlOptions['live']);
  5226. }
  5227. else
  5228. $live = self::$liveEvents;
  5229. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  5230. $return='return true';
  5231. else
  5232. $return='return false';
  5233. if(isset($htmlOptions['on'.$event]))
  5234. {
  5235. $handler=trim($htmlOptions['on'.$event],';').';';
  5236. unset($htmlOptions['on'.$event]);
  5237. }
  5238. else
  5239. $handler='';
  5240. if(isset($htmlOptions['id']))
  5241. $id=$htmlOptions['id'];
  5242. else
  5243. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  5244. $cs=Yii::app()->getClientScript();
  5245. $cs->registerCoreScript('jquery');
  5246. if(isset($htmlOptions['submit']))
  5247. {
  5248. $cs->registerCoreScript('yii');
  5249. $request=Yii::app()->getRequest();
  5250. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  5251. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  5252. if(isset($htmlOptions['params']))
  5253. $params=CJavaScript::encode($htmlOptions['params']);
  5254. else
  5255. $params='{}';
  5256. if($htmlOptions['submit']!=='')
  5257. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  5258. else
  5259. $url='';
  5260. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  5261. }
  5262. if(isset($htmlOptions['ajax']))
  5263. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  5264. if(isset($htmlOptions['confirm']))
  5265. {
  5266. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  5267. if($handler!=='')
  5268. $handler="if($confirm) {".$handler."} else return false;";
  5269. else
  5270. $handler="return $confirm;";
  5271. }
  5272. if($live)
  5273. $cs->registerScript('Yii.CHtml.#' . $id, "$('body').on('$event','#$id',function(){{$handler}});");
  5274. else
  5275. $cs->registerScript('Yii.CHtml.#' . $id, "$('#$id').on('$event', function(){{$handler}});");
  5276. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  5277. }
  5278. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  5279. {
  5280. if(!isset($htmlOptions['name']))
  5281. $htmlOptions['name']=self::resolveName($model,$attribute);
  5282. if(!isset($htmlOptions['id']))
  5283. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  5284. else if($htmlOptions['id']===false)
  5285. unset($htmlOptions['id']);
  5286. }
  5287. public static function resolveName($model,&$attribute)
  5288. {
  5289. if(($pos=strpos($attribute,'['))!==false)
  5290. {
  5291. if($pos!==0) // e.g. name[a][b]
  5292. return get_class($model).'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5293. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5294. {
  5295. $sub=substr($attribute,0,$pos+1);
  5296. $attribute=substr($attribute,$pos+1);
  5297. return get_class($model).$sub.'['.$attribute.']';
  5298. }
  5299. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5300. {
  5301. $name=get_class($model).'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5302. $attribute=$matches[1];
  5303. return $name;
  5304. }
  5305. }
  5306. return get_class($model).'['.$attribute.']';
  5307. }
  5308. public static function resolveValue($model,$attribute)
  5309. {
  5310. if(($pos=strpos($attribute,'['))!==false)
  5311. {
  5312. if($pos===0) // [a]name[b][c], should ignore [a]
  5313. {
  5314. if(preg_match('/\](\w+)/',$attribute,$matches))
  5315. $attribute=$matches[1];
  5316. if(($pos=strpos($attribute,'['))===false)
  5317. return $model->$attribute;
  5318. }
  5319. $name=substr($attribute,0,$pos);
  5320. $value=$model->$name;
  5321. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5322. {
  5323. if(is_array($value) && isset($value[$id]))
  5324. $value=$value[$id];
  5325. else
  5326. return null;
  5327. }
  5328. return $value;
  5329. }
  5330. else
  5331. return $model->$attribute;
  5332. }
  5333. protected static function addErrorCss(&$htmlOptions)
  5334. {
  5335. if(isset($htmlOptions['class']))
  5336. $htmlOptions['class'].=' '.self::$errorCss;
  5337. else
  5338. $htmlOptions['class']=self::$errorCss;
  5339. }
  5340. public static function renderAttributes($htmlOptions)
  5341. {
  5342. static $specialAttributes=array(
  5343. 'checked'=>1,
  5344. 'declare'=>1,
  5345. 'defer'=>1,
  5346. 'disabled'=>1,
  5347. 'ismap'=>1,
  5348. 'multiple'=>1,
  5349. 'nohref'=>1,
  5350. 'noresize'=>1,
  5351. 'readonly'=>1,
  5352. 'selected'=>1,
  5353. );
  5354. if($htmlOptions===array())
  5355. return '';
  5356. $html='';
  5357. if(isset($htmlOptions['encode']))
  5358. {
  5359. $raw=!$htmlOptions['encode'];
  5360. unset($htmlOptions['encode']);
  5361. }
  5362. else
  5363. $raw=false;
  5364. if($raw)
  5365. {
  5366. foreach($htmlOptions as $name=>$value)
  5367. {
  5368. if(isset($specialAttributes[$name]))
  5369. {
  5370. if($value)
  5371. $html .= ' ' . $name . '="' . $name . '"';
  5372. }
  5373. else if($value!==null)
  5374. $html .= ' ' . $name . '="' . $value . '"';
  5375. }
  5376. }
  5377. else
  5378. {
  5379. foreach($htmlOptions as $name=>$value)
  5380. {
  5381. if(isset($specialAttributes[$name]))
  5382. {
  5383. if($value)
  5384. $html .= ' ' . $name . '="' . $name . '"';
  5385. }
  5386. else if($value!==null)
  5387. $html .= ' ' . $name . '="' . self::encode($value) . '"';
  5388. }
  5389. }
  5390. return $html;
  5391. }
  5392. }
  5393. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  5394. {
  5395. public $enableSkin=false;
  5396. public $widgets=array();
  5397. public $skinnableWidgets;
  5398. public $skinPath;
  5399. private $_skins=array(); // class name, skin name, property name => value
  5400. public function init()
  5401. {
  5402. parent::init();
  5403. if($this->enableSkin && $this->skinPath===null)
  5404. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  5405. }
  5406. public function createWidget($owner,$className,$properties=array())
  5407. {
  5408. $className=Yii::import($className,true);
  5409. $widget=new $className($owner);
  5410. if(isset($this->widgets[$className]))
  5411. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  5412. if($this->enableSkin)
  5413. {
  5414. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  5415. {
  5416. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  5417. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  5418. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  5419. }
  5420. }
  5421. foreach($properties as $name=>$value)
  5422. $widget->$name=$value;
  5423. return $widget;
  5424. }
  5425. protected function getSkin($className,$skinName)
  5426. {
  5427. if(!isset($this->_skins[$className][$skinName]))
  5428. {
  5429. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  5430. if(is_file($skinFile))
  5431. $this->_skins[$className]=require($skinFile);
  5432. else
  5433. $this->_skins[$className]=array();
  5434. if(($theme=Yii::app()->getTheme())!==null)
  5435. {
  5436. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  5437. if(is_file($skinFile))
  5438. {
  5439. $skins=require($skinFile);
  5440. foreach($skins as $name=>$skin)
  5441. $this->_skins[$className][$name]=$skin;
  5442. }
  5443. }
  5444. if(!isset($this->_skins[$className][$skinName]))
  5445. $this->_skins[$className][$skinName]=array();
  5446. }
  5447. return $this->_skins[$className][$skinName];
  5448. }
  5449. }
  5450. class CWidget extends CBaseController
  5451. {
  5452. public $actionPrefix;
  5453. public $skin='default';
  5454. private static $_viewPaths;
  5455. private static $_counter=0;
  5456. private $_id;
  5457. private $_owner;
  5458. public static function actions()
  5459. {
  5460. return array();
  5461. }
  5462. public function __construct($owner=null)
  5463. {
  5464. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  5465. }
  5466. public function getOwner()
  5467. {
  5468. return $this->_owner;
  5469. }
  5470. public function getId($autoGenerate=true)
  5471. {
  5472. if($this->_id!==null)
  5473. return $this->_id;
  5474. else if($autoGenerate)
  5475. return $this->_id='yw'.self::$_counter++;
  5476. }
  5477. public function setId($value)
  5478. {
  5479. $this->_id=$value;
  5480. }
  5481. public function getController()
  5482. {
  5483. if($this->_owner instanceof CController)
  5484. return $this->_owner;
  5485. else
  5486. return Yii::app()->getController();
  5487. }
  5488. public function init()
  5489. {
  5490. }
  5491. public function run()
  5492. {
  5493. }
  5494. public function getViewPath($checkTheme=false)
  5495. {
  5496. $className=get_class($this);
  5497. if(isset(self::$_viewPaths[$className]))
  5498. return self::$_viewPaths[$className];
  5499. else
  5500. {
  5501. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  5502. {
  5503. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  5504. if(strpos($className,'\\')!==false) // namespaced class
  5505. $path.=str_replace('\\','_',ltrim($className,'\\'));
  5506. else
  5507. $path.=$className;
  5508. if(is_dir($path))
  5509. return self::$_viewPaths[$className]=$path;
  5510. }
  5511. $class=new ReflectionClass($className);
  5512. return self::$_viewPaths[$className]=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  5513. }
  5514. }
  5515. public function getViewFile($viewName)
  5516. {
  5517. if(($renderer=Yii::app()->getViewRenderer())!==null)
  5518. $extension=$renderer->fileExtension;
  5519. else
  5520. $extension='.php';
  5521. if(strpos($viewName,'.')) // a path alias
  5522. $viewFile=Yii::getPathOfAlias($viewName);
  5523. else
  5524. {
  5525. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  5526. if(is_file($viewFile.$extension))
  5527. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5528. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5529. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5530. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  5531. }
  5532. if(is_file($viewFile.$extension))
  5533. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5534. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5535. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5536. else
  5537. return false;
  5538. }
  5539. public function render($view,$data=null,$return=false)
  5540. {
  5541. if(($viewFile=$this->getViewFile($view))!==false)
  5542. return $this->renderFile($viewFile,$data,$return);
  5543. else
  5544. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  5545. array('{widget}'=>get_class($this), '{view}'=>$view)));
  5546. }
  5547. }
  5548. abstract class CMessageSource extends CApplicationComponent
  5549. {
  5550. public $forceTranslation=false;
  5551. private $_language;
  5552. private $_messages=array();
  5553. abstract protected function loadMessages($category,$language);
  5554. public function getLanguage()
  5555. {
  5556. return $this->_language===null ? Yii::app()->sourceLanguage : $this->_language;
  5557. }
  5558. public function setLanguage($language)
  5559. {
  5560. $this->_language=CLocale::getCanonicalID($language);
  5561. }
  5562. public function translate($category,$message,$language=null)
  5563. {
  5564. if($language===null)
  5565. $language=Yii::app()->getLanguage();
  5566. if($this->forceTranslation || $language!==$this->getLanguage())
  5567. return $this->translateMessage($category,$message,$language);
  5568. else
  5569. return $message;
  5570. }
  5571. protected function translateMessage($category,$message,$language)
  5572. {
  5573. $key=$language.'.'.$category;
  5574. if(!isset($this->_messages[$key]))
  5575. $this->_messages[$key]=$this->loadMessages($category,$language);
  5576. if(isset($this->_messages[$key][$message]) && $this->_messages[$key][$message]!=='')
  5577. return $this->_messages[$key][$message];
  5578. else if($this->hasEventHandler('onMissingTranslation'))
  5579. {
  5580. $event=new CMissingTranslationEvent($this,$category,$message,$language);
  5581. $this->onMissingTranslation($event);
  5582. return $event->message;
  5583. }
  5584. else
  5585. return $message;
  5586. }
  5587. public function onMissingTranslation($event)
  5588. {
  5589. $this->raiseEvent('onMissingTranslation',$event);
  5590. }
  5591. }
  5592. class CMissingTranslationEvent extends CEvent
  5593. {
  5594. public $message;
  5595. public $category;
  5596. public $language;
  5597. public function __construct($sender,$category,$message,$language)
  5598. {
  5599. parent::__construct($sender);
  5600. $this->message=$message;
  5601. $this->category=$category;
  5602. $this->language=$language;
  5603. }
  5604. }
  5605. class CPhpMessageSource extends CMessageSource
  5606. {
  5607. const CACHE_KEY_PREFIX='Yii.CPhpMessageSource.';
  5608. public $cachingDuration=0;
  5609. public $cacheID='cache';
  5610. public $basePath;
  5611. private $_files=array();
  5612. public function init()
  5613. {
  5614. parent::init();
  5615. if($this->basePath===null)
  5616. $this->basePath=Yii::getPathOfAlias('application.messages');
  5617. }
  5618. protected function getMessageFile($category,$language)
  5619. {
  5620. if(!isset($this->_files[$category][$language]))
  5621. {
  5622. if(($pos=strpos($category,'.'))!==false)
  5623. {
  5624. $moduleClass=substr($category,0,$pos);
  5625. $moduleCategory=substr($category,$pos+1);
  5626. $class=new ReflectionClass($moduleClass);
  5627. $this->_files[$category][$language]=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'messages'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.$moduleCategory.'.php';
  5628. }
  5629. else
  5630. $this->_files[$category][$language]=$this->basePath.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.$category.'.php';
  5631. }
  5632. return $this->_files[$category][$language];
  5633. }
  5634. protected function loadMessages($category,$language)
  5635. {
  5636. $messageFile=$this->getMessageFile($category,$language);
  5637. if($this->cachingDuration>0 && $this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  5638. {
  5639. $key=self::CACHE_KEY_PREFIX . $messageFile;
  5640. if(($data=$cache->get($key))!==false)
  5641. return unserialize($data);
  5642. }
  5643. if(is_file($messageFile))
  5644. {
  5645. $messages=include($messageFile);
  5646. if(!is_array($messages))
  5647. $messages=array();
  5648. if(isset($cache))
  5649. {
  5650. $dependency=new CFileCacheDependency($messageFile);
  5651. $cache->set($key,serialize($messages),$this->cachingDuration,$dependency);
  5652. }
  5653. return $messages;
  5654. }
  5655. else
  5656. return array();
  5657. }
  5658. }
  5659. class CLocale extends CComponent
  5660. {
  5661. public static $dataPath;
  5662. private $_id;
  5663. private $_data;
  5664. private $_dateFormatter;
  5665. private $_numberFormatter;
  5666. public static function getInstance($id)
  5667. {
  5668. static $locales=array();
  5669. if(isset($locales[$id]))
  5670. return $locales[$id];
  5671. else
  5672. return $locales[$id]=new CLocale($id);
  5673. }
  5674. public static function getLocaleIDs()
  5675. {
  5676. static $locales;
  5677. if($locales===null)
  5678. {
  5679. $locales=array();
  5680. $dataPath=self::$dataPath===null ? dirname(__FILE__).DIRECTORY_SEPARATOR.'data' : self::$dataPath;
  5681. $folder=@opendir($dataPath);
  5682. while(($file=@readdir($folder))!==false)
  5683. {
  5684. $fullPath=$dataPath.DIRECTORY_SEPARATOR.$file;
  5685. if(substr($file,-4)==='.php' && is_file($fullPath))
  5686. $locales[]=substr($file,0,-4);
  5687. }
  5688. closedir($folder);
  5689. sort($locales);
  5690. }
  5691. return $locales;
  5692. }
  5693. protected function __construct($id)
  5694. {
  5695. $this->_id=self::getCanonicalID($id);
  5696. $dataPath=self::$dataPath===null ? dirname(__FILE__).DIRECTORY_SEPARATOR.'data' : self::$dataPath;
  5697. $dataFile=$dataPath.DIRECTORY_SEPARATOR.$this->_id.'.php';
  5698. if(is_file($dataFile))
  5699. $this->_data=require($dataFile);
  5700. else
  5701. throw new CException(Yii::t('yii','Unrecognized locale "{locale}".',array('{locale}'=>$id)));
  5702. }
  5703. public static function getCanonicalID($id)
  5704. {
  5705. return strtolower(str_replace('-','_',$id));
  5706. }
  5707. public function getId()
  5708. {
  5709. return $this->_id;
  5710. }
  5711. public function getNumberFormatter()
  5712. {
  5713. if($this->_numberFormatter===null)
  5714. $this->_numberFormatter=new CNumberFormatter($this);
  5715. return $this->_numberFormatter;
  5716. }
  5717. public function getDateFormatter()
  5718. {
  5719. if($this->_dateFormatter===null)
  5720. $this->_dateFormatter=new CDateFormatter($this);
  5721. return $this->_dateFormatter;
  5722. }
  5723. public function getCurrencySymbol($currency)
  5724. {
  5725. return isset($this->_data['currencySymbols'][$currency]) ? $this->_data['currencySymbols'][$currency] : null;
  5726. }
  5727. public function getNumberSymbol($name)
  5728. {
  5729. return isset($this->_data['numberSymbols'][$name]) ? $this->_data['numberSymbols'][$name] : null;
  5730. }
  5731. public function getDecimalFormat()
  5732. {
  5733. return $this->_data['decimalFormat'];
  5734. }
  5735. public function getCurrencyFormat()
  5736. {
  5737. return $this->_data['currencyFormat'];
  5738. }
  5739. public function getPercentFormat()
  5740. {
  5741. return $this->_data['percentFormat'];
  5742. }
  5743. public function getScientificFormat()
  5744. {
  5745. return $this->_data['scientificFormat'];
  5746. }
  5747. public function getMonthName($month,$width='wide',$standAlone=false)
  5748. {
  5749. if($standAlone)
  5750. return isset($this->_data['monthNamesSA'][$width][$month]) ? $this->_data['monthNamesSA'][$width][$month] : $this->_data['monthNames'][$width][$month];
  5751. else
  5752. return isset($this->_data['monthNames'][$width][$month]) ? $this->_data['monthNames'][$width][$month] : $this->_data['monthNamesSA'][$width][$month];
  5753. }
  5754. public function getMonthNames($width='wide',$standAlone=false)
  5755. {
  5756. if($standAlone)
  5757. return isset($this->_data['monthNamesSA'][$width]) ? $this->_data['monthNamesSA'][$width] : $this->_data['monthNames'][$width];
  5758. else
  5759. return isset($this->_data['monthNames'][$width]) ? $this->_data['monthNames'][$width] : $this->_data['monthNamesSA'][$width];
  5760. }
  5761. public function getWeekDayName($day,$width='wide',$standAlone=false)
  5762. {
  5763. if($standAlone)
  5764. return isset($this->_data['weekDayNamesSA'][$width][$day]) ? $this->_data['weekDayNamesSA'][$width][$day] : $this->_data['weekDayNames'][$width][$day];
  5765. else
  5766. return isset($this->_data['weekDayNames'][$width][$day]) ? $this->_data['weekDayNames'][$width][$day] : $this->_data['weekDayNamesSA'][$width][$day];
  5767. }
  5768. public function getWeekDayNames($width='wide',$standAlone=false)
  5769. {
  5770. if($standAlone)
  5771. return isset($this->_data['weekDayNamesSA'][$width]) ? $this->_data['weekDayNamesSA'][$width] : $this->_data['weekDayNames'][$width];
  5772. else
  5773. return isset($this->_data['weekDayNames'][$width]) ? $this->_data['weekDayNames'][$width] : $this->_data['weekDayNamesSA'][$width];
  5774. }
  5775. public function getEraName($era,$width='wide')
  5776. {
  5777. return $this->_data['eraNames'][$width][$era];
  5778. }
  5779. public function getAMName()
  5780. {
  5781. return $this->_data['amName'];
  5782. }
  5783. public function getPMName()
  5784. {
  5785. return $this->_data['pmName'];
  5786. }
  5787. public function getDateFormat($width='medium')
  5788. {
  5789. return $this->_data['dateFormats'][$width];
  5790. }
  5791. public function getTimeFormat($width='medium')
  5792. {
  5793. return $this->_data['timeFormats'][$width];
  5794. }
  5795. public function getDateTimeFormat()
  5796. {
  5797. return $this->_data['dateTimeFormat'];
  5798. }
  5799. public function getOrientation()
  5800. {
  5801. return isset($this->_data['orientation']) ? $this->_data['orientation'] : 'ltr';
  5802. }
  5803. public function getPluralRules()
  5804. {
  5805. return isset($this->_data['pluralRules']) ? $this->_data['pluralRules'] : array();
  5806. }
  5807. public function getLanguageID($id)
  5808. {
  5809. // normalize id
  5810. $id = $this->getCanonicalID($id);
  5811. // remove sub tags
  5812. if(($underscorePosition=strpos($id, '_'))!== false)
  5813. {
  5814. $id = substr($id, 0, $underscorePosition);
  5815. }
  5816. return $id;
  5817. }
  5818. public function getScriptID($id)
  5819. {
  5820. // normalize id
  5821. $id = $this->getCanonicalID($id);
  5822. // find sub tags
  5823. if(($underscorePosition=strpos($id, '_'))!==false)
  5824. {
  5825. $subTag = explode('_', $id);
  5826. // script sub tags can be distigused from territory sub tags by length
  5827. if (strlen($subTag[1])===4)
  5828. {
  5829. $id = $subTag[1];
  5830. }
  5831. else
  5832. {
  5833. $id = null;
  5834. }
  5835. }
  5836. else
  5837. {
  5838. $id = null;
  5839. }
  5840. return $id;
  5841. }
  5842. public function getTerritoryID($id)
  5843. {
  5844. // normalize id
  5845. $id = $this->getCanonicalID($id);
  5846. // find sub tags
  5847. if (($underscorePosition=strpos($id, '_'))!== false)
  5848. {
  5849. $subTag = explode('_', $id);
  5850. // territory sub tags can be distigused from script sub tags by length
  5851. if (strlen($subTag[1])<4)
  5852. {
  5853. $id = $subTag[1];
  5854. }
  5855. else
  5856. {
  5857. $id = null;
  5858. }
  5859. }
  5860. else
  5861. {
  5862. $id = null;
  5863. }
  5864. return $id;
  5865. }
  5866. public function getLocaleDisplayName($id=null, $category='languages')
  5867. {
  5868. $id = $this->getCanonicalID($id);
  5869. if (isset($this->_data[$category][$id]))
  5870. {
  5871. return $this->_data[$category][$id];
  5872. }
  5873. else if (($category == 'languages') && ($id=$this->getLanguageID($id)) && (isset($this->_data[$category][$id])))
  5874. {
  5875. return $this->_data[$category][$id];
  5876. }
  5877. else if (($category == 'scripts') && ($id=$this->getScriptID($id)) && (isset($this->_data[$category][$id])))
  5878. {
  5879. return $this->_data[$category][$id];
  5880. }
  5881. else if (($category == 'territories') && ($id=$this->getTerritoryID($id)) && (isset($this->_data[$category][$id])))
  5882. {
  5883. return $this->_data[$category][$id];
  5884. }
  5885. else {
  5886. return null;
  5887. }
  5888. }
  5889. public function getLanguage($id)
  5890. {
  5891. return $this->getLocaleDisplayName($id, 'languages');
  5892. }
  5893. public function getScript($id)
  5894. {
  5895. return $this->getLocaleDisplayName($id, 'scripts');
  5896. }
  5897. public function getTerritory($id)
  5898. {
  5899. return $this->getLocaleDisplayName($id, 'territories');
  5900. }
  5901. }
  5902. class CClientScript extends CApplicationComponent
  5903. {
  5904. const POS_HEAD=0;
  5905. const POS_BEGIN=1;
  5906. const POS_END=2;
  5907. const POS_LOAD=3;
  5908. const POS_READY=4;
  5909. public $enableJavaScript=true;
  5910. public $scriptMap=array();
  5911. public $packages=array();
  5912. public $corePackages;
  5913. protected $cssFiles=array();
  5914. protected $scriptFiles=array();
  5915. protected $scripts=array();
  5916. protected $metaTags=array();
  5917. protected $linkTags=array();
  5918. protected $css=array();
  5919. protected $hasScripts=false;
  5920. protected $coreScripts=array();
  5921. public $coreScriptPosition=self::POS_HEAD;
  5922. private $_baseUrl;
  5923. public function reset()
  5924. {
  5925. $this->hasScripts=false;
  5926. $this->coreScripts=array();
  5927. $this->cssFiles=array();
  5928. $this->css=array();
  5929. $this->scriptFiles=array();
  5930. $this->scripts=array();
  5931. $this->metaTags=array();
  5932. $this->linkTags=array();
  5933. $this->recordCachingAction('clientScript','reset',array());
  5934. }
  5935. public function render(&$output)
  5936. {
  5937. if(!$this->hasScripts)
  5938. return;
  5939. $this->renderCoreScripts();
  5940. if(!empty($this->scriptMap))
  5941. $this->remapScripts();
  5942. $this->unifyScripts();
  5943. $this->renderHead($output);
  5944. if($this->enableJavaScript)
  5945. {
  5946. $this->renderBodyBegin($output);
  5947. $this->renderBodyEnd($output);
  5948. }
  5949. }
  5950. protected function unifyScripts()
  5951. {
  5952. if(!$this->enableJavaScript)
  5953. return;
  5954. $map=array();
  5955. if(isset($this->scriptFiles[self::POS_HEAD]))
  5956. $map=$this->scriptFiles[self::POS_HEAD];
  5957. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5958. {
  5959. foreach($this->scriptFiles[self::POS_BEGIN] as $key=>$scriptFile)
  5960. {
  5961. if(isset($map[$scriptFile]))
  5962. unset($this->scriptFiles[self::POS_BEGIN][$key]);
  5963. else
  5964. $map[$scriptFile]=true;
  5965. }
  5966. }
  5967. if(isset($this->scriptFiles[self::POS_END]))
  5968. {
  5969. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  5970. {
  5971. if(isset($map[$scriptFile]))
  5972. unset($this->scriptFiles[self::POS_END][$key]);
  5973. }
  5974. }
  5975. }
  5976. protected function remapScripts()
  5977. {
  5978. $cssFiles=array();
  5979. foreach($this->cssFiles as $url=>$media)
  5980. {
  5981. $name=basename($url);
  5982. if(isset($this->scriptMap[$name]))
  5983. {
  5984. if($this->scriptMap[$name]!==false)
  5985. $cssFiles[$this->scriptMap[$name]]=$media;
  5986. }
  5987. else if(isset($this->scriptMap['*.css']))
  5988. {
  5989. if($this->scriptMap['*.css']!==false)
  5990. $cssFiles[$this->scriptMap['*.css']]=$media;
  5991. }
  5992. else
  5993. $cssFiles[$url]=$media;
  5994. }
  5995. $this->cssFiles=$cssFiles;
  5996. $jsFiles=array();
  5997. foreach($this->scriptFiles as $position=>$scripts)
  5998. {
  5999. $jsFiles[$position]=array();
  6000. foreach($scripts as $key=>$script)
  6001. {
  6002. $name=basename($script);
  6003. if(isset($this->scriptMap[$name]))
  6004. {
  6005. if($this->scriptMap[$name]!==false)
  6006. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  6007. }
  6008. else if(isset($this->scriptMap['*.js']))
  6009. {
  6010. if($this->scriptMap['*.js']!==false)
  6011. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  6012. }
  6013. else
  6014. $jsFiles[$position][$key]=$script;
  6015. }
  6016. }
  6017. $this->scriptFiles=$jsFiles;
  6018. }
  6019. public function renderCoreScripts()
  6020. {
  6021. if($this->coreScripts===null)
  6022. return;
  6023. $cssFiles=array();
  6024. $jsFiles=array();
  6025. foreach($this->coreScripts as $name=>$package)
  6026. {
  6027. $baseUrl=$this->getPackageBaseUrl($name);
  6028. if(!empty($package['js']))
  6029. {
  6030. foreach($package['js'] as $js)
  6031. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  6032. }
  6033. if(!empty($package['css']))
  6034. {
  6035. foreach($package['css'] as $css)
  6036. $cssFiles[$baseUrl.'/'.$css]='';
  6037. }
  6038. }
  6039. // merge in place
  6040. if($cssFiles!==array())
  6041. {
  6042. foreach($this->cssFiles as $cssFile=>$media)
  6043. $cssFiles[$cssFile]=$media;
  6044. $this->cssFiles=$cssFiles;
  6045. }
  6046. if($jsFiles!==array())
  6047. {
  6048. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  6049. {
  6050. foreach($this->scriptFiles[$this->coreScriptPosition] as $url)
  6051. $jsFiles[$url]=$url;
  6052. }
  6053. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  6054. }
  6055. }
  6056. public function renderHead(&$output)
  6057. {
  6058. $html='';
  6059. foreach($this->metaTags as $meta)
  6060. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  6061. foreach($this->linkTags as $link)
  6062. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  6063. foreach($this->cssFiles as $url=>$media)
  6064. $html.=CHtml::cssFile($url,$media)."\n";
  6065. foreach($this->css as $css)
  6066. $html.=CHtml::css($css[0],$css[1])."\n";
  6067. if($this->enableJavaScript)
  6068. {
  6069. if(isset($this->scriptFiles[self::POS_HEAD]))
  6070. {
  6071. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFile)
  6072. $html.=CHtml::scriptFile($scriptFile)."\n";
  6073. }
  6074. if(isset($this->scripts[self::POS_HEAD]))
  6075. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_HEAD]))."\n";
  6076. }
  6077. if($html!=='')
  6078. {
  6079. $count=0;
  6080. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  6081. if($count)
  6082. $output=str_replace('<###head###>',$html,$output);
  6083. else
  6084. $output=$html.$output;
  6085. }
  6086. }
  6087. public function renderBodyBegin(&$output)
  6088. {
  6089. $html='';
  6090. if(isset($this->scriptFiles[self::POS_BEGIN]))
  6091. {
  6092. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile)
  6093. $html.=CHtml::scriptFile($scriptFile)."\n";
  6094. }
  6095. if(isset($this->scripts[self::POS_BEGIN]))
  6096. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_BEGIN]))."\n";
  6097. if($html!=='')
  6098. {
  6099. $count=0;
  6100. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  6101. if($count)
  6102. $output=str_replace('<###begin###>',$html,$output);
  6103. else
  6104. $output=$html.$output;
  6105. }
  6106. }
  6107. public function renderBodyEnd(&$output)
  6108. {
  6109. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  6110. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  6111. return;
  6112. $fullPage=0;
  6113. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  6114. $html='';
  6115. if(isset($this->scriptFiles[self::POS_END]))
  6116. {
  6117. foreach($this->scriptFiles[self::POS_END] as $scriptFile)
  6118. $html.=CHtml::scriptFile($scriptFile)."\n";
  6119. }
  6120. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  6121. if(isset($this->scripts[self::POS_READY]))
  6122. {
  6123. if($fullPage)
  6124. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  6125. else
  6126. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  6127. }
  6128. if(isset($this->scripts[self::POS_LOAD]))
  6129. {
  6130. if($fullPage)
  6131. $scripts[]="jQuery(window).load(function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  6132. else
  6133. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  6134. }
  6135. if(!empty($scripts))
  6136. $html.=CHtml::script(implode("\n",$scripts))."\n";
  6137. if($fullPage)
  6138. $output=str_replace('<###end###>',$html,$output);
  6139. else
  6140. $output=$output.$html;
  6141. }
  6142. public function getCoreScriptUrl()
  6143. {
  6144. if($this->_baseUrl!==null)
  6145. return $this->_baseUrl;
  6146. else
  6147. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  6148. }
  6149. public function setCoreScriptUrl($value)
  6150. {
  6151. $this->_baseUrl=$value;
  6152. }
  6153. public function getPackageBaseUrl($name)
  6154. {
  6155. if(!isset($this->coreScripts[$name]))
  6156. return false;
  6157. $package=$this->coreScripts[$name];
  6158. if(isset($package['baseUrl']))
  6159. {
  6160. $baseUrl=$package['baseUrl'];
  6161. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  6162. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  6163. $baseUrl=rtrim($baseUrl,'/');
  6164. }
  6165. else if(isset($package['basePath']))
  6166. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  6167. else
  6168. $baseUrl=$this->getCoreScriptUrl();
  6169. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  6170. }
  6171. public function registerPackage($name)
  6172. {
  6173. return $this->registerCoreScript($name);
  6174. }
  6175. public function registerCoreScript($name)
  6176. {
  6177. if(isset($this->coreScripts[$name]))
  6178. return $this;
  6179. if(isset($this->packages[$name]))
  6180. $package=$this->packages[$name];
  6181. else
  6182. {
  6183. if($this->corePackages===null)
  6184. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  6185. if(isset($this->corePackages[$name]))
  6186. $package=$this->corePackages[$name];
  6187. }
  6188. if(isset($package))
  6189. {
  6190. if(!empty($package['depends']))
  6191. {
  6192. foreach($package['depends'] as $p)
  6193. $this->registerCoreScript($p);
  6194. }
  6195. $this->coreScripts[$name]=$package;
  6196. $this->hasScripts=true;
  6197. $params=func_get_args();
  6198. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  6199. }
  6200. return $this;
  6201. }
  6202. public function registerCssFile($url,$media='')
  6203. {
  6204. $this->hasScripts=true;
  6205. $this->cssFiles[$url]=$media;
  6206. $params=func_get_args();
  6207. $this->recordCachingAction('clientScript','registerCssFile',$params);
  6208. return $this;
  6209. }
  6210. public function registerCss($id,$css,$media='')
  6211. {
  6212. $this->hasScripts=true;
  6213. $this->css[$id]=array($css,$media);
  6214. $params=func_get_args();
  6215. $this->recordCachingAction('clientScript','registerCss',$params);
  6216. return $this;
  6217. }
  6218. public function registerScriptFile($url,$position=self::POS_HEAD)
  6219. {
  6220. $this->hasScripts=true;
  6221. $this->scriptFiles[$position][$url]=$url;
  6222. $params=func_get_args();
  6223. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  6224. return $this;
  6225. }
  6226. public function registerScript($id,$script,$position=self::POS_READY)
  6227. {
  6228. $this->hasScripts=true;
  6229. $this->scripts[$position][$id]=$script;
  6230. if($position===self::POS_READY || $position===self::POS_LOAD)
  6231. $this->registerCoreScript('jquery');
  6232. $params=func_get_args();
  6233. $this->recordCachingAction('clientScript','registerScript',$params);
  6234. return $this;
  6235. }
  6236. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array())
  6237. {
  6238. $this->hasScripts=true;
  6239. if($name!==null)
  6240. $options['name']=$name;
  6241. if($httpEquiv!==null)
  6242. $options['http-equiv']=$httpEquiv;
  6243. $options['content']=$content;
  6244. $this->metaTags[serialize($options)]=$options;
  6245. $params=func_get_args();
  6246. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  6247. return $this;
  6248. }
  6249. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  6250. {
  6251. $this->hasScripts=true;
  6252. if($relation!==null)
  6253. $options['rel']=$relation;
  6254. if($type!==null)
  6255. $options['type']=$type;
  6256. if($href!==null)
  6257. $options['href']=$href;
  6258. if($media!==null)
  6259. $options['media']=$media;
  6260. $this->linkTags[serialize($options)]=$options;
  6261. $params=func_get_args();
  6262. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  6263. return $this;
  6264. }
  6265. public function isCssFileRegistered($url)
  6266. {
  6267. return isset($this->cssFiles[$url]);
  6268. }
  6269. public function isCssRegistered($id)
  6270. {
  6271. return isset($this->css[$id]);
  6272. }
  6273. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  6274. {
  6275. return isset($this->scriptFiles[$position][$url]);
  6276. }
  6277. public function isScriptRegistered($id,$position=self::POS_READY)
  6278. {
  6279. return isset($this->scripts[$position][$id]);
  6280. }
  6281. protected function recordCachingAction($context,$method,$params)
  6282. {
  6283. if(($controller=Yii::app()->getController())!==null)
  6284. $controller->recordCachingAction($context,$method,$params);
  6285. }
  6286. public function addPackage($name,$definition)
  6287. {
  6288. $this->packages[$name]=$definition;
  6289. }
  6290. }
  6291. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  6292. {
  6293. private $_d=array();
  6294. private $_c=0;
  6295. private $_r=false;
  6296. public function __construct($data=null,$readOnly=false)
  6297. {
  6298. if($data!==null)
  6299. $this->copyFrom($data);
  6300. $this->setReadOnly($readOnly);
  6301. }
  6302. public function getReadOnly()
  6303. {
  6304. return $this->_r;
  6305. }
  6306. protected function setReadOnly($value)
  6307. {
  6308. $this->_r=$value;
  6309. }
  6310. public function getIterator()
  6311. {
  6312. return new CListIterator($this->_d);
  6313. }
  6314. public function count()
  6315. {
  6316. return $this->getCount();
  6317. }
  6318. public function getCount()
  6319. {
  6320. return $this->_c;
  6321. }
  6322. public function itemAt($index)
  6323. {
  6324. if(isset($this->_d[$index]))
  6325. return $this->_d[$index];
  6326. else if($index>=0 && $index<$this->_c) // in case the value is null
  6327. return $this->_d[$index];
  6328. else
  6329. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6330. array('{index}'=>$index)));
  6331. }
  6332. public function add($item)
  6333. {
  6334. $this->insertAt($this->_c,$item);
  6335. return $this->_c-1;
  6336. }
  6337. public function insertAt($index,$item)
  6338. {
  6339. if(!$this->_r)
  6340. {
  6341. if($index===$this->_c)
  6342. $this->_d[$this->_c++]=$item;
  6343. else if($index>=0 && $index<$this->_c)
  6344. {
  6345. array_splice($this->_d,$index,0,array($item));
  6346. $this->_c++;
  6347. }
  6348. else
  6349. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6350. array('{index}'=>$index)));
  6351. }
  6352. else
  6353. throw new CException(Yii::t('yii','The list is read only.'));
  6354. }
  6355. public function remove($item)
  6356. {
  6357. if(($index=$this->indexOf($item))>=0)
  6358. {
  6359. $this->removeAt($index);
  6360. return $index;
  6361. }
  6362. else
  6363. return false;
  6364. }
  6365. public function removeAt($index)
  6366. {
  6367. if(!$this->_r)
  6368. {
  6369. if($index>=0 && $index<$this->_c)
  6370. {
  6371. $this->_c--;
  6372. if($index===$this->_c)
  6373. return array_pop($this->_d);
  6374. else
  6375. {
  6376. $item=$this->_d[$index];
  6377. array_splice($this->_d,$index,1);
  6378. return $item;
  6379. }
  6380. }
  6381. else
  6382. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6383. array('{index}'=>$index)));
  6384. }
  6385. else
  6386. throw new CException(Yii::t('yii','The list is read only.'));
  6387. }
  6388. public function clear()
  6389. {
  6390. for($i=$this->_c-1;$i>=0;--$i)
  6391. $this->removeAt($i);
  6392. }
  6393. public function contains($item)
  6394. {
  6395. return $this->indexOf($item)>=0;
  6396. }
  6397. public function indexOf($item)
  6398. {
  6399. if(($index=array_search($item,$this->_d,true))!==false)
  6400. return $index;
  6401. else
  6402. return -1;
  6403. }
  6404. public function toArray()
  6405. {
  6406. return $this->_d;
  6407. }
  6408. public function copyFrom($data)
  6409. {
  6410. if(is_array($data) || ($data instanceof Traversable))
  6411. {
  6412. if($this->_c>0)
  6413. $this->clear();
  6414. if($data instanceof CList)
  6415. $data=$data->_d;
  6416. foreach($data as $item)
  6417. $this->add($item);
  6418. }
  6419. else if($data!==null)
  6420. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6421. }
  6422. public function mergeWith($data)
  6423. {
  6424. if(is_array($data) || ($data instanceof Traversable))
  6425. {
  6426. if($data instanceof CList)
  6427. $data=$data->_d;
  6428. foreach($data as $item)
  6429. $this->add($item);
  6430. }
  6431. else if($data!==null)
  6432. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6433. }
  6434. public function offsetExists($offset)
  6435. {
  6436. return ($offset>=0 && $offset<$this->_c);
  6437. }
  6438. public function offsetGet($offset)
  6439. {
  6440. return $this->itemAt($offset);
  6441. }
  6442. public function offsetSet($offset,$item)
  6443. {
  6444. if($offset===null || $offset===$this->_c)
  6445. $this->insertAt($this->_c,$item);
  6446. else
  6447. {
  6448. $this->removeAt($offset);
  6449. $this->insertAt($offset,$item);
  6450. }
  6451. }
  6452. public function offsetUnset($offset)
  6453. {
  6454. $this->removeAt($offset);
  6455. }
  6456. }
  6457. class CFilterChain extends CList
  6458. {
  6459. public $controller;
  6460. public $action;
  6461. public $filterIndex=0;
  6462. public function __construct($controller,$action)
  6463. {
  6464. $this->controller=$controller;
  6465. $this->action=$action;
  6466. }
  6467. public static function create($controller,$action,$filters)
  6468. {
  6469. $chain=new CFilterChain($controller,$action);
  6470. $actionID=$action->getId();
  6471. foreach($filters as $filter)
  6472. {
  6473. if(is_string($filter)) // filterName [+|- action1 action2]
  6474. {
  6475. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  6476. {
  6477. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  6478. if(($filter[$pos]==='+')===$matched)
  6479. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  6480. }
  6481. else
  6482. $filter=CInlineFilter::create($controller,$filter);
  6483. }
  6484. else if(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  6485. {
  6486. if(!isset($filter[0]))
  6487. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  6488. $filterClass=$filter[0];
  6489. unset($filter[0]);
  6490. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  6491. {
  6492. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  6493. if(($filterClass[$pos]==='+')===$matched)
  6494. $filterClass=trim(substr($filterClass,0,$pos));
  6495. else
  6496. continue;
  6497. }
  6498. $filter['class']=$filterClass;
  6499. $filter=Yii::createComponent($filter);
  6500. }
  6501. if(is_object($filter))
  6502. {
  6503. $filter->init();
  6504. $chain->add($filter);
  6505. }
  6506. }
  6507. return $chain;
  6508. }
  6509. public function insertAt($index,$item)
  6510. {
  6511. if($item instanceof IFilter)
  6512. parent::insertAt($index,$item);
  6513. else
  6514. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  6515. }
  6516. public function run()
  6517. {
  6518. if($this->offsetExists($this->filterIndex))
  6519. {
  6520. $filter=$this->itemAt($this->filterIndex++);
  6521. $filter->filter($this);
  6522. }
  6523. else
  6524. $this->controller->runAction($this->action);
  6525. }
  6526. }
  6527. class CFilter extends CComponent implements IFilter
  6528. {
  6529. public function filter($filterChain)
  6530. {
  6531. if($this->preFilter($filterChain))
  6532. {
  6533. $filterChain->run();
  6534. $this->postFilter($filterChain);
  6535. }
  6536. }
  6537. public function init()
  6538. {
  6539. }
  6540. protected function preFilter($filterChain)
  6541. {
  6542. return true;
  6543. }
  6544. protected function postFilter($filterChain)
  6545. {
  6546. }
  6547. }
  6548. class CInlineFilter extends CFilter
  6549. {
  6550. public $name;
  6551. public static function create($controller,$filterName)
  6552. {
  6553. if(method_exists($controller,'filter'.$filterName))
  6554. {
  6555. $filter=new CInlineFilter;
  6556. $filter->name=$filterName;
  6557. return $filter;
  6558. }
  6559. else
  6560. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  6561. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  6562. }
  6563. public function filter($filterChain)
  6564. {
  6565. $method='filter'.$this->name;
  6566. $filterChain->controller->$method($filterChain);
  6567. }
  6568. }
  6569. class CAccessControlFilter extends CFilter
  6570. {
  6571. public $message;
  6572. private $_rules=array();
  6573. public function getRules()
  6574. {
  6575. return $this->_rules;
  6576. }
  6577. public function setRules($rules)
  6578. {
  6579. foreach($rules as $rule)
  6580. {
  6581. if(is_array($rule) && isset($rule[0]))
  6582. {
  6583. $r=new CAccessRule;
  6584. $r->allow=$rule[0]==='allow';
  6585. foreach(array_slice($rule,1) as $name=>$value)
  6586. {
  6587. if($name==='expression' || $name==='roles' || $name==='message')
  6588. $r->$name=$value;
  6589. else
  6590. $r->$name=array_map('strtolower',$value);
  6591. }
  6592. $this->_rules[]=$r;
  6593. }
  6594. }
  6595. }
  6596. protected function preFilter($filterChain)
  6597. {
  6598. $app=Yii::app();
  6599. $request=$app->getRequest();
  6600. $user=$app->getUser();
  6601. $verb=$request->getRequestType();
  6602. $ip=$request->getUserHostAddress();
  6603. foreach($this->getRules() as $rule)
  6604. {
  6605. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  6606. break;
  6607. else if($allow<0) // denied
  6608. {
  6609. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  6610. return false;
  6611. }
  6612. }
  6613. return true;
  6614. }
  6615. protected function resolveErrorMessage($rule)
  6616. {
  6617. if($rule->message!==null)
  6618. return $rule->message;
  6619. else if($this->message!==null)
  6620. return $this->message;
  6621. else
  6622. return Yii::t('yii','You are not authorized to perform this action.');
  6623. }
  6624. protected function accessDenied($user,$message)
  6625. {
  6626. if($user->getIsGuest())
  6627. $user->loginRequired();
  6628. else
  6629. throw new CHttpException(403,$message);
  6630. }
  6631. }
  6632. class CAccessRule extends CComponent
  6633. {
  6634. public $allow;
  6635. public $actions;
  6636. public $controllers;
  6637. public $users;
  6638. public $roles;
  6639. public $ips;
  6640. public $verbs;
  6641. public $expression;
  6642. public $message;
  6643. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  6644. {
  6645. if($this->isActionMatched($action)
  6646. && $this->isUserMatched($user)
  6647. && $this->isRoleMatched($user)
  6648. && $this->isIpMatched($ip)
  6649. && $this->isVerbMatched($verb)
  6650. && $this->isControllerMatched($controller)
  6651. && $this->isExpressionMatched($user))
  6652. return $this->allow ? 1 : -1;
  6653. else
  6654. return 0;
  6655. }
  6656. protected function isActionMatched($action)
  6657. {
  6658. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  6659. }
  6660. protected function isControllerMatched($controller)
  6661. {
  6662. return empty($this->controllers) || in_array(strtolower($controller->getId()),$this->controllers);
  6663. }
  6664. protected function isUserMatched($user)
  6665. {
  6666. if(empty($this->users))
  6667. return true;
  6668. foreach($this->users as $u)
  6669. {
  6670. if($u==='*')
  6671. return true;
  6672. else if($u==='?' && $user->getIsGuest())
  6673. return true;
  6674. else if($u==='@' && !$user->getIsGuest())
  6675. return true;
  6676. else if(!strcasecmp($u,$user->getName()))
  6677. return true;
  6678. }
  6679. return false;
  6680. }
  6681. protected function isRoleMatched($user)
  6682. {
  6683. if(empty($this->roles))
  6684. return true;
  6685. foreach($this->roles as $role)
  6686. {
  6687. if($user->checkAccess($role))
  6688. return true;
  6689. }
  6690. return false;
  6691. }
  6692. protected function isIpMatched($ip)
  6693. {
  6694. if(empty($this->ips))
  6695. return true;
  6696. foreach($this->ips as $rule)
  6697. {
  6698. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  6699. return true;
  6700. }
  6701. return false;
  6702. }
  6703. protected function isVerbMatched($verb)
  6704. {
  6705. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  6706. }
  6707. protected function isExpressionMatched($user)
  6708. {
  6709. if($this->expression===null)
  6710. return true;
  6711. else
  6712. return $this->evaluateExpression($this->expression, array('user'=>$user));
  6713. }
  6714. }
  6715. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  6716. {
  6717. private $_errors=array(); // attribute name => array of errors
  6718. private $_validators; // validators
  6719. private $_scenario=''; // scenario
  6720. abstract public function attributeNames();
  6721. public function rules()
  6722. {
  6723. return array();
  6724. }
  6725. public function behaviors()
  6726. {
  6727. return array();
  6728. }
  6729. public function attributeLabels()
  6730. {
  6731. return array();
  6732. }
  6733. public function validate($attributes=null, $clearErrors=true)
  6734. {
  6735. if($clearErrors)
  6736. $this->clearErrors();
  6737. if($this->beforeValidate())
  6738. {
  6739. foreach($this->getValidators() as $validator)
  6740. $validator->validate($this,$attributes);
  6741. $this->afterValidate();
  6742. return !$this->hasErrors();
  6743. }
  6744. else
  6745. return false;
  6746. }
  6747. protected function afterConstruct()
  6748. {
  6749. if($this->hasEventHandler('onAfterConstruct'))
  6750. $this->onAfterConstruct(new CEvent($this));
  6751. }
  6752. protected function beforeValidate()
  6753. {
  6754. $event=new CModelEvent($this);
  6755. $this->onBeforeValidate($event);
  6756. return $event->isValid;
  6757. }
  6758. protected function afterValidate()
  6759. {
  6760. $this->onAfterValidate(new CEvent($this));
  6761. }
  6762. public function onAfterConstruct($event)
  6763. {
  6764. $this->raiseEvent('onAfterConstruct',$event);
  6765. }
  6766. public function onBeforeValidate($event)
  6767. {
  6768. $this->raiseEvent('onBeforeValidate',$event);
  6769. }
  6770. public function onAfterValidate($event)
  6771. {
  6772. $this->raiseEvent('onAfterValidate',$event);
  6773. }
  6774. public function getValidatorList()
  6775. {
  6776. if($this->_validators===null)
  6777. $this->_validators=$this->createValidators();
  6778. return $this->_validators;
  6779. }
  6780. public function getValidators($attribute=null)
  6781. {
  6782. if($this->_validators===null)
  6783. $this->_validators=$this->createValidators();
  6784. $validators=array();
  6785. $scenario=$this->getScenario();
  6786. foreach($this->_validators as $validator)
  6787. {
  6788. if($validator->applyTo($scenario))
  6789. {
  6790. if($attribute===null || in_array($attribute,$validator->attributes,true))
  6791. $validators[]=$validator;
  6792. }
  6793. }
  6794. return $validators;
  6795. }
  6796. public function createValidators()
  6797. {
  6798. $validators=new CList;
  6799. foreach($this->rules() as $rule)
  6800. {
  6801. if(isset($rule[0],$rule[1])) // attributes, validator name
  6802. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  6803. else
  6804. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  6805. array('{class}'=>get_class($this))));
  6806. }
  6807. return $validators;
  6808. }
  6809. public function isAttributeRequired($attribute)
  6810. {
  6811. foreach($this->getValidators($attribute) as $validator)
  6812. {
  6813. if($validator instanceof CRequiredValidator)
  6814. return true;
  6815. }
  6816. return false;
  6817. }
  6818. public function isAttributeSafe($attribute)
  6819. {
  6820. $attributes=$this->getSafeAttributeNames();
  6821. return in_array($attribute,$attributes);
  6822. }
  6823. public function getAttributeLabel($attribute)
  6824. {
  6825. $labels=$this->attributeLabels();
  6826. if(isset($labels[$attribute]))
  6827. return $labels[$attribute];
  6828. else
  6829. return $this->generateAttributeLabel($attribute);
  6830. }
  6831. public function hasErrors($attribute=null)
  6832. {
  6833. if($attribute===null)
  6834. return $this->_errors!==array();
  6835. else
  6836. return isset($this->_errors[$attribute]);
  6837. }
  6838. public function getErrors($attribute=null)
  6839. {
  6840. if($attribute===null)
  6841. return $this->_errors;
  6842. else
  6843. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  6844. }
  6845. public function getError($attribute)
  6846. {
  6847. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  6848. }
  6849. public function addError($attribute,$error)
  6850. {
  6851. $this->_errors[$attribute][]=$error;
  6852. }
  6853. public function addErrors($errors)
  6854. {
  6855. foreach($errors as $attribute=>$error)
  6856. {
  6857. if(is_array($error))
  6858. {
  6859. foreach($error as $e)
  6860. $this->_errors[$attribute][]=$e;
  6861. }
  6862. else
  6863. $this->_errors[$attribute][]=$error;
  6864. }
  6865. }
  6866. public function clearErrors($attribute=null)
  6867. {
  6868. if($attribute===null)
  6869. $this->_errors=array();
  6870. else
  6871. unset($this->_errors[$attribute]);
  6872. }
  6873. public function generateAttributeLabel($name)
  6874. {
  6875. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  6876. }
  6877. public function getAttributes($names=null)
  6878. {
  6879. $values=array();
  6880. foreach($this->attributeNames() as $name)
  6881. $values[$name]=$this->$name;
  6882. if(is_array($names))
  6883. {
  6884. $values2=array();
  6885. foreach($names as $name)
  6886. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  6887. return $values2;
  6888. }
  6889. else
  6890. return $values;
  6891. }
  6892. public function setAttributes($values,$safeOnly=true)
  6893. {
  6894. if(!is_array($values))
  6895. return;
  6896. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  6897. foreach($values as $name=>$value)
  6898. {
  6899. if(isset($attributes[$name]))
  6900. $this->$name=$value;
  6901. else if($safeOnly)
  6902. $this->onUnsafeAttribute($name,$value);
  6903. }
  6904. }
  6905. public function unsetAttributes($names=null)
  6906. {
  6907. if($names===null)
  6908. $names=$this->attributeNames();
  6909. foreach($names as $name)
  6910. $this->$name=null;
  6911. }
  6912. public function onUnsafeAttribute($name,$value)
  6913. {
  6914. if(YII_DEBUG)
  6915. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  6916. }
  6917. public function getScenario()
  6918. {
  6919. return $this->_scenario;
  6920. }
  6921. public function setScenario($value)
  6922. {
  6923. $this->_scenario=$value;
  6924. }
  6925. public function getSafeAttributeNames()
  6926. {
  6927. $attributes=array();
  6928. $unsafe=array();
  6929. foreach($this->getValidators() as $validator)
  6930. {
  6931. if(!$validator->safe)
  6932. {
  6933. foreach($validator->attributes as $name)
  6934. $unsafe[]=$name;
  6935. }
  6936. else
  6937. {
  6938. foreach($validator->attributes as $name)
  6939. $attributes[$name]=true;
  6940. }
  6941. }
  6942. foreach($unsafe as $name)
  6943. unset($attributes[$name]);
  6944. return array_keys($attributes);
  6945. }
  6946. public function getIterator()
  6947. {
  6948. $attributes=$this->getAttributes();
  6949. return new CMapIterator($attributes);
  6950. }
  6951. public function offsetExists($offset)
  6952. {
  6953. return property_exists($this,$offset);
  6954. }
  6955. public function offsetGet($offset)
  6956. {
  6957. return $this->$offset;
  6958. }
  6959. public function offsetSet($offset,$item)
  6960. {
  6961. $this->$offset=$item;
  6962. }
  6963. public function offsetUnset($offset)
  6964. {
  6965. unset($this->$offset);
  6966. }
  6967. }
  6968. abstract class CActiveRecord extends CModel
  6969. {
  6970. const BELONGS_TO='CBelongsToRelation';
  6971. const HAS_ONE='CHasOneRelation';
  6972. const HAS_MANY='CHasManyRelation';
  6973. const MANY_MANY='CManyManyRelation';
  6974. const STAT='CStatRelation';
  6975. public static $db;
  6976. private static $_models=array(); // class name => model
  6977. private $_md; // meta data
  6978. private $_new=false; // whether this instance is new or not
  6979. private $_attributes=array(); // attribute name => attribute value
  6980. private $_related=array(); // attribute name => related objects
  6981. private $_c; // query criteria (used by finder only)
  6982. private $_pk; // old primary key value
  6983. private $_alias='t'; // the table alias being used for query
  6984. public function __construct($scenario='insert')
  6985. {
  6986. if($scenario===null) // internally used by populateRecord() and model()
  6987. return;
  6988. $this->setScenario($scenario);
  6989. $this->setIsNewRecord(true);
  6990. $this->_attributes=$this->getMetaData()->attributeDefaults;
  6991. $this->init();
  6992. $this->attachBehaviors($this->behaviors());
  6993. $this->afterConstruct();
  6994. }
  6995. public function init()
  6996. {
  6997. }
  6998. public function cache($duration, $dependency=null, $queryCount=1)
  6999. {
  7000. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  7001. return $this;
  7002. }
  7003. public function __sleep()
  7004. {
  7005. $this->_md=null;
  7006. return array_keys((array)$this);
  7007. }
  7008. public function __get($name)
  7009. {
  7010. if(isset($this->_attributes[$name]))
  7011. return $this->_attributes[$name];
  7012. else if(isset($this->getMetaData()->columns[$name]))
  7013. return null;
  7014. else if(isset($this->_related[$name]))
  7015. return $this->_related[$name];
  7016. else if(isset($this->getMetaData()->relations[$name]))
  7017. return $this->getRelated($name);
  7018. else
  7019. return parent::__get($name);
  7020. }
  7021. public function __set($name,$value)
  7022. {
  7023. if($this->setAttribute($name,$value)===false)
  7024. {
  7025. if(isset($this->getMetaData()->relations[$name]))
  7026. $this->_related[$name]=$value;
  7027. else
  7028. parent::__set($name,$value);
  7029. }
  7030. }
  7031. public function __isset($name)
  7032. {
  7033. if(isset($this->_attributes[$name]))
  7034. return true;
  7035. else if(isset($this->getMetaData()->columns[$name]))
  7036. return false;
  7037. else if(isset($this->_related[$name]))
  7038. return true;
  7039. else if(isset($this->getMetaData()->relations[$name]))
  7040. return $this->getRelated($name)!==null;
  7041. else
  7042. return parent::__isset($name);
  7043. }
  7044. public function __unset($name)
  7045. {
  7046. if(isset($this->getMetaData()->columns[$name]))
  7047. unset($this->_attributes[$name]);
  7048. else if(isset($this->getMetaData()->relations[$name]))
  7049. unset($this->_related[$name]);
  7050. else
  7051. parent::__unset($name);
  7052. }
  7053. public function __call($name,$parameters)
  7054. {
  7055. if(isset($this->getMetaData()->relations[$name]))
  7056. {
  7057. if(empty($parameters))
  7058. return $this->getRelated($name,false);
  7059. else
  7060. return $this->getRelated($name,false,$parameters[0]);
  7061. }
  7062. $scopes=$this->scopes();
  7063. if(isset($scopes[$name]))
  7064. {
  7065. $this->getDbCriteria()->mergeWith($scopes[$name]);
  7066. return $this;
  7067. }
  7068. return parent::__call($name,$parameters);
  7069. }
  7070. public function getRelated($name,$refresh=false,$params=array())
  7071. {
  7072. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  7073. return $this->_related[$name];
  7074. $md=$this->getMetaData();
  7075. if(!isset($md->relations[$name]))
  7076. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  7077. array('{class}'=>get_class($this), '{name}'=>$name)));
  7078. $relation=$md->relations[$name];
  7079. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  7080. return $relation instanceof CHasOneRelation ? null : array();
  7081. if($params!==array()) // dynamic query
  7082. {
  7083. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7084. if($exists)
  7085. $save=$this->_related[$name];
  7086. $r=array($name=>$params);
  7087. }
  7088. else
  7089. $r=$name;
  7090. unset($this->_related[$name]);
  7091. $finder=new CActiveFinder($this,$r);
  7092. $finder->lazyFind($this);
  7093. if(!isset($this->_related[$name]))
  7094. {
  7095. if($relation instanceof CHasManyRelation)
  7096. $this->_related[$name]=array();
  7097. else if($relation instanceof CStatRelation)
  7098. $this->_related[$name]=$relation->defaultValue;
  7099. else
  7100. $this->_related[$name]=null;
  7101. }
  7102. if($params!==array())
  7103. {
  7104. $results=$this->_related[$name];
  7105. if($exists)
  7106. $this->_related[$name]=$save;
  7107. else
  7108. unset($this->_related[$name]);
  7109. return $results;
  7110. }
  7111. else
  7112. return $this->_related[$name];
  7113. }
  7114. public function hasRelated($name)
  7115. {
  7116. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7117. }
  7118. public function getDbCriteria($createIfNull=true)
  7119. {
  7120. if($this->_c===null)
  7121. {
  7122. if(($c=$this->defaultScope())!==array() || $createIfNull)
  7123. $this->_c=new CDbCriteria($c);
  7124. }
  7125. return $this->_c;
  7126. }
  7127. public function setDbCriteria($criteria)
  7128. {
  7129. $this->_c=$criteria;
  7130. }
  7131. public function defaultScope()
  7132. {
  7133. return array();
  7134. }
  7135. public function resetScope()
  7136. {
  7137. $this->_c=new CDbCriteria();
  7138. return $this;
  7139. }
  7140. public static function model($className=__CLASS__)
  7141. {
  7142. if(isset(self::$_models[$className]))
  7143. return self::$_models[$className];
  7144. else
  7145. {
  7146. $model=self::$_models[$className]=new $className(null);
  7147. $model->_md=new CActiveRecordMetaData($model);
  7148. $model->attachBehaviors($model->behaviors());
  7149. return $model;
  7150. }
  7151. }
  7152. public function getMetaData()
  7153. {
  7154. if($this->_md!==null)
  7155. return $this->_md;
  7156. else
  7157. return $this->_md=self::model(get_class($this))->_md;
  7158. }
  7159. public function refreshMetaData()
  7160. {
  7161. $finder=self::model(get_class($this));
  7162. $finder->_md=new CActiveRecordMetaData($finder);
  7163. if($this!==$finder)
  7164. $this->_md=$finder->_md;
  7165. }
  7166. public function tableName()
  7167. {
  7168. return get_class($this);
  7169. }
  7170. public function primaryKey()
  7171. {
  7172. }
  7173. public function relations()
  7174. {
  7175. return array();
  7176. }
  7177. public function scopes()
  7178. {
  7179. return array();
  7180. }
  7181. public function attributeNames()
  7182. {
  7183. return array_keys($this->getMetaData()->columns);
  7184. }
  7185. public function getAttributeLabel($attribute)
  7186. {
  7187. $labels=$this->attributeLabels();
  7188. if(isset($labels[$attribute]))
  7189. return $labels[$attribute];
  7190. else if(strpos($attribute,'.')!==false)
  7191. {
  7192. $segs=explode('.',$attribute);
  7193. $name=array_pop($segs);
  7194. $model=$this;
  7195. foreach($segs as $seg)
  7196. {
  7197. $relations=$model->getMetaData()->relations;
  7198. if(isset($relations[$seg]))
  7199. $model=CActiveRecord::model($relations[$seg]->className);
  7200. else
  7201. break;
  7202. }
  7203. return $model->getAttributeLabel($name);
  7204. }
  7205. else
  7206. return $this->generateAttributeLabel($attribute);
  7207. }
  7208. public function getDbConnection()
  7209. {
  7210. if(self::$db!==null)
  7211. return self::$db;
  7212. else
  7213. {
  7214. self::$db=Yii::app()->getDb();
  7215. if(self::$db instanceof CDbConnection)
  7216. return self::$db;
  7217. else
  7218. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  7219. }
  7220. }
  7221. public function getActiveRelation($name)
  7222. {
  7223. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  7224. }
  7225. public function getTableSchema()
  7226. {
  7227. return $this->getMetaData()->tableSchema;
  7228. }
  7229. public function getCommandBuilder()
  7230. {
  7231. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  7232. }
  7233. public function hasAttribute($name)
  7234. {
  7235. return isset($this->getMetaData()->columns[$name]);
  7236. }
  7237. public function getAttribute($name)
  7238. {
  7239. if(property_exists($this,$name))
  7240. return $this->$name;
  7241. else if(isset($this->_attributes[$name]))
  7242. return $this->_attributes[$name];
  7243. }
  7244. public function setAttribute($name,$value)
  7245. {
  7246. if(property_exists($this,$name))
  7247. $this->$name=$value;
  7248. else if(isset($this->getMetaData()->columns[$name]))
  7249. $this->_attributes[$name]=$value;
  7250. else
  7251. return false;
  7252. return true;
  7253. }
  7254. public function addRelatedRecord($name,$record,$index)
  7255. {
  7256. if($index!==false)
  7257. {
  7258. if(!isset($this->_related[$name]))
  7259. $this->_related[$name]=array();
  7260. if($record instanceof CActiveRecord)
  7261. {
  7262. if($index===true)
  7263. $this->_related[$name][]=$record;
  7264. else
  7265. $this->_related[$name][$index]=$record;
  7266. }
  7267. }
  7268. else if(!isset($this->_related[$name]))
  7269. $this->_related[$name]=$record;
  7270. }
  7271. public function getAttributes($names=true)
  7272. {
  7273. $attributes=$this->_attributes;
  7274. foreach($this->getMetaData()->columns as $name=>$column)
  7275. {
  7276. if(property_exists($this,$name))
  7277. $attributes[$name]=$this->$name;
  7278. else if($names===true && !isset($attributes[$name]))
  7279. $attributes[$name]=null;
  7280. }
  7281. if(is_array($names))
  7282. {
  7283. $attrs=array();
  7284. foreach($names as $name)
  7285. {
  7286. if(property_exists($this,$name))
  7287. $attrs[$name]=$this->$name;
  7288. else
  7289. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  7290. }
  7291. return $attrs;
  7292. }
  7293. else
  7294. return $attributes;
  7295. }
  7296. public function save($runValidation=true,$attributes=null)
  7297. {
  7298. if(!$runValidation || $this->validate($attributes))
  7299. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  7300. else
  7301. return false;
  7302. }
  7303. public function getIsNewRecord()
  7304. {
  7305. return $this->_new;
  7306. }
  7307. public function setIsNewRecord($value)
  7308. {
  7309. $this->_new=$value;
  7310. }
  7311. public function onBeforeSave($event)
  7312. {
  7313. $this->raiseEvent('onBeforeSave',$event);
  7314. }
  7315. public function onAfterSave($event)
  7316. {
  7317. $this->raiseEvent('onAfterSave',$event);
  7318. }
  7319. public function onBeforeDelete($event)
  7320. {
  7321. $this->raiseEvent('onBeforeDelete',$event);
  7322. }
  7323. public function onAfterDelete($event)
  7324. {
  7325. $this->raiseEvent('onAfterDelete',$event);
  7326. }
  7327. public function onBeforeFind($event)
  7328. {
  7329. $this->raiseEvent('onBeforeFind',$event);
  7330. }
  7331. public function onAfterFind($event)
  7332. {
  7333. $this->raiseEvent('onAfterFind',$event);
  7334. }
  7335. protected function beforeSave()
  7336. {
  7337. if($this->hasEventHandler('onBeforeSave'))
  7338. {
  7339. $event=new CModelEvent($this);
  7340. $this->onBeforeSave($event);
  7341. return $event->isValid;
  7342. }
  7343. else
  7344. return true;
  7345. }
  7346. protected function afterSave()
  7347. {
  7348. if($this->hasEventHandler('onAfterSave'))
  7349. $this->onAfterSave(new CEvent($this));
  7350. }
  7351. protected function beforeDelete()
  7352. {
  7353. if($this->hasEventHandler('onBeforeDelete'))
  7354. {
  7355. $event=new CModelEvent($this);
  7356. $this->onBeforeDelete($event);
  7357. return $event->isValid;
  7358. }
  7359. else
  7360. return true;
  7361. }
  7362. protected function afterDelete()
  7363. {
  7364. if($this->hasEventHandler('onAfterDelete'))
  7365. $this->onAfterDelete(new CEvent($this));
  7366. }
  7367. protected function beforeFind()
  7368. {
  7369. if($this->hasEventHandler('onBeforeFind'))
  7370. {
  7371. $event=new CModelEvent($this);
  7372. // for backward compatibility
  7373. $event->criteria=func_num_args()>0 ? func_get_arg(0) : null;
  7374. $this->onBeforeFind($event);
  7375. }
  7376. }
  7377. protected function afterFind()
  7378. {
  7379. if($this->hasEventHandler('onAfterFind'))
  7380. $this->onAfterFind(new CEvent($this));
  7381. }
  7382. public function beforeFindInternal()
  7383. {
  7384. $this->beforeFind();
  7385. }
  7386. public function afterFindInternal()
  7387. {
  7388. $this->afterFind();
  7389. }
  7390. public function insert($attributes=null)
  7391. {
  7392. if(!$this->getIsNewRecord())
  7393. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  7394. if($this->beforeSave())
  7395. {
  7396. $builder=$this->getCommandBuilder();
  7397. $table=$this->getMetaData()->tableSchema;
  7398. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  7399. if($command->execute())
  7400. {
  7401. $primaryKey=$table->primaryKey;
  7402. if($table->sequenceName!==null)
  7403. {
  7404. if(is_string($primaryKey) && $this->$primaryKey===null)
  7405. $this->$primaryKey=$builder->getLastInsertID($table);
  7406. else if(is_array($primaryKey))
  7407. {
  7408. foreach($primaryKey as $pk)
  7409. {
  7410. if($this->$pk===null)
  7411. {
  7412. $this->$pk=$builder->getLastInsertID($table);
  7413. break;
  7414. }
  7415. }
  7416. }
  7417. }
  7418. $this->_pk=$this->getPrimaryKey();
  7419. $this->afterSave();
  7420. $this->setIsNewRecord(false);
  7421. $this->setScenario('update');
  7422. return true;
  7423. }
  7424. }
  7425. return false;
  7426. }
  7427. public function update($attributes=null)
  7428. {
  7429. if($this->getIsNewRecord())
  7430. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7431. if($this->beforeSave())
  7432. {
  7433. if($this->_pk===null)
  7434. $this->_pk=$this->getPrimaryKey();
  7435. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  7436. $this->_pk=$this->getPrimaryKey();
  7437. $this->afterSave();
  7438. return true;
  7439. }
  7440. else
  7441. return false;
  7442. }
  7443. public function saveAttributes($attributes)
  7444. {
  7445. if(!$this->getIsNewRecord())
  7446. {
  7447. $values=array();
  7448. foreach($attributes as $name=>$value)
  7449. {
  7450. if(is_integer($name))
  7451. $values[$value]=$this->$value;
  7452. else
  7453. $values[$name]=$this->$name=$value;
  7454. }
  7455. if($this->_pk===null)
  7456. $this->_pk=$this->getPrimaryKey();
  7457. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  7458. {
  7459. $this->_pk=$this->getPrimaryKey();
  7460. return true;
  7461. }
  7462. else
  7463. return false;
  7464. }
  7465. else
  7466. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7467. }
  7468. public function saveCounters($counters)
  7469. {
  7470. $builder=$this->getCommandBuilder();
  7471. $table=$this->getTableSchema();
  7472. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  7473. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7474. if($command->execute())
  7475. {
  7476. foreach($counters as $name=>$value)
  7477. $this->$name=$this->$name+$value;
  7478. return true;
  7479. }
  7480. else
  7481. return false;
  7482. }
  7483. public function delete()
  7484. {
  7485. if(!$this->getIsNewRecord())
  7486. {
  7487. if($this->beforeDelete())
  7488. {
  7489. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  7490. $this->afterDelete();
  7491. return $result;
  7492. }
  7493. else
  7494. return false;
  7495. }
  7496. else
  7497. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  7498. }
  7499. public function refresh()
  7500. {
  7501. if(!$this->getIsNewRecord() && ($record=$this->findByPk($this->getPrimaryKey()))!==null)
  7502. {
  7503. $this->_attributes=array();
  7504. $this->_related=array();
  7505. foreach($this->getMetaData()->columns as $name=>$column)
  7506. {
  7507. if(property_exists($this,$name))
  7508. $this->$name=$record->$name;
  7509. else
  7510. $this->_attributes[$name]=$record->$name;
  7511. }
  7512. return true;
  7513. }
  7514. else
  7515. return false;
  7516. }
  7517. public function equals($record)
  7518. {
  7519. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  7520. }
  7521. public function getPrimaryKey()
  7522. {
  7523. $table=$this->getMetaData()->tableSchema;
  7524. if(is_string($table->primaryKey))
  7525. return $this->{$table->primaryKey};
  7526. else if(is_array($table->primaryKey))
  7527. {
  7528. $values=array();
  7529. foreach($table->primaryKey as $name)
  7530. $values[$name]=$this->$name;
  7531. return $values;
  7532. }
  7533. else
  7534. return null;
  7535. }
  7536. public function setPrimaryKey($value)
  7537. {
  7538. $this->_pk=$this->getPrimaryKey();
  7539. $table=$this->getMetaData()->tableSchema;
  7540. if(is_string($table->primaryKey))
  7541. $this->{$table->primaryKey}=$value;
  7542. else if(is_array($table->primaryKey))
  7543. {
  7544. foreach($table->primaryKey as $name)
  7545. $this->$name=$value[$name];
  7546. }
  7547. }
  7548. public function getOldPrimaryKey()
  7549. {
  7550. return $this->_pk;
  7551. }
  7552. public function setOldPrimaryKey($value)
  7553. {
  7554. $this->_pk=$value;
  7555. }
  7556. protected function query($criteria,$all=false)
  7557. {
  7558. $this->beforeFind();
  7559. $this->applyScopes($criteria);
  7560. if(empty($criteria->with))
  7561. {
  7562. if(!$all)
  7563. $criteria->limit=1;
  7564. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  7565. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  7566. }
  7567. else
  7568. {
  7569. $finder=new CActiveFinder($this,$criteria->with);
  7570. return $finder->query($criteria,$all);
  7571. }
  7572. }
  7573. public function applyScopes(&$criteria)
  7574. {
  7575. if(!empty($criteria->scopes))
  7576. {
  7577. $scs=$this->scopes();
  7578. $c=$this->getDbCriteria();
  7579. foreach((array)$criteria->scopes as $k=>$v)
  7580. {
  7581. if(is_integer($k))
  7582. {
  7583. if(is_string($v))
  7584. {
  7585. if(isset($scs[$v]))
  7586. {
  7587. $c->mergeWith($scs[$v],true);
  7588. continue;
  7589. }
  7590. $scope=$v;
  7591. $params=array();
  7592. }
  7593. else if(is_array($v))
  7594. {
  7595. $scope=key($v);
  7596. $params=current($v);
  7597. }
  7598. }
  7599. else if(is_string($k))
  7600. {
  7601. $scope=$k;
  7602. $params=$v;
  7603. }
  7604. call_user_func_array(array($this,$scope),(array)$params);
  7605. }
  7606. }
  7607. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  7608. {
  7609. $c->mergeWith($criteria);
  7610. $criteria=$c;
  7611. $this->_c=null;
  7612. }
  7613. }
  7614. public function getTableAlias($quote=false, $checkScopes=true)
  7615. {
  7616. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  7617. $alias=$criteria->alias;
  7618. else
  7619. $alias=$this->_alias;
  7620. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  7621. }
  7622. public function setTableAlias($alias)
  7623. {
  7624. $this->_alias=$alias;
  7625. }
  7626. public function find($condition='',$params=array())
  7627. {
  7628. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7629. return $this->query($criteria);
  7630. }
  7631. public function findAll($condition='',$params=array())
  7632. {
  7633. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7634. return $this->query($criteria,true);
  7635. }
  7636. public function findByPk($pk,$condition='',$params=array())
  7637. {
  7638. $prefix=$this->getTableAlias(true).'.';
  7639. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7640. return $this->query($criteria);
  7641. }
  7642. public function findAllByPk($pk,$condition='',$params=array())
  7643. {
  7644. $prefix=$this->getTableAlias(true).'.';
  7645. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7646. return $this->query($criteria,true);
  7647. }
  7648. public function findByAttributes($attributes,$condition='',$params=array())
  7649. {
  7650. $prefix=$this->getTableAlias(true).'.';
  7651. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7652. return $this->query($criteria);
  7653. }
  7654. public function findAllByAttributes($attributes,$condition='',$params=array())
  7655. {
  7656. $prefix=$this->getTableAlias(true).'.';
  7657. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7658. return $this->query($criteria,true);
  7659. }
  7660. public function findBySql($sql,$params=array())
  7661. {
  7662. $this->beforeFind();
  7663. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7664. {
  7665. $this->_c=null;
  7666. $finder=new CActiveFinder($this,$criteria->with);
  7667. return $finder->findBySql($sql,$params);
  7668. }
  7669. else
  7670. {
  7671. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7672. return $this->populateRecord($command->queryRow());
  7673. }
  7674. }
  7675. public function findAllBySql($sql,$params=array())
  7676. {
  7677. $this->beforeFind();
  7678. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7679. {
  7680. $this->_c=null;
  7681. $finder=new CActiveFinder($this,$criteria->with);
  7682. return $finder->findAllBySql($sql,$params);
  7683. }
  7684. else
  7685. {
  7686. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7687. return $this->populateRecords($command->queryAll());
  7688. }
  7689. }
  7690. public function count($condition='',$params=array())
  7691. {
  7692. $builder=$this->getCommandBuilder();
  7693. $criteria=$builder->createCriteria($condition,$params);
  7694. $this->applyScopes($criteria);
  7695. if(empty($criteria->with))
  7696. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7697. else
  7698. {
  7699. $finder=new CActiveFinder($this,$criteria->with);
  7700. return $finder->count($criteria);
  7701. }
  7702. }
  7703. public function countByAttributes($attributes,$condition='',$params=array())
  7704. {
  7705. $prefix=$this->getTableAlias(true).'.';
  7706. $builder=$this->getCommandBuilder();
  7707. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7708. $this->applyScopes($criteria);
  7709. if(empty($criteria->with))
  7710. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7711. else
  7712. {
  7713. $finder=new CActiveFinder($this,$criteria->with);
  7714. return $finder->count($criteria);
  7715. }
  7716. }
  7717. public function countBySql($sql,$params=array())
  7718. {
  7719. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  7720. }
  7721. public function exists($condition='',$params=array())
  7722. {
  7723. $builder=$this->getCommandBuilder();
  7724. $criteria=$builder->createCriteria($condition,$params);
  7725. $table=$this->getTableSchema();
  7726. $criteria->select='1';
  7727. $criteria->limit=1;
  7728. $this->applyScopes($criteria);
  7729. if(empty($criteria->with))
  7730. return $builder->createFindCommand($table,$criteria)->queryRow()!==false;
  7731. else
  7732. {
  7733. $criteria->select='*';
  7734. $finder=new CActiveFinder($this,$criteria->with);
  7735. return $finder->count($criteria)>0;
  7736. }
  7737. }
  7738. public function with()
  7739. {
  7740. if(func_num_args()>0)
  7741. {
  7742. $with=func_get_args();
  7743. if(is_array($with[0])) // the parameter is given as an array
  7744. $with=$with[0];
  7745. if(!empty($with))
  7746. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  7747. }
  7748. return $this;
  7749. }
  7750. public function together()
  7751. {
  7752. $this->getDbCriteria()->together=true;
  7753. return $this;
  7754. }
  7755. public function updateByPk($pk,$attributes,$condition='',$params=array())
  7756. {
  7757. $builder=$this->getCommandBuilder();
  7758. $table=$this->getTableSchema();
  7759. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  7760. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  7761. return $command->execute();
  7762. }
  7763. public function updateAll($attributes,$condition='',$params=array())
  7764. {
  7765. $builder=$this->getCommandBuilder();
  7766. $criteria=$builder->createCriteria($condition,$params);
  7767. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  7768. return $command->execute();
  7769. }
  7770. public function updateCounters($counters,$condition='',$params=array())
  7771. {
  7772. $builder=$this->getCommandBuilder();
  7773. $criteria=$builder->createCriteria($condition,$params);
  7774. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7775. return $command->execute();
  7776. }
  7777. public function deleteByPk($pk,$condition='',$params=array())
  7778. {
  7779. $builder=$this->getCommandBuilder();
  7780. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  7781. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7782. return $command->execute();
  7783. }
  7784. public function deleteAll($condition='',$params=array())
  7785. {
  7786. $builder=$this->getCommandBuilder();
  7787. $criteria=$builder->createCriteria($condition,$params);
  7788. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7789. return $command->execute();
  7790. }
  7791. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  7792. {
  7793. $builder=$this->getCommandBuilder();
  7794. $table=$this->getTableSchema();
  7795. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  7796. $command=$builder->createDeleteCommand($table,$criteria);
  7797. return $command->execute();
  7798. }
  7799. public function populateRecord($attributes,$callAfterFind=true)
  7800. {
  7801. if($attributes!==false)
  7802. {
  7803. $record=$this->instantiate($attributes);
  7804. $record->setScenario('update');
  7805. $record->init();
  7806. $md=$record->getMetaData();
  7807. foreach($attributes as $name=>$value)
  7808. {
  7809. if(property_exists($record,$name))
  7810. $record->$name=$value;
  7811. else if(isset($md->columns[$name]))
  7812. $record->_attributes[$name]=$value;
  7813. }
  7814. $record->_pk=$record->getPrimaryKey();
  7815. $record->attachBehaviors($record->behaviors());
  7816. if($callAfterFind)
  7817. $record->afterFind();
  7818. return $record;
  7819. }
  7820. else
  7821. return null;
  7822. }
  7823. public function populateRecords($data,$callAfterFind=true,$index=null)
  7824. {
  7825. $records=array();
  7826. foreach($data as $attributes)
  7827. {
  7828. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  7829. {
  7830. if($index===null)
  7831. $records[]=$record;
  7832. else
  7833. $records[$record->$index]=$record;
  7834. }
  7835. }
  7836. return $records;
  7837. }
  7838. protected function instantiate($attributes)
  7839. {
  7840. $class=get_class($this);
  7841. $model=new $class(null);
  7842. return $model;
  7843. }
  7844. public function offsetExists($offset)
  7845. {
  7846. return $this->__isset($offset);
  7847. }
  7848. }
  7849. class CBaseActiveRelation extends CComponent
  7850. {
  7851. public $name;
  7852. public $className;
  7853. public $foreignKey;
  7854. public $select='*';
  7855. public $condition='';
  7856. public $params=array();
  7857. public $group='';
  7858. public $join='';
  7859. public $having='';
  7860. public $order='';
  7861. public function __construct($name,$className,$foreignKey,$options=array())
  7862. {
  7863. $this->name=$name;
  7864. $this->className=$className;
  7865. $this->foreignKey=$foreignKey;
  7866. foreach($options as $name=>$value)
  7867. $this->$name=$value;
  7868. }
  7869. public function mergeWith($criteria,$fromScope=false)
  7870. {
  7871. if($criteria instanceof CDbCriteria)
  7872. $criteria=$criteria->toArray();
  7873. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  7874. {
  7875. if($this->select==='*')
  7876. $this->select=$criteria['select'];
  7877. else if($criteria['select']!=='*')
  7878. {
  7879. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  7880. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  7881. $this->select=array_merge($select1,array_diff($select2,$select1));
  7882. }
  7883. }
  7884. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  7885. {
  7886. if($this->condition==='')
  7887. $this->condition=$criteria['condition'];
  7888. else if($criteria['condition']!=='')
  7889. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  7890. }
  7891. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  7892. $this->params=array_merge($this->params,$criteria['params']);
  7893. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  7894. {
  7895. if($this->order==='')
  7896. $this->order=$criteria['order'];
  7897. else if($criteria['order']!=='')
  7898. $this->order=$criteria['order'].', '.$this->order;
  7899. }
  7900. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  7901. {
  7902. if($this->group==='')
  7903. $this->group=$criteria['group'];
  7904. else if($criteria['group']!=='')
  7905. $this->group.=', '.$criteria['group'];
  7906. }
  7907. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  7908. {
  7909. if($this->join==='')
  7910. $this->join=$criteria['join'];
  7911. else if($criteria['join']!=='')
  7912. $this->join.=' '.$criteria['join'];
  7913. }
  7914. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  7915. {
  7916. if($this->having==='')
  7917. $this->having=$criteria['having'];
  7918. else if($criteria['having']!=='')
  7919. $this->having="({$this->having}) AND ({$criteria['having']})";
  7920. }
  7921. }
  7922. }
  7923. class CStatRelation extends CBaseActiveRelation
  7924. {
  7925. public $select='COUNT(*)';
  7926. public $defaultValue=0;
  7927. public function mergeWith($criteria,$fromScope=false)
  7928. {
  7929. if($criteria instanceof CDbCriteria)
  7930. $criteria=$criteria->toArray();
  7931. parent::mergeWith($criteria,$fromScope);
  7932. if(isset($criteria['defaultValue']))
  7933. $this->defaultValue=$criteria['defaultValue'];
  7934. }
  7935. }
  7936. class CActiveRelation extends CBaseActiveRelation
  7937. {
  7938. public $joinType='LEFT OUTER JOIN';
  7939. public $on='';
  7940. public $alias;
  7941. public $with=array();
  7942. public $together;
  7943. public $scopes;
  7944. public function mergeWith($criteria,$fromScope=false)
  7945. {
  7946. if($criteria instanceof CDbCriteria)
  7947. $criteria=$criteria->toArray();
  7948. if($fromScope)
  7949. {
  7950. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  7951. {
  7952. if($this->on==='')
  7953. $this->on=$criteria['condition'];
  7954. else if($criteria['condition']!=='')
  7955. $this->on="({$this->on}) AND ({$criteria['condition']})";
  7956. }
  7957. unset($criteria['condition']);
  7958. }
  7959. parent::mergeWith($criteria);
  7960. if(isset($criteria['joinType']))
  7961. $this->joinType=$criteria['joinType'];
  7962. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  7963. {
  7964. if($this->on==='')
  7965. $this->on=$criteria['on'];
  7966. else if($criteria['on']!=='')
  7967. $this->on="({$this->on}) AND ({$criteria['on']})";
  7968. }
  7969. if(isset($criteria['with']))
  7970. $this->with=$criteria['with'];
  7971. if(isset($criteria['alias']))
  7972. $this->alias=$criteria['alias'];
  7973. if(isset($criteria['together']))
  7974. $this->together=$criteria['together'];
  7975. }
  7976. }
  7977. class CBelongsToRelation extends CActiveRelation
  7978. {
  7979. }
  7980. class CHasOneRelation extends CActiveRelation
  7981. {
  7982. public $through;
  7983. }
  7984. class CHasManyRelation extends CActiveRelation
  7985. {
  7986. public $limit=-1;
  7987. public $offset=-1;
  7988. public $index;
  7989. public $through;
  7990. public function mergeWith($criteria,$fromScope=false)
  7991. {
  7992. if($criteria instanceof CDbCriteria)
  7993. $criteria=$criteria->toArray();
  7994. parent::mergeWith($criteria,$fromScope);
  7995. if(isset($criteria['limit']) && $criteria['limit']>0)
  7996. $this->limit=$criteria['limit'];
  7997. if(isset($criteria['offset']) && $criteria['offset']>=0)
  7998. $this->offset=$criteria['offset'];
  7999. if(isset($criteria['index']))
  8000. $this->index=$criteria['index'];
  8001. }
  8002. }
  8003. class CManyManyRelation extends CHasManyRelation
  8004. {
  8005. }
  8006. class CActiveRecordMetaData
  8007. {
  8008. public $tableSchema;
  8009. public $columns;
  8010. public $relations=array();
  8011. public $attributeDefaults=array();
  8012. private $_model;
  8013. public function __construct($model)
  8014. {
  8015. $this->_model=$model;
  8016. $tableName=$model->tableName();
  8017. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  8018. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  8019. array('{class}'=>get_class($model),'{table}'=>$tableName)));
  8020. if($table->primaryKey===null)
  8021. {
  8022. $table->primaryKey=$model->primaryKey();
  8023. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  8024. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  8025. else if(is_array($table->primaryKey))
  8026. {
  8027. foreach($table->primaryKey as $name)
  8028. {
  8029. if(isset($table->columns[$name]))
  8030. $table->columns[$name]->isPrimaryKey=true;
  8031. }
  8032. }
  8033. }
  8034. $this->tableSchema=$table;
  8035. $this->columns=$table->columns;
  8036. foreach($table->columns as $name=>$column)
  8037. {
  8038. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  8039. $this->attributeDefaults[$name]=$column->defaultValue;
  8040. }
  8041. foreach($model->relations() as $name=>$config)
  8042. {
  8043. $this->addRelation($name,$config);
  8044. }
  8045. }
  8046. public function addRelation($name,$config)
  8047. {
  8048. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  8049. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  8050. else
  8051. throw new CDbException(Yii::t('yii','Active record "{class}" has an invalid configuration for relation "{relation}". It must specify the relation type, the related active record class and the foreign key.', array('{class}'=>get_class($this->_model),'{relation}'=>$name)));
  8052. }
  8053. public function hasRelation($name)
  8054. {
  8055. return isset($this->relations[$name]);
  8056. }
  8057. public function removeRelation($name)
  8058. {
  8059. unset($this->relations[$name]);
  8060. }
  8061. }
  8062. class CDbConnection extends CApplicationComponent
  8063. {
  8064. public $connectionString;
  8065. public $username='';
  8066. public $password='';
  8067. public $schemaCachingDuration=0;
  8068. public $schemaCachingExclude=array();
  8069. public $schemaCacheID='cache';
  8070. public $queryCachingDuration=0;
  8071. public $queryCachingDependency;
  8072. public $queryCachingCount=0;
  8073. public $queryCacheID='cache';
  8074. public $autoConnect=true;
  8075. public $charset;
  8076. public $emulatePrepare;
  8077. public $enableParamLogging=false;
  8078. public $enableProfiling=false;
  8079. public $tablePrefix;
  8080. public $initSQLs;
  8081. public $driverMap=array(
  8082. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  8083. 'mysqli'=>'CMysqlSchema', // MySQL
  8084. 'mysql'=>'CMysqlSchema', // MySQL
  8085. 'sqlite'=>'CSqliteSchema', // sqlite 3
  8086. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  8087. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  8088. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  8089. 'sqlsrv'=>'CMssqlSchema', // Mssql
  8090. 'oci'=>'COciSchema', // Oracle driver
  8091. );
  8092. public $pdoClass = 'PDO';
  8093. private $_attributes=array();
  8094. private $_active=false;
  8095. private $_pdo;
  8096. private $_transaction;
  8097. private $_schema;
  8098. public function __construct($dsn='',$username='',$password='')
  8099. {
  8100. $this->connectionString=$dsn;
  8101. $this->username=$username;
  8102. $this->password=$password;
  8103. }
  8104. public function __sleep()
  8105. {
  8106. $this->close();
  8107. return array_keys(get_object_vars($this));
  8108. }
  8109. public static function getAvailableDrivers()
  8110. {
  8111. return PDO::getAvailableDrivers();
  8112. }
  8113. public function init()
  8114. {
  8115. parent::init();
  8116. if($this->autoConnect)
  8117. $this->setActive(true);
  8118. }
  8119. public function getActive()
  8120. {
  8121. return $this->_active;
  8122. }
  8123. public function setActive($value)
  8124. {
  8125. if($value!=$this->_active)
  8126. {
  8127. if($value)
  8128. $this->open();
  8129. else
  8130. $this->close();
  8131. }
  8132. }
  8133. public function cache($duration, $dependency=null, $queryCount=1)
  8134. {
  8135. $this->queryCachingDuration=$duration;
  8136. $this->queryCachingDependency=$dependency;
  8137. $this->queryCachingCount=$queryCount;
  8138. return $this;
  8139. }
  8140. protected function open()
  8141. {
  8142. if($this->_pdo===null)
  8143. {
  8144. if(empty($this->connectionString))
  8145. throw new CDbException(Yii::t('yii','CDbConnection.connectionString cannot be empty.'));
  8146. try
  8147. {
  8148. $this->_pdo=$this->createPdoInstance();
  8149. $this->initConnection($this->_pdo);
  8150. $this->_active=true;
  8151. }
  8152. catch(PDOException $e)
  8153. {
  8154. if(YII_DEBUG)
  8155. {
  8156. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection: {error}',
  8157. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$e->errorInfo);
  8158. }
  8159. else
  8160. {
  8161. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  8162. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'),(int)$e->getCode(),$e->errorInfo);
  8163. }
  8164. }
  8165. }
  8166. }
  8167. protected function close()
  8168. {
  8169. $this->_pdo=null;
  8170. $this->_active=false;
  8171. $this->_schema=null;
  8172. }
  8173. protected function createPdoInstance()
  8174. {
  8175. $pdoClass=$this->pdoClass;
  8176. if(($pos=strpos($this->connectionString,':'))!==false)
  8177. {
  8178. $driver=strtolower(substr($this->connectionString,0,$pos));
  8179. if($driver==='mssql' || $driver==='dblib' || $driver==='sqlsrv')
  8180. $pdoClass='CMssqlPdoAdapter';
  8181. }
  8182. return new $pdoClass($this->connectionString,$this->username,
  8183. $this->password,$this->_attributes);
  8184. }
  8185. protected function initConnection($pdo)
  8186. {
  8187. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  8188. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  8189. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  8190. if($this->charset!==null)
  8191. {
  8192. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  8193. if(in_array($driver,array('pgsql','mysql','mysqli')))
  8194. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  8195. }
  8196. if($this->initSQLs!==null)
  8197. {
  8198. foreach($this->initSQLs as $sql)
  8199. $pdo->exec($sql);
  8200. }
  8201. }
  8202. public function getPdoInstance()
  8203. {
  8204. return $this->_pdo;
  8205. }
  8206. public function createCommand($query=null)
  8207. {
  8208. $this->setActive(true);
  8209. return new CDbCommand($this,$query);
  8210. }
  8211. public function getCurrentTransaction()
  8212. {
  8213. if($this->_transaction!==null)
  8214. {
  8215. if($this->_transaction->getActive())
  8216. return $this->_transaction;
  8217. }
  8218. return null;
  8219. }
  8220. public function beginTransaction()
  8221. {
  8222. $this->setActive(true);
  8223. $this->_pdo->beginTransaction();
  8224. return $this->_transaction=new CDbTransaction($this);
  8225. }
  8226. public function getSchema()
  8227. {
  8228. if($this->_schema!==null)
  8229. return $this->_schema;
  8230. else
  8231. {
  8232. $driver=$this->getDriverName();
  8233. if(isset($this->driverMap[$driver]))
  8234. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  8235. else
  8236. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  8237. array('{driver}'=>$driver)));
  8238. }
  8239. }
  8240. public function getCommandBuilder()
  8241. {
  8242. return $this->getSchema()->getCommandBuilder();
  8243. }
  8244. public function getLastInsertID($sequenceName='')
  8245. {
  8246. $this->setActive(true);
  8247. return $this->_pdo->lastInsertId($sequenceName);
  8248. }
  8249. public function quoteValue($str)
  8250. {
  8251. if(is_int($str) || is_float($str))
  8252. return $str;
  8253. $this->setActive(true);
  8254. if(($value=$this->_pdo->quote($str))!==false)
  8255. return $value;
  8256. else // the driver doesn't support quote (e.g. oci)
  8257. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  8258. }
  8259. public function quoteTableName($name)
  8260. {
  8261. return $this->getSchema()->quoteTableName($name);
  8262. }
  8263. public function quoteColumnName($name)
  8264. {
  8265. return $this->getSchema()->quoteColumnName($name);
  8266. }
  8267. public function getPdoType($type)
  8268. {
  8269. static $map=array
  8270. (
  8271. 'boolean'=>PDO::PARAM_BOOL,
  8272. 'integer'=>PDO::PARAM_INT,
  8273. 'string'=>PDO::PARAM_STR,
  8274. 'NULL'=>PDO::PARAM_NULL,
  8275. );
  8276. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  8277. }
  8278. public function getColumnCase()
  8279. {
  8280. return $this->getAttribute(PDO::ATTR_CASE);
  8281. }
  8282. public function setColumnCase($value)
  8283. {
  8284. $this->setAttribute(PDO::ATTR_CASE,$value);
  8285. }
  8286. public function getNullConversion()
  8287. {
  8288. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  8289. }
  8290. public function setNullConversion($value)
  8291. {
  8292. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  8293. }
  8294. public function getAutoCommit()
  8295. {
  8296. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  8297. }
  8298. public function setAutoCommit($value)
  8299. {
  8300. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  8301. }
  8302. public function getPersistent()
  8303. {
  8304. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  8305. }
  8306. public function setPersistent($value)
  8307. {
  8308. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  8309. }
  8310. public function getDriverName()
  8311. {
  8312. if(($pos=strpos($this->connectionString, ':'))!==false)
  8313. return strtolower(substr($this->connectionString, 0, $pos));
  8314. // return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  8315. }
  8316. public function getClientVersion()
  8317. {
  8318. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  8319. }
  8320. public function getConnectionStatus()
  8321. {
  8322. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  8323. }
  8324. public function getPrefetch()
  8325. {
  8326. return $this->getAttribute(PDO::ATTR_PREFETCH);
  8327. }
  8328. public function getServerInfo()
  8329. {
  8330. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  8331. }
  8332. public function getServerVersion()
  8333. {
  8334. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  8335. }
  8336. public function getTimeout()
  8337. {
  8338. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  8339. }
  8340. public function getAttribute($name)
  8341. {
  8342. $this->setActive(true);
  8343. return $this->_pdo->getAttribute($name);
  8344. }
  8345. public function setAttribute($name,$value)
  8346. {
  8347. if($this->_pdo instanceof PDO)
  8348. $this->_pdo->setAttribute($name,$value);
  8349. else
  8350. $this->_attributes[$name]=$value;
  8351. }
  8352. public function getAttributes()
  8353. {
  8354. return $this->_attributes;
  8355. }
  8356. public function setAttributes($values)
  8357. {
  8358. foreach($values as $name=>$value)
  8359. $this->_attributes[$name]=$value;
  8360. }
  8361. public function getStats()
  8362. {
  8363. $logger=Yii::getLogger();
  8364. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  8365. $count=count($timings);
  8366. $time=array_sum($timings);
  8367. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  8368. $count+=count($timings);
  8369. $time+=array_sum($timings);
  8370. return array($count,$time);
  8371. }
  8372. }
  8373. abstract class CDbSchema extends CComponent
  8374. {
  8375. public $columnTypes=array();
  8376. private $_tableNames=array();
  8377. private $_tables=array();
  8378. private $_connection;
  8379. private $_builder;
  8380. private $_cacheExclude=array();
  8381. abstract protected function loadTable($name);
  8382. public function __construct($conn)
  8383. {
  8384. $this->_connection=$conn;
  8385. foreach($conn->schemaCachingExclude as $name)
  8386. $this->_cacheExclude[$name]=true;
  8387. }
  8388. public function getDbConnection()
  8389. {
  8390. return $this->_connection;
  8391. }
  8392. public function getTable($name,$refresh=false)
  8393. {
  8394. if($refresh===false && isset($this->_tables[$name]))
  8395. return $this->_tables[$name];
  8396. else
  8397. {
  8398. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  8399. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  8400. else
  8401. $realName=$name;
  8402. // temporarily disable query caching
  8403. if($this->_connection->queryCachingDuration>0)
  8404. {
  8405. $qcDuration=$this->_connection->queryCachingDuration;
  8406. $this->_connection->queryCachingDuration=0;
  8407. }
  8408. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8409. {
  8410. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8411. $table=$cache->get($key);
  8412. if($refresh===true || $table===false)
  8413. {
  8414. $table=$this->loadTable($realName);
  8415. if($table!==null)
  8416. $cache->set($key,$table,$duration);
  8417. }
  8418. $this->_tables[$name]=$table;
  8419. }
  8420. else
  8421. $this->_tables[$name]=$table=$this->loadTable($realName);
  8422. if(isset($qcDuration)) // re-enable query caching
  8423. $this->_connection->queryCachingDuration=$qcDuration;
  8424. return $table;
  8425. }
  8426. }
  8427. public function getTables($schema='')
  8428. {
  8429. $tables=array();
  8430. foreach($this->getTableNames($schema) as $name)
  8431. {
  8432. if(($table=$this->getTable($name))!==null)
  8433. $tables[$name]=$table;
  8434. }
  8435. return $tables;
  8436. }
  8437. public function getTableNames($schema='')
  8438. {
  8439. if(!isset($this->_tableNames[$schema]))
  8440. $this->_tableNames[$schema]=$this->findTableNames($schema);
  8441. return $this->_tableNames[$schema];
  8442. }
  8443. public function getCommandBuilder()
  8444. {
  8445. if($this->_builder!==null)
  8446. return $this->_builder;
  8447. else
  8448. return $this->_builder=$this->createCommandBuilder();
  8449. }
  8450. public function refresh()
  8451. {
  8452. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8453. {
  8454. foreach(array_keys($this->_tables) as $name)
  8455. {
  8456. if(!isset($this->_cacheExclude[$name]))
  8457. {
  8458. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8459. $cache->delete($key);
  8460. }
  8461. }
  8462. }
  8463. $this->_tables=array();
  8464. $this->_tableNames=array();
  8465. $this->_builder=null;
  8466. }
  8467. public function quoteTableName($name)
  8468. {
  8469. if(strpos($name,'.')===false)
  8470. return $this->quoteSimpleTableName($name);
  8471. $parts=explode('.',$name);
  8472. foreach($parts as $i=>$part)
  8473. $parts[$i]=$this->quoteSimpleTableName($part);
  8474. return implode('.',$parts);
  8475. }
  8476. public function quoteSimpleTableName($name)
  8477. {
  8478. return "'".$name."'";
  8479. }
  8480. public function quoteColumnName($name)
  8481. {
  8482. if(($pos=strrpos($name,'.'))!==false)
  8483. {
  8484. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  8485. $name=substr($name,$pos+1);
  8486. }
  8487. else
  8488. $prefix='';
  8489. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  8490. }
  8491. public function quoteSimpleColumnName($name)
  8492. {
  8493. return '"'.$name.'"';
  8494. }
  8495. public function compareTableNames($name1,$name2)
  8496. {
  8497. $name1=str_replace(array('"','`',"'"),'',$name1);
  8498. $name2=str_replace(array('"','`',"'"),'',$name2);
  8499. if(($pos=strrpos($name1,'.'))!==false)
  8500. $name1=substr($name1,$pos+1);
  8501. if(($pos=strrpos($name2,'.'))!==false)
  8502. $name2=substr($name2,$pos+1);
  8503. if($this->_connection->tablePrefix!==null)
  8504. {
  8505. if(strpos($name1,'{')!==false)
  8506. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  8507. if(strpos($name2,'{')!==false)
  8508. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  8509. }
  8510. return $name1===$name2;
  8511. }
  8512. public function resetSequence($table,$value=null)
  8513. {
  8514. }
  8515. public function checkIntegrity($check=true,$schema='')
  8516. {
  8517. }
  8518. protected function createCommandBuilder()
  8519. {
  8520. return new CDbCommandBuilder($this);
  8521. }
  8522. protected function findTableNames($schema='')
  8523. {
  8524. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  8525. array('{class}'=>get_class($this))));
  8526. }
  8527. public function getColumnType($type)
  8528. {
  8529. if(isset($this->columnTypes[$type]))
  8530. return $this->columnTypes[$type];
  8531. else if(($pos=strpos($type,' '))!==false)
  8532. {
  8533. $t=substr($type,0,$pos);
  8534. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  8535. }
  8536. else
  8537. return $type;
  8538. }
  8539. public function createTable($table, $columns, $options=null)
  8540. {
  8541. $cols=array();
  8542. foreach($columns as $name=>$type)
  8543. {
  8544. if(is_string($name))
  8545. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  8546. else
  8547. $cols[]="\t".$type;
  8548. }
  8549. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  8550. return $options===null ? $sql : $sql.' '.$options;
  8551. }
  8552. public function renameTable($table, $newName)
  8553. {
  8554. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  8555. }
  8556. public function dropTable($table)
  8557. {
  8558. return "DROP TABLE ".$this->quoteTableName($table);
  8559. }
  8560. public function truncateTable($table)
  8561. {
  8562. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  8563. }
  8564. public function addColumn($table, $column, $type)
  8565. {
  8566. return 'ALTER TABLE ' . $this->quoteTableName($table)
  8567. . ' ADD ' . $this->quoteColumnName($column) . ' '
  8568. . $this->getColumnType($type);
  8569. }
  8570. public function dropColumn($table, $column)
  8571. {
  8572. return "ALTER TABLE ".$this->quoteTableName($table)
  8573. ." DROP COLUMN ".$this->quoteColumnName($column);
  8574. }
  8575. public function renameColumn($table, $name, $newName)
  8576. {
  8577. return "ALTER TABLE ".$this->quoteTableName($table)
  8578. . " RENAME COLUMN ".$this->quoteColumnName($name)
  8579. . " TO ".$this->quoteColumnName($newName);
  8580. }
  8581. public function alterColumn($table, $column, $type)
  8582. {
  8583. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  8584. . $this->quoteColumnName($column) . ' '
  8585. . $this->quoteColumnName($column) . ' '
  8586. . $this->getColumnType($type);
  8587. }
  8588. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8589. {
  8590. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  8591. foreach($columns as $i=>$col)
  8592. $columns[$i]=$this->quoteColumnName($col);
  8593. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  8594. foreach($refColumns as $i=>$col)
  8595. $refColumns[$i]=$this->quoteColumnName($col);
  8596. $sql='ALTER TABLE '.$this->quoteTableName($table)
  8597. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  8598. .' FOREIGN KEY ('.implode(', ', $columns).')'
  8599. .' REFERENCES '.$this->quoteTableName($refTable)
  8600. .' ('.implode(', ', $refColumns).')';
  8601. if($delete!==null)
  8602. $sql.=' ON DELETE '.$delete;
  8603. if($update!==null)
  8604. $sql.=' ON UPDATE '.$update;
  8605. return $sql;
  8606. }
  8607. public function dropForeignKey($name, $table)
  8608. {
  8609. return 'ALTER TABLE '.$this->quoteTableName($table)
  8610. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  8611. }
  8612. public function createIndex($name, $table, $column, $unique=false)
  8613. {
  8614. $cols=array();
  8615. $columns=preg_split('/\s*,\s*/',$column,-1,PREG_SPLIT_NO_EMPTY);
  8616. foreach($columns as $col)
  8617. {
  8618. if(strpos($col,'(')!==false)
  8619. $cols[]=$col;
  8620. else
  8621. $cols[]=$this->quoteColumnName($col);
  8622. }
  8623. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  8624. . $this->quoteTableName($name).' ON '
  8625. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  8626. }
  8627. public function dropIndex($name, $table)
  8628. {
  8629. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  8630. }
  8631. }
  8632. class CSqliteSchema extends CDbSchema
  8633. {
  8634. public $columnTypes=array(
  8635. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  8636. 'string' => 'varchar(255)',
  8637. 'text' => 'text',
  8638. 'integer' => 'integer',
  8639. 'float' => 'float',
  8640. 'decimal' => 'decimal',
  8641. 'datetime' => 'datetime',
  8642. 'timestamp' => 'timestamp',
  8643. 'time' => 'time',
  8644. 'date' => 'date',
  8645. 'binary' => 'blob',
  8646. 'boolean' => 'tinyint(1)',
  8647. 'money' => 'decimal(19,4)',
  8648. );
  8649. public function resetSequence($table,$value=null)
  8650. {
  8651. if($table->sequenceName!==null)
  8652. {
  8653. if($value===null)
  8654. $value=$this->getDbConnection()->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")->queryScalar();
  8655. else
  8656. $value=(int)$value-1;
  8657. try
  8658. {
  8659. // it's possible sqlite_sequence does not exist
  8660. $this->getDbConnection()->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")->execute();
  8661. }
  8662. catch(Exception $e)
  8663. {
  8664. }
  8665. }
  8666. }
  8667. public function checkIntegrity($check=true,$schema='')
  8668. {
  8669. // SQLite doesn't enforce integrity
  8670. return;
  8671. }
  8672. protected function findTableNames($schema='')
  8673. {
  8674. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  8675. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  8676. }
  8677. protected function createCommandBuilder()
  8678. {
  8679. return new CSqliteCommandBuilder($this);
  8680. }
  8681. protected function loadTable($name)
  8682. {
  8683. $table=new CDbTableSchema;
  8684. $table->name=$name;
  8685. $table->rawName=$this->quoteTableName($name);
  8686. if($this->findColumns($table))
  8687. {
  8688. $this->findConstraints($table);
  8689. return $table;
  8690. }
  8691. else
  8692. return null;
  8693. }
  8694. protected function findColumns($table)
  8695. {
  8696. $sql="PRAGMA table_info({$table->rawName})";
  8697. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  8698. if(empty($columns))
  8699. return false;
  8700. foreach($columns as $column)
  8701. {
  8702. $c=$this->createColumn($column);
  8703. $table->columns[$c->name]=$c;
  8704. if($c->isPrimaryKey)
  8705. {
  8706. if($table->primaryKey===null)
  8707. $table->primaryKey=$c->name;
  8708. else if(is_string($table->primaryKey))
  8709. $table->primaryKey=array($table->primaryKey,$c->name);
  8710. else
  8711. $table->primaryKey[]=$c->name;
  8712. }
  8713. }
  8714. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  8715. {
  8716. $table->sequenceName='';
  8717. $table->columns[$table->primaryKey]->autoIncrement=true;
  8718. }
  8719. return true;
  8720. }
  8721. protected function findConstraints($table)
  8722. {
  8723. $foreignKeys=array();
  8724. $sql="PRAGMA foreign_key_list({$table->rawName})";
  8725. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  8726. foreach($keys as $key)
  8727. {
  8728. $column=$table->columns[$key['from']];
  8729. $column->isForeignKey=true;
  8730. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  8731. }
  8732. $table->foreignKeys=$foreignKeys;
  8733. }
  8734. protected function createColumn($column)
  8735. {
  8736. $c=new CSqliteColumnSchema;
  8737. $c->name=$column['name'];
  8738. $c->rawName=$this->quoteColumnName($c->name);
  8739. $c->allowNull=!$column['notnull'];
  8740. $c->isPrimaryKey=$column['pk']!=0;
  8741. $c->isForeignKey=false;
  8742. $c->init(strtolower($column['type']),$column['dflt_value']);
  8743. return $c;
  8744. }
  8745. public function truncateTable($table)
  8746. {
  8747. return "DELETE FROM ".$this->quoteTableName($table);
  8748. }
  8749. public function dropColumn($table, $column)
  8750. {
  8751. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  8752. }
  8753. public function renameColumn($table, $name, $newName)
  8754. {
  8755. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  8756. }
  8757. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8758. {
  8759. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  8760. }
  8761. public function dropForeignKey($name, $table)
  8762. {
  8763. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  8764. }
  8765. public function alterColumn($table, $column, $type)
  8766. {
  8767. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  8768. }
  8769. public function dropIndex($name, $table)
  8770. {
  8771. return 'DROP INDEX '.$this->quoteTableName($name);
  8772. }
  8773. }
  8774. class CDbTableSchema extends CComponent
  8775. {
  8776. public $name;
  8777. public $rawName;
  8778. public $primaryKey;
  8779. public $sequenceName;
  8780. public $foreignKeys=array();
  8781. public $columns=array();
  8782. public function getColumn($name)
  8783. {
  8784. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  8785. }
  8786. public function getColumnNames()
  8787. {
  8788. return array_keys($this->columns);
  8789. }
  8790. }
  8791. class CDbCommand extends CComponent
  8792. {
  8793. public $params=array();
  8794. private $_connection;
  8795. private $_text;
  8796. private $_statement;
  8797. private $_paramLog=array();
  8798. private $_query;
  8799. private $_fetchMode = array(PDO::FETCH_ASSOC);
  8800. public function __construct(CDbConnection $connection,$query=null)
  8801. {
  8802. $this->_connection=$connection;
  8803. if(is_array($query))
  8804. {
  8805. foreach($query as $name=>$value)
  8806. $this->$name=$value;
  8807. }
  8808. else
  8809. $this->setText($query);
  8810. }
  8811. public function __sleep()
  8812. {
  8813. $this->_statement=null;
  8814. return array_keys(get_object_vars($this));
  8815. }
  8816. public function setFetchMode($mode)
  8817. {
  8818. $params=func_get_args();
  8819. $this->_fetchMode = $params;
  8820. return $this;
  8821. }
  8822. public function reset()
  8823. {
  8824. $this->_text=null;
  8825. $this->_query=null;
  8826. $this->_statement=null;
  8827. $this->_paramLog=array();
  8828. $this->params=array();
  8829. return $this;
  8830. }
  8831. public function getText()
  8832. {
  8833. if($this->_text=='' && !empty($this->_query))
  8834. $this->setText($this->buildQuery($this->_query));
  8835. return $this->_text;
  8836. }
  8837. public function setText($value)
  8838. {
  8839. if($this->_connection->tablePrefix!==null && $value!='')
  8840. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  8841. else
  8842. $this->_text=$value;
  8843. $this->cancel();
  8844. return $this;
  8845. }
  8846. public function getConnection()
  8847. {
  8848. return $this->_connection;
  8849. }
  8850. public function getPdoStatement()
  8851. {
  8852. return $this->_statement;
  8853. }
  8854. public function prepare()
  8855. {
  8856. if($this->_statement==null)
  8857. {
  8858. try
  8859. {
  8860. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  8861. $this->_paramLog=array();
  8862. }
  8863. catch(Exception $e)
  8864. {
  8865. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8866. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8867. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  8868. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  8869. }
  8870. }
  8871. }
  8872. public function cancel()
  8873. {
  8874. $this->_statement=null;
  8875. }
  8876. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  8877. {
  8878. $this->prepare();
  8879. if($dataType===null)
  8880. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  8881. else if($length===null)
  8882. $this->_statement->bindParam($name,$value,$dataType);
  8883. else if($driverOptions===null)
  8884. $this->_statement->bindParam($name,$value,$dataType,$length);
  8885. else
  8886. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  8887. $this->_paramLog[$name]=&$value;
  8888. return $this;
  8889. }
  8890. public function bindValue($name, $value, $dataType=null)
  8891. {
  8892. $this->prepare();
  8893. if($dataType===null)
  8894. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8895. else
  8896. $this->_statement->bindValue($name,$value,$dataType);
  8897. $this->_paramLog[$name]=$value;
  8898. return $this;
  8899. }
  8900. public function bindValues($values)
  8901. {
  8902. $this->prepare();
  8903. foreach($values as $name=>$value)
  8904. {
  8905. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8906. $this->_paramLog[$name]=$value;
  8907. }
  8908. return $this;
  8909. }
  8910. public function execute($params=array())
  8911. {
  8912. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8913. {
  8914. $p=array();
  8915. foreach($pars as $name=>$value)
  8916. $p[$name]=$name.'='.var_export($value,true);
  8917. $par='. Bound with ' .implode(', ',$p);
  8918. }
  8919. else
  8920. $par='';
  8921. try
  8922. {
  8923. if($this->_connection->enableProfiling)
  8924. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8925. $this->prepare();
  8926. if($params===array())
  8927. $this->_statement->execute();
  8928. else
  8929. $this->_statement->execute($params);
  8930. $n=$this->_statement->rowCount();
  8931. if($this->_connection->enableProfiling)
  8932. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8933. return $n;
  8934. }
  8935. catch(Exception $e)
  8936. {
  8937. if($this->_connection->enableProfiling)
  8938. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8939. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8940. $message = $e->getMessage();
  8941. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  8942. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8943. if(YII_DEBUG)
  8944. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  8945. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8946. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8947. }
  8948. }
  8949. public function query($params=array())
  8950. {
  8951. return $this->queryInternal('',0,$params);
  8952. }
  8953. public function queryAll($fetchAssociative=true,$params=array())
  8954. {
  8955. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8956. }
  8957. public function queryRow($fetchAssociative=true,$params=array())
  8958. {
  8959. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8960. }
  8961. public function queryScalar($params=array())
  8962. {
  8963. $result=$this->queryInternal('fetchColumn',0,$params);
  8964. if(is_resource($result) && get_resource_type($result)==='stream')
  8965. return stream_get_contents($result);
  8966. else
  8967. return $result;
  8968. }
  8969. public function queryColumn($params=array())
  8970. {
  8971. return $this->queryInternal('fetchAll',PDO::FETCH_COLUMN,$params);
  8972. }
  8973. private function queryInternal($method,$mode,$params=array())
  8974. {
  8975. $params=array_merge($this->params,$params);
  8976. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8977. {
  8978. $p=array();
  8979. foreach($pars as $name=>$value)
  8980. $p[$name]=$name.'='.var_export($value,true);
  8981. $par='. Bound with '.implode(', ',$p);
  8982. }
  8983. else
  8984. $par='';
  8985. if($this->_connection->queryCachingCount>0 && $method!==''
  8986. && $this->_connection->queryCachingDuration>0
  8987. && $this->_connection->queryCacheID!==false
  8988. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  8989. {
  8990. $this->_connection->queryCachingCount--;
  8991. $cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
  8992. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  8993. if(($result=$cache->get($cacheKey))!==false)
  8994. {
  8995. return $result;
  8996. }
  8997. }
  8998. try
  8999. {
  9000. if($this->_connection->enableProfiling)
  9001. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9002. $this->prepare();
  9003. if($params===array())
  9004. $this->_statement->execute();
  9005. else
  9006. $this->_statement->execute($params);
  9007. if($method==='')
  9008. $result=new CDbDataReader($this);
  9009. else
  9010. {
  9011. $mode=(array)$mode;
  9012. $result=call_user_func_array(array($this->_statement, $method), $mode);
  9013. $this->_statement->closeCursor();
  9014. }
  9015. if($this->_connection->enableProfiling)
  9016. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9017. if(isset($cache,$cacheKey))
  9018. $cache->set($cacheKey, $result, $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  9019. return $result;
  9020. }
  9021. catch(Exception $e)
  9022. {
  9023. if($this->_connection->enableProfiling)
  9024. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9025. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  9026. $message = $e->getMessage();
  9027. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  9028. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9029. if(YII_DEBUG)
  9030. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  9031. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  9032. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  9033. }
  9034. }
  9035. public function buildQuery($query)
  9036. {
  9037. $sql=isset($query['distinct']) && $query['distinct'] ? 'SELECT DISTINCT' : 'SELECT';
  9038. $sql.=' '.(isset($query['select']) ? $query['select'] : '*');
  9039. if(isset($query['from']))
  9040. $sql.="\nFROM ".$query['from'];
  9041. else
  9042. throw new CDbException(Yii::t('yii','The DB query must contain the "from" portion.'));
  9043. if(isset($query['join']))
  9044. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  9045. if(isset($query['where']))
  9046. $sql.="\nWHERE ".$query['where'];
  9047. if(isset($query['group']))
  9048. $sql.="\nGROUP BY ".$query['group'];
  9049. if(isset($query['having']))
  9050. $sql.="\nHAVING ".$query['having'];
  9051. if(isset($query['order']))
  9052. $sql.="\nORDER BY ".$query['order'];
  9053. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  9054. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  9055. if($limit>=0 || $offset>0)
  9056. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  9057. if(isset($query['union']))
  9058. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  9059. return $sql;
  9060. }
  9061. public function select($columns='*', $option='')
  9062. {
  9063. if(is_string($columns) && strpos($columns,'(')!==false)
  9064. $this->_query['select']=$columns;
  9065. else
  9066. {
  9067. if(!is_array($columns))
  9068. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9069. foreach($columns as $i=>$column)
  9070. {
  9071. if(is_object($column))
  9072. $columns[$i]=(string)$column;
  9073. else if(strpos($column,'(')===false)
  9074. {
  9075. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  9076. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  9077. else
  9078. $columns[$i]=$this->_connection->quoteColumnName($column);
  9079. }
  9080. }
  9081. $this->_query['select']=implode(', ',$columns);
  9082. }
  9083. if($option!='')
  9084. $this->_query['select']=$option.' '.$this->_query['select'];
  9085. return $this;
  9086. }
  9087. public function getSelect()
  9088. {
  9089. return isset($this->_query['select']) ? $this->_query['select'] : '';
  9090. }
  9091. public function setSelect($value)
  9092. {
  9093. $this->select($value);
  9094. }
  9095. public function selectDistinct($columns='*')
  9096. {
  9097. $this->_query['distinct']=true;
  9098. return $this->select($columns);
  9099. }
  9100. public function getDistinct()
  9101. {
  9102. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  9103. }
  9104. public function setDistinct($value)
  9105. {
  9106. $this->_query['distinct']=$value;
  9107. }
  9108. public function from($tables)
  9109. {
  9110. if(is_string($tables) && strpos($tables,'(')!==false)
  9111. $this->_query['from']=$tables;
  9112. else
  9113. {
  9114. if(!is_array($tables))
  9115. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  9116. foreach($tables as $i=>$table)
  9117. {
  9118. if(strpos($table,'(')===false)
  9119. {
  9120. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9121. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9122. else
  9123. $tables[$i]=$this->_connection->quoteTableName($table);
  9124. }
  9125. }
  9126. $this->_query['from']=implode(', ',$tables);
  9127. }
  9128. return $this;
  9129. }
  9130. public function getFrom()
  9131. {
  9132. return isset($this->_query['from']) ? $this->_query['from'] : '';
  9133. }
  9134. public function setFrom($value)
  9135. {
  9136. $this->from($value);
  9137. }
  9138. public function where($conditions, $params=array())
  9139. {
  9140. $this->_query['where']=$this->processConditions($conditions);
  9141. foreach($params as $name=>$value)
  9142. $this->params[$name]=$value;
  9143. return $this;
  9144. }
  9145. public function getWhere()
  9146. {
  9147. return isset($this->_query['where']) ? $this->_query['where'] : '';
  9148. }
  9149. public function setWhere($value)
  9150. {
  9151. $this->where($value);
  9152. }
  9153. public function join($table, $conditions, $params=array())
  9154. {
  9155. return $this->joinInternal('join', $table, $conditions, $params);
  9156. }
  9157. public function getJoin()
  9158. {
  9159. return isset($this->_query['join']) ? $this->_query['join'] : '';
  9160. }
  9161. public function setJoin($value)
  9162. {
  9163. $this->_query['join']=$value;
  9164. }
  9165. public function leftJoin($table, $conditions, $params=array())
  9166. {
  9167. return $this->joinInternal('left join', $table, $conditions, $params);
  9168. }
  9169. public function rightJoin($table, $conditions, $params=array())
  9170. {
  9171. return $this->joinInternal('right join', $table, $conditions, $params);
  9172. }
  9173. public function crossJoin($table)
  9174. {
  9175. return $this->joinInternal('cross join', $table);
  9176. }
  9177. public function naturalJoin($table)
  9178. {
  9179. return $this->joinInternal('natural join', $table);
  9180. }
  9181. public function group($columns)
  9182. {
  9183. if(is_string($columns) && strpos($columns,'(')!==false)
  9184. $this->_query['group']=$columns;
  9185. else
  9186. {
  9187. if(!is_array($columns))
  9188. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9189. foreach($columns as $i=>$column)
  9190. {
  9191. if(is_object($column))
  9192. $columns[$i]=(string)$column;
  9193. else if(strpos($column,'(')===false)
  9194. $columns[$i]=$this->_connection->quoteColumnName($column);
  9195. }
  9196. $this->_query['group']=implode(', ',$columns);
  9197. }
  9198. return $this;
  9199. }
  9200. public function getGroup()
  9201. {
  9202. return isset($this->_query['group']) ? $this->_query['group'] : '';
  9203. }
  9204. public function setGroup($value)
  9205. {
  9206. $this->group($value);
  9207. }
  9208. public function having($conditions, $params=array())
  9209. {
  9210. $this->_query['having']=$this->processConditions($conditions);
  9211. foreach($params as $name=>$value)
  9212. $this->params[$name]=$value;
  9213. return $this;
  9214. }
  9215. public function getHaving()
  9216. {
  9217. return isset($this->_query['having']) ? $this->_query['having'] : '';
  9218. }
  9219. public function setHaving($value)
  9220. {
  9221. $this->having($value);
  9222. }
  9223. public function order($columns)
  9224. {
  9225. if(is_string($columns) && strpos($columns,'(')!==false)
  9226. $this->_query['order']=$columns;
  9227. else
  9228. {
  9229. if(!is_array($columns))
  9230. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9231. foreach($columns as $i=>$column)
  9232. {
  9233. if(is_object($column))
  9234. $columns[$i]=(string)$column;
  9235. else if(strpos($column,'(')===false)
  9236. {
  9237. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  9238. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  9239. else
  9240. $columns[$i]=$this->_connection->quoteColumnName($column);
  9241. }
  9242. }
  9243. $this->_query['order']=implode(', ',$columns);
  9244. }
  9245. return $this;
  9246. }
  9247. public function getOrder()
  9248. {
  9249. return isset($this->_query['order']) ? $this->_query['order'] : '';
  9250. }
  9251. public function setOrder($value)
  9252. {
  9253. $this->order($value);
  9254. }
  9255. public function limit($limit, $offset=null)
  9256. {
  9257. $this->_query['limit']=(int)$limit;
  9258. if($offset!==null)
  9259. $this->offset($offset);
  9260. return $this;
  9261. }
  9262. public function getLimit()
  9263. {
  9264. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  9265. }
  9266. public function setLimit($value)
  9267. {
  9268. $this->limit($value);
  9269. }
  9270. public function offset($offset)
  9271. {
  9272. $this->_query['offset']=(int)$offset;
  9273. return $this;
  9274. }
  9275. public function getOffset()
  9276. {
  9277. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  9278. }
  9279. public function setOffset($value)
  9280. {
  9281. $this->offset($value);
  9282. }
  9283. public function union($sql)
  9284. {
  9285. if(isset($this->_query['union']) && is_string($this->_query['union']))
  9286. $this->_query['union']=array($this->_query['union']);
  9287. $this->_query['union'][]=$sql;
  9288. return $this;
  9289. }
  9290. public function getUnion()
  9291. {
  9292. return isset($this->_query['union']) ? $this->_query['union'] : '';
  9293. }
  9294. public function setUnion($value)
  9295. {
  9296. $this->_query['union']=$value;
  9297. }
  9298. public function insert($table, $columns)
  9299. {
  9300. $params=array();
  9301. $names=array();
  9302. $placeholders=array();
  9303. foreach($columns as $name=>$value)
  9304. {
  9305. $names[]=$this->_connection->quoteColumnName($name);
  9306. if($value instanceof CDbExpression)
  9307. {
  9308. $placeholders[] = $value->expression;
  9309. foreach($value->params as $n => $v)
  9310. $params[$n] = $v;
  9311. }
  9312. else
  9313. {
  9314. $placeholders[] = ':' . $name;
  9315. $params[':' . $name] = $value;
  9316. }
  9317. }
  9318. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  9319. . ' (' . implode(', ',$names) . ') VALUES ('
  9320. . implode(', ', $placeholders) . ')';
  9321. return $this->setText($sql)->execute($params);
  9322. }
  9323. public function update($table, $columns, $conditions='', $params=array())
  9324. {
  9325. $lines=array();
  9326. foreach($columns as $name=>$value)
  9327. {
  9328. if($value instanceof CDbExpression)
  9329. {
  9330. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  9331. foreach($value->params as $n => $v)
  9332. $params[$n] = $v;
  9333. }
  9334. else
  9335. {
  9336. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  9337. $params[':' . $name]=$value;
  9338. }
  9339. }
  9340. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  9341. if(($where=$this->processConditions($conditions))!='')
  9342. $sql.=' WHERE '.$where;
  9343. return $this->setText($sql)->execute($params);
  9344. }
  9345. public function delete($table, $conditions='', $params=array())
  9346. {
  9347. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  9348. if(($where=$this->processConditions($conditions))!='')
  9349. $sql.=' WHERE '.$where;
  9350. return $this->setText($sql)->execute($params);
  9351. }
  9352. public function createTable($table, $columns, $options=null)
  9353. {
  9354. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  9355. }
  9356. public function renameTable($table, $newName)
  9357. {
  9358. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  9359. }
  9360. public function dropTable($table)
  9361. {
  9362. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  9363. }
  9364. public function truncateTable($table)
  9365. {
  9366. $schema=$this->getConnection()->getSchema();
  9367. $n=$this->setText($schema->truncateTable($table))->execute();
  9368. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  9369. $schema->resetSequence($schema->getTable($table));
  9370. return $n;
  9371. }
  9372. public function addColumn($table, $column, $type)
  9373. {
  9374. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  9375. }
  9376. public function dropColumn($table, $column)
  9377. {
  9378. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  9379. }
  9380. public function renameColumn($table, $name, $newName)
  9381. {
  9382. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  9383. }
  9384. public function alterColumn($table, $column, $type)
  9385. {
  9386. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  9387. }
  9388. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9389. {
  9390. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  9391. }
  9392. public function dropForeignKey($name, $table)
  9393. {
  9394. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  9395. }
  9396. public function createIndex($name, $table, $column, $unique=false)
  9397. {
  9398. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $column, $unique))->execute();
  9399. }
  9400. public function dropIndex($name, $table)
  9401. {
  9402. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  9403. }
  9404. private function processConditions($conditions)
  9405. {
  9406. if(!is_array($conditions))
  9407. return $conditions;
  9408. else if($conditions===array())
  9409. return '';
  9410. $n=count($conditions);
  9411. $operator=strtoupper($conditions[0]);
  9412. if($operator==='OR' || $operator==='AND')
  9413. {
  9414. $parts=array();
  9415. for($i=1;$i<$n;++$i)
  9416. {
  9417. $condition=$this->processConditions($conditions[$i]);
  9418. if($condition!=='')
  9419. $parts[]='('.$condition.')';
  9420. }
  9421. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  9422. }
  9423. if(!isset($conditions[1],$conditions[2]))
  9424. return '';
  9425. $column=$conditions[1];
  9426. if(strpos($column,'(')===false)
  9427. $column=$this->_connection->quoteColumnName($column);
  9428. $values=$conditions[2];
  9429. if(!is_array($values))
  9430. $values=array($values);
  9431. if($operator==='IN' || $operator==='NOT IN')
  9432. {
  9433. if($values===array())
  9434. return $operator==='IN' ? '0=1' : '';
  9435. foreach($values as $i=>$value)
  9436. {
  9437. if(is_string($value))
  9438. $values[$i]=$this->_connection->quoteValue($value);
  9439. else
  9440. $values[$i]=(string)$value;
  9441. }
  9442. return $column.' '.$operator.' ('.implode(', ',$values).')';
  9443. }
  9444. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  9445. {
  9446. if($values===array())
  9447. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  9448. if($operator==='LIKE' || $operator==='NOT LIKE')
  9449. $andor=' AND ';
  9450. else
  9451. {
  9452. $andor=' OR ';
  9453. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  9454. }
  9455. $expressions=array();
  9456. foreach($values as $value)
  9457. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  9458. return implode($andor,$expressions);
  9459. }
  9460. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  9461. }
  9462. private function joinInternal($type, $table, $conditions='', $params=array())
  9463. {
  9464. if(strpos($table,'(')===false)
  9465. {
  9466. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9467. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9468. else
  9469. $table=$this->_connection->quoteTableName($table);
  9470. }
  9471. $conditions=$this->processConditions($conditions);
  9472. if($conditions!='')
  9473. $conditions=' ON '.$conditions;
  9474. if(isset($this->_query['join']) && is_string($this->_query['join']))
  9475. $this->_query['join']=array($this->_query['join']);
  9476. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  9477. foreach($params as $name=>$value)
  9478. $this->params[$name]=$value;
  9479. return $this;
  9480. }
  9481. }
  9482. class CDbColumnSchema extends CComponent
  9483. {
  9484. public $name;
  9485. public $rawName;
  9486. public $allowNull;
  9487. public $dbType;
  9488. public $type;
  9489. public $defaultValue;
  9490. public $size;
  9491. public $precision;
  9492. public $scale;
  9493. public $isPrimaryKey;
  9494. public $isForeignKey;
  9495. public $autoIncrement=false;
  9496. public function init($dbType, $defaultValue)
  9497. {
  9498. $this->dbType=$dbType;
  9499. $this->extractType($dbType);
  9500. $this->extractLimit($dbType);
  9501. if($defaultValue!==null)
  9502. $this->extractDefault($defaultValue);
  9503. }
  9504. protected function extractType($dbType)
  9505. {
  9506. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  9507. $this->type='integer';
  9508. else if(stripos($dbType,'bool')!==false)
  9509. $this->type='boolean';
  9510. else if(preg_match('/(real|floa|doub)/i',$dbType))
  9511. $this->type='double';
  9512. else
  9513. $this->type='string';
  9514. }
  9515. protected function extractLimit($dbType)
  9516. {
  9517. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  9518. {
  9519. $values=explode(',',$matches[1]);
  9520. $this->size=$this->precision=(int)$values[0];
  9521. if(isset($values[1]))
  9522. $this->scale=(int)$values[1];
  9523. }
  9524. }
  9525. protected function extractDefault($defaultValue)
  9526. {
  9527. $this->defaultValue=$this->typecast($defaultValue);
  9528. }
  9529. public function typecast($value)
  9530. {
  9531. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  9532. return $value;
  9533. if($value==='')
  9534. return $this->type==='string' ? '' : null;
  9535. switch($this->type)
  9536. {
  9537. case 'string': return (string)$value;
  9538. case 'integer': return (integer)$value;
  9539. case 'boolean': return (boolean)$value;
  9540. case 'double':
  9541. default: return $value;
  9542. }
  9543. }
  9544. }
  9545. class CSqliteColumnSchema extends CDbColumnSchema
  9546. {
  9547. protected function extractDefault($defaultValue)
  9548. {
  9549. if($this->type==='string') // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  9550. $this->defaultValue=trim($defaultValue,"'\"");
  9551. else
  9552. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  9553. }
  9554. }
  9555. abstract class CValidator extends CComponent
  9556. {
  9557. public static $builtInValidators=array(
  9558. 'required'=>'CRequiredValidator',
  9559. 'filter'=>'CFilterValidator',
  9560. 'match'=>'CRegularExpressionValidator',
  9561. 'email'=>'CEmailValidator',
  9562. 'url'=>'CUrlValidator',
  9563. 'unique'=>'CUniqueValidator',
  9564. 'compare'=>'CCompareValidator',
  9565. 'length'=>'CStringValidator',
  9566. 'in'=>'CRangeValidator',
  9567. 'numerical'=>'CNumberValidator',
  9568. 'captcha'=>'CCaptchaValidator',
  9569. 'type'=>'CTypeValidator',
  9570. 'file'=>'CFileValidator',
  9571. 'default'=>'CDefaultValueValidator',
  9572. 'exist'=>'CExistValidator',
  9573. 'boolean'=>'CBooleanValidator',
  9574. 'safe'=>'CSafeValidator',
  9575. 'unsafe'=>'CUnsafeValidator',
  9576. 'date'=>'CDateValidator',
  9577. );
  9578. public $attributes;
  9579. public $message;
  9580. public $skipOnError=false;
  9581. public $on;
  9582. public $safe=true;
  9583. public $enableClientValidation=true;
  9584. abstract protected function validateAttribute($object,$attribute);
  9585. public static function createValidator($name,$object,$attributes,$params=array())
  9586. {
  9587. if(is_string($attributes))
  9588. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  9589. if(isset($params['on']))
  9590. {
  9591. if(is_array($params['on']))
  9592. $on=$params['on'];
  9593. else
  9594. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  9595. }
  9596. else
  9597. $on=array();
  9598. if(method_exists($object,$name))
  9599. {
  9600. $validator=new CInlineValidator;
  9601. $validator->attributes=$attributes;
  9602. $validator->method=$name;
  9603. if(isset($params['clientValidate']))
  9604. {
  9605. $validator->clientValidate=$params['clientValidate'];
  9606. unset($params['clientValidate']);
  9607. }
  9608. $validator->params=$params;
  9609. if(isset($params['skipOnError']))
  9610. $validator->skipOnError=$params['skipOnError'];
  9611. }
  9612. else
  9613. {
  9614. $params['attributes']=$attributes;
  9615. if(isset(self::$builtInValidators[$name]))
  9616. $className=Yii::import(self::$builtInValidators[$name],true);
  9617. else
  9618. $className=Yii::import($name,true);
  9619. $validator=new $className;
  9620. foreach($params as $name=>$value)
  9621. $validator->$name=$value;
  9622. }
  9623. $validator->on=empty($on) ? array() : array_combine($on,$on);
  9624. return $validator;
  9625. }
  9626. public function validate($object,$attributes=null)
  9627. {
  9628. if(is_array($attributes))
  9629. $attributes=array_intersect($this->attributes,$attributes);
  9630. else
  9631. $attributes=$this->attributes;
  9632. foreach($attributes as $attribute)
  9633. {
  9634. if(!$this->skipOnError || !$object->hasErrors($attribute))
  9635. $this->validateAttribute($object,$attribute);
  9636. }
  9637. }
  9638. public function clientValidateAttribute($object,$attribute)
  9639. {
  9640. }
  9641. public function applyTo($scenario)
  9642. {
  9643. return empty($this->on) || isset($this->on[$scenario]);
  9644. }
  9645. protected function addError($object,$attribute,$message,$params=array())
  9646. {
  9647. $params['{attribute}']=$object->getAttributeLabel($attribute);
  9648. $object->addError($attribute,strtr($message,$params));
  9649. }
  9650. protected function isEmpty($value,$trim=false)
  9651. {
  9652. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  9653. }
  9654. }
  9655. class CStringValidator extends CValidator
  9656. {
  9657. public $max;
  9658. public $min;
  9659. public $is;
  9660. public $tooShort;
  9661. public $tooLong;
  9662. public $allowEmpty=true;
  9663. public $encoding;
  9664. protected function validateAttribute($object,$attribute)
  9665. {
  9666. $value=$object->$attribute;
  9667. if($this->allowEmpty && $this->isEmpty($value))
  9668. return;
  9669. if(function_exists('mb_strlen') && $this->encoding!==false)
  9670. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  9671. else
  9672. $length=strlen($value);
  9673. if($this->min!==null && $length<$this->min)
  9674. {
  9675. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9676. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9677. }
  9678. if($this->max!==null && $length>$this->max)
  9679. {
  9680. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9681. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9682. }
  9683. if($this->is!==null && $length!==$this->is)
  9684. {
  9685. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9686. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  9687. }
  9688. }
  9689. public function clientValidateAttribute($object,$attribute)
  9690. {
  9691. $label=$object->getAttributeLabel($attribute);
  9692. if(($message=$this->message)===null)
  9693. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9694. $message=strtr($message, array(
  9695. '{attribute}'=>$label,
  9696. '{length}'=>$this->is,
  9697. ));
  9698. if(($tooShort=$this->tooShort)===null)
  9699. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9700. $tooShort=strtr($tooShort, array(
  9701. '{attribute}'=>$label,
  9702. '{min}'=>$this->min,
  9703. ));
  9704. if(($tooLong=$this->tooLong)===null)
  9705. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9706. $tooLong=strtr($tooLong, array(
  9707. '{attribute}'=>$label,
  9708. '{max}'=>$this->max,
  9709. ));
  9710. $js='';
  9711. if($this->min!==null)
  9712. {
  9713. $js.="
  9714. if(value.length<{$this->min}) {
  9715. messages.push(".CJSON::encode($tooShort).");
  9716. }
  9717. ";
  9718. }
  9719. if($this->max!==null)
  9720. {
  9721. $js.="
  9722. if(value.length>{$this->max}) {
  9723. messages.push(".CJSON::encode($tooLong).");
  9724. }
  9725. ";
  9726. }
  9727. if($this->is!==null)
  9728. {
  9729. $js.="
  9730. if(value.length!={$this->is}) {
  9731. messages.push(".CJSON::encode($message).");
  9732. }
  9733. ";
  9734. }
  9735. if($this->allowEmpty)
  9736. {
  9737. $js="
  9738. if($.trim(value)!='') {
  9739. $js
  9740. }
  9741. ";
  9742. }
  9743. return $js;
  9744. }
  9745. }
  9746. class CRequiredValidator extends CValidator
  9747. {
  9748. public $requiredValue;
  9749. public $strict=false;
  9750. protected function validateAttribute($object,$attribute)
  9751. {
  9752. $value=$object->$attribute;
  9753. if($this->requiredValue!==null)
  9754. {
  9755. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  9756. {
  9757. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  9758. array('{value}'=>$this->requiredValue));
  9759. $this->addError($object,$attribute,$message);
  9760. }
  9761. }
  9762. else if($this->isEmpty($value,true))
  9763. {
  9764. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  9765. $this->addError($object,$attribute,$message);
  9766. }
  9767. }
  9768. public function clientValidateAttribute($object,$attribute)
  9769. {
  9770. $message=$this->message;
  9771. if($this->requiredValue!==null)
  9772. {
  9773. if($message===null)
  9774. $message=Yii::t('yii','{attribute} must be {value}.');
  9775. $message=strtr($message, array(
  9776. '{value}'=>$this->requiredValue,
  9777. '{attribute}'=>$object->getAttributeLabel($attribute),
  9778. ));
  9779. return "
  9780. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  9781. messages.push(".CJSON::encode($message).");
  9782. }
  9783. ";
  9784. }
  9785. else
  9786. {
  9787. if($message===null)
  9788. $message=Yii::t('yii','{attribute} cannot be blank.');
  9789. $message=strtr($message, array(
  9790. '{attribute}'=>$object->getAttributeLabel($attribute),
  9791. ));
  9792. return "
  9793. if($.trim(value)=='') {
  9794. messages.push(".CJSON::encode($message).");
  9795. }
  9796. ";
  9797. }
  9798. }
  9799. }
  9800. class CNumberValidator extends CValidator
  9801. {
  9802. public $integerOnly=false;
  9803. public $allowEmpty=true;
  9804. public $max;
  9805. public $min;
  9806. public $tooBig;
  9807. public $tooSmall;
  9808. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  9809. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  9810. protected function validateAttribute($object,$attribute)
  9811. {
  9812. $value=$object->$attribute;
  9813. if($this->allowEmpty && $this->isEmpty($value))
  9814. return;
  9815. if($this->integerOnly)
  9816. {
  9817. if(!preg_match($this->integerPattern,"$value"))
  9818. {
  9819. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  9820. $this->addError($object,$attribute,$message);
  9821. }
  9822. }
  9823. else
  9824. {
  9825. if(!preg_match($this->numberPattern,"$value"))
  9826. {
  9827. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  9828. $this->addError($object,$attribute,$message);
  9829. }
  9830. }
  9831. if($this->min!==null && $value<$this->min)
  9832. {
  9833. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9834. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9835. }
  9836. if($this->max!==null && $value>$this->max)
  9837. {
  9838. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9839. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9840. }
  9841. }
  9842. public function clientValidateAttribute($object,$attribute)
  9843. {
  9844. $label=$object->getAttributeLabel($attribute);
  9845. if(($message=$this->message)===null)
  9846. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  9847. $message=strtr($message, array(
  9848. '{attribute}'=>$label,
  9849. ));
  9850. if(($tooBig=$this->tooBig)===null)
  9851. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9852. $tooBig=strtr($tooBig, array(
  9853. '{attribute}'=>$label,
  9854. '{max}'=>$this->max,
  9855. ));
  9856. if(($tooSmall=$this->tooSmall)===null)
  9857. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9858. $tooSmall=strtr($tooSmall, array(
  9859. '{attribute}'=>$label,
  9860. '{min}'=>$this->min,
  9861. ));
  9862. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  9863. $js="
  9864. if(!value.match($pattern)) {
  9865. messages.push(".CJSON::encode($message).");
  9866. }
  9867. ";
  9868. if($this->min!==null)
  9869. {
  9870. $js.="
  9871. if(value<{$this->min}) {
  9872. messages.push(".CJSON::encode($tooSmall).");
  9873. }
  9874. ";
  9875. }
  9876. if($this->max!==null)
  9877. {
  9878. $js.="
  9879. if(value>{$this->max}) {
  9880. messages.push(".CJSON::encode($tooBig).");
  9881. }
  9882. ";
  9883. }
  9884. if($this->allowEmpty)
  9885. {
  9886. $js="
  9887. if($.trim(value)!='') {
  9888. $js
  9889. }
  9890. ";
  9891. }
  9892. return $js;
  9893. }
  9894. }
  9895. class CListIterator implements Iterator
  9896. {
  9897. private $_d;
  9898. private $_i;
  9899. private $_c;
  9900. public function __construct(&$data)
  9901. {
  9902. $this->_d=&$data;
  9903. $this->_i=0;
  9904. $this->_c=count($this->_d);
  9905. }
  9906. public function rewind()
  9907. {
  9908. $this->_i=0;
  9909. }
  9910. public function key()
  9911. {
  9912. return $this->_i;
  9913. }
  9914. public function current()
  9915. {
  9916. return $this->_d[$this->_i];
  9917. }
  9918. public function next()
  9919. {
  9920. $this->_i++;
  9921. }
  9922. public function valid()
  9923. {
  9924. return $this->_i<$this->_c;
  9925. }
  9926. }
  9927. interface IApplicationComponent
  9928. {
  9929. public function init();
  9930. public function getIsInitialized();
  9931. }
  9932. interface ICache
  9933. {
  9934. public function get($id);
  9935. public function mget($ids);
  9936. public function set($id,$value,$expire=0,$dependency=null);
  9937. public function add($id,$value,$expire=0,$dependency=null);
  9938. public function delete($id);
  9939. public function flush();
  9940. }
  9941. interface ICacheDependency
  9942. {
  9943. public function evaluateDependency();
  9944. public function getHasChanged();
  9945. }
  9946. interface IStatePersister
  9947. {
  9948. public function load();
  9949. public function save($state);
  9950. }
  9951. interface IFilter
  9952. {
  9953. public function filter($filterChain);
  9954. }
  9955. interface IAction
  9956. {
  9957. public function getId();
  9958. public function getController();
  9959. }
  9960. interface IWebServiceProvider
  9961. {
  9962. public function beforeWebMethod($service);
  9963. public function afterWebMethod($service);
  9964. }
  9965. interface IViewRenderer
  9966. {
  9967. public function renderFile($context,$file,$data,$return);
  9968. }
  9969. interface IUserIdentity
  9970. {
  9971. public function authenticate();
  9972. public function getIsAuthenticated();
  9973. public function getId();
  9974. public function getName();
  9975. public function getPersistentStates();
  9976. }
  9977. interface IWebUser
  9978. {
  9979. public function getId();
  9980. public function getName();
  9981. public function getIsGuest();
  9982. public function checkAccess($operation,$params=array());
  9983. }
  9984. interface IAuthManager
  9985. {
  9986. public function checkAccess($itemName,$userId,$params=array());
  9987. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  9988. public function removeAuthItem($name);
  9989. public function getAuthItems($type=null,$userId=null);
  9990. public function getAuthItem($name);
  9991. public function saveAuthItem($item,$oldName=null);
  9992. public function addItemChild($itemName,$childName);
  9993. public function removeItemChild($itemName,$childName);
  9994. public function hasItemChild($itemName,$childName);
  9995. public function getItemChildren($itemName);
  9996. public function assign($itemName,$userId,$bizRule=null,$data=null);
  9997. public function revoke($itemName,$userId);
  9998. public function isAssigned($itemName,$userId);
  9999. public function getAuthAssignment($itemName,$userId);
  10000. public function getAuthAssignments($userId);
  10001. public function saveAuthAssignment($assignment);
  10002. public function clearAll();
  10003. public function clearAuthAssignments();
  10004. public function save();
  10005. public function executeBizRule($bizRule,$params,$data);
  10006. }
  10007. interface IBehavior
  10008. {
  10009. public function attach($component);
  10010. public function detach($component);
  10011. public function getEnabled();
  10012. public function setEnabled($value);
  10013. }
  10014. interface IWidgetFactory
  10015. {
  10016. public function createWidget($owner,$className,$properties=array());
  10017. }
  10018. interface IDataProvider
  10019. {
  10020. public function getId();
  10021. public function getItemCount($refresh=false);
  10022. public function getTotalItemCount($refresh=false);
  10023. public function getData($refresh=false);
  10024. public function getKeys($refresh=false);
  10025. public function getSort();
  10026. public function getPagination();
  10027. }
  10028. ?>