PageRenderTime 108ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/yii/yiilite.php

https://bitbucket.org/Crisu83/webgames
PHP | 9678 lines | 9623 code | 2 blank | 53 comment | 815 complexity | 47ae14a1de722724e4bdc61582da7a41 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, GPL-3.0, LGPL-2.0, LGPL-2.1, BSD-2-Clause
  1. <?php
  2. /**
  3. * Yii bootstrap file.
  4. *
  5. * This file is automatically generated using 'build lite' command.
  6. * It is the result of merging commonly used Yii class files with
  7. * comments and trace statements removed away.
  8. *
  9. * By using this file instead of yii.php, an Yii application may
  10. * improve performance due to the reduction of PHP parsing time.
  11. * The performance improvement is especially obvious when PHP APC extension
  12. * is enabled.
  13. *
  14. * DO NOT modify this file manually.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @link http://www.yiiframework.com/
  18. * @copyright Copyright &copy; 2008-2012 Yii Software LLC
  19. * @license http://www.yiiframework.com/license/
  20. * @version $Id: yiilite.php 3564 2012-02-13 01:29:03Z 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.10';
  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. return self::$_app;
  56. }
  57. public static function setApplication($app)
  58. {
  59. if(self::$_app===null || $app===null)
  60. self::$_app=$app;
  61. else
  62. throw new CException(Yii::t('yii','Yii application can only be created once.'));
  63. }
  64. public static function getFrameworkPath()
  65. {
  66. return YII_PATH;
  67. }
  68. public static function createComponent($config)
  69. {
  70. if(is_string($config))
  71. {
  72. $type=$config;
  73. $config=array();
  74. }
  75. else if(isset($config['class']))
  76. {
  77. $type=$config['class'];
  78. unset($config['class']);
  79. }
  80. else
  81. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  82. if(!class_exists($type,false))
  83. $type=Yii::import($type,true);
  84. if(($n=func_num_args())>1)
  85. {
  86. $args=func_get_args();
  87. if($n===2)
  88. $object=new $type($args[1]);
  89. else if($n===3)
  90. $object=new $type($args[1],$args[2]);
  91. else if($n===4)
  92. $object=new $type($args[1],$args[2],$args[3]);
  93. else
  94. {
  95. unset($args[0]);
  96. $class=new ReflectionClass($type);
  97. // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
  98. // $object=$class->newInstanceArgs($args);
  99. $object=call_user_func_array(array($class,'newInstance'),$args);
  100. }
  101. }
  102. else
  103. $object=new $type;
  104. foreach($config as $key=>$value)
  105. $object->$key=$value;
  106. return $object;
  107. }
  108. public static function import($alias,$forceInclude=false)
  109. {
  110. if(isset(self::$_imports[$alias])) // previously imported
  111. return self::$_imports[$alias];
  112. if(class_exists($alias,false) || interface_exists($alias,false))
  113. return self::$_imports[$alias]=$alias;
  114. if(($pos=strrpos($alias,'\\'))!==false) // a class name in PHP 5.3 namespace format
  115. {
  116. $namespace=str_replace('\\','.',ltrim(substr($alias,0,$pos),'\\'));
  117. if(($path=self::getPathOfAlias($namespace))!==false)
  118. {
  119. $classFile=$path.DIRECTORY_SEPARATOR.substr($alias,$pos+1).'.php';
  120. if($forceInclude)
  121. {
  122. if(is_file($classFile))
  123. require($classFile);
  124. else
  125. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file.',array('{alias}'=>$alias)));
  126. self::$_imports[$alias]=$alias;
  127. }
  128. else
  129. self::$classMap[$alias]=$classFile;
  130. return $alias;
  131. }
  132. else
  133. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory.',
  134. array('{alias}'=>$namespace)));
  135. }
  136. if(($pos=strrpos($alias,'.'))===false) // a simple class name
  137. {
  138. if($forceInclude && self::autoload($alias))
  139. self::$_imports[$alias]=$alias;
  140. return $alias;
  141. }
  142. $className=(string)substr($alias,$pos+1);
  143. $isClass=$className!=='*';
  144. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  145. return self::$_imports[$alias]=$className;
  146. if(($path=self::getPathOfAlias($alias))!==false)
  147. {
  148. if($isClass)
  149. {
  150. if($forceInclude)
  151. {
  152. if(is_file($path.'.php'))
  153. require($path.'.php');
  154. else
  155. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file.',array('{alias}'=>$alias)));
  156. self::$_imports[$alias]=$className;
  157. }
  158. else
  159. self::$classMap[$className]=$path.'.php';
  160. return $className;
  161. }
  162. else // a directory
  163. {
  164. if(self::$_includePaths===null)
  165. {
  166. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  167. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  168. unset(self::$_includePaths[$pos]);
  169. }
  170. array_unshift(self::$_includePaths,$path);
  171. if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  172. self::$enableIncludePath=false;
  173. return self::$_imports[$alias]=$path;
  174. }
  175. }
  176. else
  177. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  178. array('{alias}'=>$alias)));
  179. }
  180. public static function getPathOfAlias($alias)
  181. {
  182. if(isset(self::$_aliases[$alias]))
  183. return self::$_aliases[$alias];
  184. else if(($pos=strpos($alias,'.'))!==false)
  185. {
  186. $rootAlias=substr($alias,0,$pos);
  187. if(isset(self::$_aliases[$rootAlias]))
  188. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  189. else if(self::$_app instanceof CWebApplication)
  190. {
  191. if(self::$_app->findModule($rootAlias)!==null)
  192. return self::getPathOfAlias($alias);
  193. }
  194. }
  195. return false;
  196. }
  197. public static function setPathOfAlias($alias,$path)
  198. {
  199. if(empty($path))
  200. unset(self::$_aliases[$alias]);
  201. else
  202. self::$_aliases[$alias]=rtrim($path,'\\/');
  203. }
  204. public static function autoload($className)
  205. {
  206. // use include so that the error PHP file may appear
  207. if(isset(self::$classMap[$className]))
  208. include(self::$classMap[$className]);
  209. else if(isset(self::$_coreClasses[$className]))
  210. include(YII_PATH.self::$_coreClasses[$className]);
  211. else
  212. {
  213. // include class file relying on include_path
  214. if(strpos($className,'\\')===false) // class without namespace
  215. {
  216. if(self::$enableIncludePath===false)
  217. {
  218. foreach(self::$_includePaths as $path)
  219. {
  220. $classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
  221. if(is_file($classFile))
  222. {
  223. include($classFile);
  224. break;
  225. }
  226. }
  227. }
  228. else
  229. include($className.'.php');
  230. }
  231. else // class name with namespace in PHP 5.3
  232. {
  233. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  234. if(($path=self::getPathOfAlias($namespace))!==false)
  235. include($path.'.php');
  236. else
  237. return false;
  238. }
  239. return class_exists($className,false) || interface_exists($className,false);
  240. }
  241. return true;
  242. }
  243. public static function trace($msg,$category='application')
  244. {
  245. if(YII_DEBUG)
  246. self::log($msg,CLogger::LEVEL_TRACE,$category);
  247. }
  248. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  249. {
  250. if(self::$_logger===null)
  251. self::$_logger=new CLogger;
  252. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  253. {
  254. $traces=debug_backtrace();
  255. $count=0;
  256. foreach($traces as $trace)
  257. {
  258. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  259. {
  260. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  261. if(++$count>=YII_TRACE_LEVEL)
  262. break;
  263. }
  264. }
  265. }
  266. self::$_logger->log($msg,$level,$category);
  267. }
  268. public static function beginProfile($token,$category='application')
  269. {
  270. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  271. }
  272. public static function endProfile($token,$category='application')
  273. {
  274. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  275. }
  276. public static function getLogger()
  277. {
  278. if(self::$_logger!==null)
  279. return self::$_logger;
  280. else
  281. return self::$_logger=new CLogger;
  282. }
  283. public static function setLogger($logger)
  284. {
  285. self::$_logger=$logger;
  286. }
  287. public static function powered()
  288. {
  289. return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
  290. }
  291. public static function t($category,$message,$params=array(),$source=null,$language=null)
  292. {
  293. if(self::$_app!==null)
  294. {
  295. if($source===null)
  296. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  297. if(($source=self::$_app->getComponent($source))!==null)
  298. $message=$source->translate($category,$message,$language);
  299. }
  300. if($params===array())
  301. return $message;
  302. if(!is_array($params))
  303. $params=array($params);
  304. if(isset($params[0])) // number choice
  305. {
  306. if(strpos($message,'|')!==false)
  307. {
  308. if(strpos($message,'#')===false)
  309. {
  310. $chunks=explode('|',$message);
  311. $expressions=self::$_app->getLocale($language)->getPluralRules();
  312. if($n=min(count($chunks),count($expressions)))
  313. {
  314. for($i=0;$i<$n;$i++)
  315. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  316. $message=implode('|',$chunks);
  317. }
  318. }
  319. $message=CChoiceFormat::format($message,$params[0]);
  320. }
  321. if(!isset($params['{n}']))
  322. $params['{n}']=$params[0];
  323. unset($params[0]);
  324. }
  325. return $params!==array() ? strtr($message,$params) : $message;
  326. }
  327. public static function registerAutoloader($callback, $append=false)
  328. {
  329. if($append)
  330. {
  331. self::$enableIncludePath=false;
  332. spl_autoload_register($callback);
  333. }
  334. else
  335. {
  336. spl_autoload_unregister(array('YiiBase','autoload'));
  337. spl_autoload_register($callback);
  338. spl_autoload_register(array('YiiBase','autoload'));
  339. }
  340. }
  341. private static $_coreClasses=array(
  342. 'CApplication' => '/base/CApplication.php',
  343. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  344. 'CBehavior' => '/base/CBehavior.php',
  345. 'CComponent' => '/base/CComponent.php',
  346. 'CErrorEvent' => '/base/CErrorEvent.php',
  347. 'CErrorHandler' => '/base/CErrorHandler.php',
  348. 'CException' => '/base/CException.php',
  349. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  350. 'CHttpException' => '/base/CHttpException.php',
  351. 'CModel' => '/base/CModel.php',
  352. 'CModelBehavior' => '/base/CModelBehavior.php',
  353. 'CModelEvent' => '/base/CModelEvent.php',
  354. 'CModule' => '/base/CModule.php',
  355. 'CSecurityManager' => '/base/CSecurityManager.php',
  356. 'CStatePersister' => '/base/CStatePersister.php',
  357. 'CApcCache' => '/caching/CApcCache.php',
  358. 'CCache' => '/caching/CCache.php',
  359. 'CDbCache' => '/caching/CDbCache.php',
  360. 'CDummyCache' => '/caching/CDummyCache.php',
  361. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  362. 'CFileCache' => '/caching/CFileCache.php',
  363. 'CMemCache' => '/caching/CMemCache.php',
  364. 'CWinCache' => '/caching/CWinCache.php',
  365. 'CXCache' => '/caching/CXCache.php',
  366. 'CZendDataCache' => '/caching/CZendDataCache.php',
  367. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  368. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  369. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  370. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  371. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  372. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  373. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  374. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  375. 'CConfiguration' => '/collections/CConfiguration.php',
  376. 'CList' => '/collections/CList.php',
  377. 'CListIterator' => '/collections/CListIterator.php',
  378. 'CMap' => '/collections/CMap.php',
  379. 'CMapIterator' => '/collections/CMapIterator.php',
  380. 'CQueue' => '/collections/CQueue.php',
  381. 'CQueueIterator' => '/collections/CQueueIterator.php',
  382. 'CStack' => '/collections/CStack.php',
  383. 'CStackIterator' => '/collections/CStackIterator.php',
  384. 'CTypedList' => '/collections/CTypedList.php',
  385. 'CTypedMap' => '/collections/CTypedMap.php',
  386. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  387. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  388. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  389. 'CHelpCommand' => '/console/CHelpCommand.php',
  390. 'CDbCommand' => '/db/CDbCommand.php',
  391. 'CDbConnection' => '/db/CDbConnection.php',
  392. 'CDbDataReader' => '/db/CDbDataReader.php',
  393. 'CDbException' => '/db/CDbException.php',
  394. 'CDbMigration' => '/db/CDbMigration.php',
  395. 'CDbTransaction' => '/db/CDbTransaction.php',
  396. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  397. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  398. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  399. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  400. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  401. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  402. 'CDbExpression' => '/db/schema/CDbExpression.php',
  403. 'CDbSchema' => '/db/schema/CDbSchema.php',
  404. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  405. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  406. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  407. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  408. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  409. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  410. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  411. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  412. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  413. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  414. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  415. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  416. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  417. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  418. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  419. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  420. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  421. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  422. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  423. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  424. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  425. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  426. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  427. 'CLocale' => '/i18n/CLocale.php',
  428. 'CMessageSource' => '/i18n/CMessageSource.php',
  429. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  430. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  431. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  432. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  433. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  434. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  435. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  436. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  437. 'CLogFilter' => '/logging/CLogFilter.php',
  438. 'CLogRoute' => '/logging/CLogRoute.php',
  439. 'CLogRouter' => '/logging/CLogRouter.php',
  440. 'CLogger' => '/logging/CLogger.php',
  441. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  442. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  443. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  444. 'CFileHelper' => '/utils/CFileHelper.php',
  445. 'CFormatter' => '/utils/CFormatter.php',
  446. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  447. 'CPropertyValue' => '/utils/CPropertyValue.php',
  448. 'CTimestamp' => '/utils/CTimestamp.php',
  449. 'CVarDumper' => '/utils/CVarDumper.php',
  450. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  451. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  452. 'CCompareValidator' => '/validators/CCompareValidator.php',
  453. 'CDateValidator' => '/validators/CDateValidator.php',
  454. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  455. 'CEmailValidator' => '/validators/CEmailValidator.php',
  456. 'CExistValidator' => '/validators/CExistValidator.php',
  457. 'CFileValidator' => '/validators/CFileValidator.php',
  458. 'CFilterValidator' => '/validators/CFilterValidator.php',
  459. 'CInlineValidator' => '/validators/CInlineValidator.php',
  460. 'CNumberValidator' => '/validators/CNumberValidator.php',
  461. 'CRangeValidator' => '/validators/CRangeValidator.php',
  462. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  463. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  464. 'CSafeValidator' => '/validators/CSafeValidator.php',
  465. 'CStringValidator' => '/validators/CStringValidator.php',
  466. 'CTypeValidator' => '/validators/CTypeValidator.php',
  467. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  468. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  469. 'CUrlValidator' => '/validators/CUrlValidator.php',
  470. 'CValidator' => '/validators/CValidator.php',
  471. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  472. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  473. 'CAssetManager' => '/web/CAssetManager.php',
  474. 'CBaseController' => '/web/CBaseController.php',
  475. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  476. 'CClientScript' => '/web/CClientScript.php',
  477. 'CController' => '/web/CController.php',
  478. 'CDataProvider' => '/web/CDataProvider.php',
  479. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  480. 'CExtController' => '/web/CExtController.php',
  481. 'CFormModel' => '/web/CFormModel.php',
  482. 'CHttpCookie' => '/web/CHttpCookie.php',
  483. 'CHttpRequest' => '/web/CHttpRequest.php',
  484. 'CHttpSession' => '/web/CHttpSession.php',
  485. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  486. 'COutputEvent' => '/web/COutputEvent.php',
  487. 'CPagination' => '/web/CPagination.php',
  488. 'CSort' => '/web/CSort.php',
  489. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  490. 'CTheme' => '/web/CTheme.php',
  491. 'CThemeManager' => '/web/CThemeManager.php',
  492. 'CUploadedFile' => '/web/CUploadedFile.php',
  493. 'CUrlManager' => '/web/CUrlManager.php',
  494. 'CWebApplication' => '/web/CWebApplication.php',
  495. 'CWebModule' => '/web/CWebModule.php',
  496. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  497. 'CAction' => '/web/actions/CAction.php',
  498. 'CInlineAction' => '/web/actions/CInlineAction.php',
  499. 'CViewAction' => '/web/actions/CViewAction.php',
  500. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  501. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  502. 'CAuthItem' => '/web/auth/CAuthItem.php',
  503. 'CAuthManager' => '/web/auth/CAuthManager.php',
  504. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  505. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  506. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  507. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  508. 'CWebUser' => '/web/auth/CWebUser.php',
  509. 'CFilter' => '/web/filters/CFilter.php',
  510. 'CFilterChain' => '/web/filters/CFilterChain.php',
  511. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  512. 'CForm' => '/web/form/CForm.php',
  513. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  514. 'CFormElement' => '/web/form/CFormElement.php',
  515. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  516. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  517. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  518. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  519. 'CHtml' => '/web/helpers/CHtml.php',
  520. 'CJSON' => '/web/helpers/CJSON.php',
  521. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  522. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  523. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  524. 'CWebService' => '/web/services/CWebService.php',
  525. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  526. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  527. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  528. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  529. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  530. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  531. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  532. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  533. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  534. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  535. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  536. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  537. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  538. 'COutputCache' => '/web/widgets/COutputCache.php',
  539. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  540. 'CStarRating' => '/web/widgets/CStarRating.php',
  541. 'CTabView' => '/web/widgets/CTabView.php',
  542. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  543. 'CTreeView' => '/web/widgets/CTreeView.php',
  544. 'CWidget' => '/web/widgets/CWidget.php',
  545. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  546. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  547. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  548. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  549. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  550. );
  551. }
  552. spl_autoload_register(array('YiiBase','autoload'));
  553. class Yii extends YiiBase
  554. {
  555. }
  556. class CComponent
  557. {
  558. private $_e;
  559. private $_m;
  560. public function __get($name)
  561. {
  562. $getter='get'.$name;
  563. if(method_exists($this,$getter))
  564. return $this->$getter();
  565. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  566. {
  567. // duplicating getEventHandlers() here for performance
  568. $name=strtolower($name);
  569. if(!isset($this->_e[$name]))
  570. $this->_e[$name]=new CList;
  571. return $this->_e[$name];
  572. }
  573. else if(isset($this->_m[$name]))
  574. return $this->_m[$name];
  575. else if(is_array($this->_m))
  576. {
  577. foreach($this->_m as $object)
  578. {
  579. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  580. return $object->$name;
  581. }
  582. }
  583. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  584. array('{class}'=>get_class($this), '{property}'=>$name)));
  585. }
  586. public function __set($name,$value)
  587. {
  588. $setter='set'.$name;
  589. if(method_exists($this,$setter))
  590. return $this->$setter($value);
  591. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  592. {
  593. // duplicating getEventHandlers() here for performance
  594. $name=strtolower($name);
  595. if(!isset($this->_e[$name]))
  596. $this->_e[$name]=new CList;
  597. return $this->_e[$name]->add($value);
  598. }
  599. else if(is_array($this->_m))
  600. {
  601. foreach($this->_m as $object)
  602. {
  603. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  604. return $object->$name=$value;
  605. }
  606. }
  607. if(method_exists($this,'get'.$name))
  608. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  609. array('{class}'=>get_class($this), '{property}'=>$name)));
  610. else
  611. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  612. array('{class}'=>get_class($this), '{property}'=>$name)));
  613. }
  614. public function __isset($name)
  615. {
  616. $getter='get'.$name;
  617. if(method_exists($this,$getter))
  618. return $this->$getter()!==null;
  619. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  620. {
  621. $name=strtolower($name);
  622. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  623. }
  624. else if(is_array($this->_m))
  625. {
  626. if(isset($this->_m[$name]))
  627. return true;
  628. foreach($this->_m as $object)
  629. {
  630. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  631. return $object->$name!==null;
  632. }
  633. }
  634. return false;
  635. }
  636. public function __unset($name)
  637. {
  638. $setter='set'.$name;
  639. if(method_exists($this,$setter))
  640. $this->$setter(null);
  641. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  642. unset($this->_e[strtolower($name)]);
  643. else if(is_array($this->_m))
  644. {
  645. if(isset($this->_m[$name]))
  646. $this->detachBehavior($name);
  647. else
  648. {
  649. foreach($this->_m as $object)
  650. {
  651. if($object->getEnabled())
  652. {
  653. if(property_exists($object,$name))
  654. return $object->$name=null;
  655. else if($object->canSetProperty($name))
  656. return $object->$setter(null);
  657. }
  658. }
  659. }
  660. }
  661. else if(method_exists($this,'get'.$name))
  662. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  663. array('{class}'=>get_class($this), '{property}'=>$name)));
  664. }
  665. public function __call($name,$parameters)
  666. {
  667. if($this->_m!==null)
  668. {
  669. foreach($this->_m as $object)
  670. {
  671. if($object->getEnabled() && method_exists($object,$name))
  672. return call_user_func_array(array($object,$name),$parameters);
  673. }
  674. }
  675. if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)
  676. return call_user_func_array($this->$name, $parameters);
  677. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  678. array('{class}'=>get_class($this), '{name}'=>$name)));
  679. }
  680. public function asa($behavior)
  681. {
  682. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  683. }
  684. public function attachBehaviors($behaviors)
  685. {
  686. foreach($behaviors as $name=>$behavior)
  687. $this->attachBehavior($name,$behavior);
  688. }
  689. public function detachBehaviors()
  690. {
  691. if($this->_m!==null)
  692. {
  693. foreach($this->_m as $name=>$behavior)
  694. $this->detachBehavior($name);
  695. $this->_m=null;
  696. }
  697. }
  698. public function attachBehavior($name,$behavior)
  699. {
  700. if(!($behavior instanceof IBehavior))
  701. $behavior=Yii::createComponent($behavior);
  702. $behavior->setEnabled(true);
  703. $behavior->attach($this);
  704. return $this->_m[$name]=$behavior;
  705. }
  706. public function detachBehavior($name)
  707. {
  708. if(isset($this->_m[$name]))
  709. {
  710. $this->_m[$name]->detach($this);
  711. $behavior=$this->_m[$name];
  712. unset($this->_m[$name]);
  713. return $behavior;
  714. }
  715. }
  716. public function enableBehaviors()
  717. {
  718. if($this->_m!==null)
  719. {
  720. foreach($this->_m as $behavior)
  721. $behavior->setEnabled(true);
  722. }
  723. }
  724. public function disableBehaviors()
  725. {
  726. if($this->_m!==null)
  727. {
  728. foreach($this->_m as $behavior)
  729. $behavior->setEnabled(false);
  730. }
  731. }
  732. public function enableBehavior($name)
  733. {
  734. if(isset($this->_m[$name]))
  735. $this->_m[$name]->setEnabled(true);
  736. }
  737. public function disableBehavior($name)
  738. {
  739. if(isset($this->_m[$name]))
  740. $this->_m[$name]->setEnabled(false);
  741. }
  742. public function hasProperty($name)
  743. {
  744. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  745. }
  746. public function canGetProperty($name)
  747. {
  748. return method_exists($this,'get'.$name);
  749. }
  750. public function canSetProperty($name)
  751. {
  752. return method_exists($this,'set'.$name);
  753. }
  754. public function hasEvent($name)
  755. {
  756. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  757. }
  758. public function hasEventHandler($name)
  759. {
  760. $name=strtolower($name);
  761. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  762. }
  763. public function getEventHandlers($name)
  764. {
  765. if($this->hasEvent($name))
  766. {
  767. $name=strtolower($name);
  768. if(!isset($this->_e[$name]))
  769. $this->_e[$name]=new CList;
  770. return $this->_e[$name];
  771. }
  772. else
  773. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  774. array('{class}'=>get_class($this), '{event}'=>$name)));
  775. }
  776. public function attachEventHandler($name,$handler)
  777. {
  778. $this->getEventHandlers($name)->add($handler);
  779. }
  780. public function detachEventHandler($name,$handler)
  781. {
  782. if($this->hasEventHandler($name))
  783. return $this->getEventHandlers($name)->remove($handler)!==false;
  784. else
  785. return false;
  786. }
  787. public function raiseEvent($name,$event)
  788. {
  789. $name=strtolower($name);
  790. if(isset($this->_e[$name]))
  791. {
  792. foreach($this->_e[$name] as $handler)
  793. {
  794. if(is_string($handler))
  795. call_user_func($handler,$event);
  796. else if(is_callable($handler,true))
  797. {
  798. if(is_array($handler))
  799. {
  800. // an array: 0 - object, 1 - method name
  801. list($object,$method)=$handler;
  802. if(is_string($object)) // static method call
  803. call_user_func($handler,$event);
  804. else if(method_exists($object,$method))
  805. $object->$method($event);
  806. else
  807. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  808. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  809. }
  810. else // PHP 5.3: anonymous function
  811. call_user_func($handler,$event);
  812. }
  813. else
  814. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  815. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  816. // stop further handling if param.handled is set true
  817. if(($event instanceof CEvent) && $event->handled)
  818. return;
  819. }
  820. }
  821. else if(YII_DEBUG && !$this->hasEvent($name))
  822. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  823. array('{class}'=>get_class($this), '{event}'=>$name)));
  824. }
  825. public function evaluateExpression($_expression_,$_data_=array())
  826. {
  827. if(is_string($_expression_))
  828. {
  829. extract($_data_);
  830. return eval('return '.$_expression_.';');
  831. }
  832. else
  833. {
  834. $_data_[]=$this;
  835. return call_user_func_array($_expression_, $_data_);
  836. }
  837. }
  838. }
  839. class CEvent extends CComponent
  840. {
  841. public $sender;
  842. public $handled=false;
  843. public $params;
  844. public function __construct($sender=null,$params=null)
  845. {
  846. $this->sender=$sender;
  847. $this->params=$params;
  848. }
  849. }
  850. class CEnumerable
  851. {
  852. }
  853. abstract class CModule extends CComponent
  854. {
  855. public $preload=array();
  856. public $behaviors=array();
  857. private $_id;
  858. private $_parentModule;
  859. private $_basePath;
  860. private $_modulePath;
  861. private $_params;
  862. private $_modules=array();
  863. private $_moduleConfig=array();
  864. private $_components=array();
  865. private $_componentConfig=array();
  866. public function __construct($id,$parent,$config=null)
  867. {
  868. $this->_id=$id;
  869. $this->_parentModule=$parent;
  870. // set basePath at early as possible to avoid trouble
  871. if(is_string($config))
  872. $config=require($config);
  873. if(isset($config['basePath']))
  874. {
  875. $this->setBasePath($config['basePath']);
  876. unset($config['basePath']);
  877. }
  878. Yii::setPathOfAlias($id,$this->getBasePath());
  879. $this->preinit();
  880. $this->configure($config);
  881. $this->attachBehaviors($this->behaviors);
  882. $this->preloadComponents();
  883. $this->init();
  884. }
  885. public function __get($name)
  886. {
  887. if($this->hasComponent($name))
  888. return $this->getComponent($name);
  889. else
  890. return parent::__get($name);
  891. }
  892. public function __isset($name)
  893. {
  894. if($this->hasComponent($name))
  895. return $this->getComponent($name)!==null;
  896. else
  897. return parent::__isset($name);
  898. }
  899. public function getId()
  900. {
  901. return $this->_id;
  902. }
  903. public function setId($id)
  904. {
  905. $this->_id=$id;
  906. }
  907. public function getBasePath()
  908. {
  909. if($this->_basePath===null)
  910. {
  911. $class=new ReflectionClass(get_class($this));
  912. $this->_basePath=dirname($class->getFileName());
  913. }
  914. return $this->_basePath;
  915. }
  916. public function setBasePath($path)
  917. {
  918. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  919. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  920. array('{path}'=>$path)));
  921. }
  922. public function getParams()
  923. {
  924. if($this->_params!==null)
  925. return $this->_params;
  926. else
  927. {
  928. $this->_params=new CAttributeCollection;
  929. $this->_params->caseSensitive=true;
  930. return $this->_params;
  931. }
  932. }
  933. public function setParams($value)
  934. {
  935. $params=$this->getParams();
  936. foreach($value as $k=>$v)
  937. $params->add($k,$v);
  938. }
  939. public function getModulePath()
  940. {
  941. if($this->_modulePath!==null)
  942. return $this->_modulePath;
  943. else
  944. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  945. }
  946. public function setModulePath($value)
  947. {
  948. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  949. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  950. array('{path}'=>$value)));
  951. }
  952. public function setImport($aliases)
  953. {
  954. foreach($aliases as $alias)
  955. Yii::import($alias);
  956. }
  957. public function setAliases($mappings)
  958. {
  959. foreach($mappings as $name=>$alias)
  960. {
  961. if(($path=Yii::getPathOfAlias($alias))!==false)
  962. Yii::setPathOfAlias($name,$path);
  963. else
  964. Yii::setPathOfAlias($name,$alias);
  965. }
  966. }
  967. public function getParentModule()
  968. {
  969. return $this->_parentModule;
  970. }
  971. public function getModule($id)
  972. {
  973. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  974. return $this->_modules[$id];
  975. else if(isset($this->_moduleConfig[$id]))
  976. {
  977. $config=$this->_moduleConfig[$id];
  978. if(!isset($config['enabled']) || $config['enabled'])
  979. {
  980. $class=$config['class'];
  981. unset($config['class'], $config['enabled']);
  982. if($this===Yii::app())
  983. $module=Yii::createComponent($class,$id,null,$config);
  984. else
  985. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  986. return $this->_modules[$id]=$module;
  987. }
  988. }
  989. }
  990. public function hasModule($id)
  991. {
  992. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  993. }
  994. public function getModules()
  995. {
  996. return $this->_moduleConfig;
  997. }
  998. public function setModules($modules)
  999. {
  1000. foreach($modules as $id=>$module)
  1001. {
  1002. if(is_int($id))
  1003. {
  1004. $id=$module;
  1005. $module=array();
  1006. }
  1007. if(!isset($module['class']))
  1008. {
  1009. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1010. $module['class']=$id.'.'.ucfirst($id).'Module';
  1011. }
  1012. if(isset($this->_moduleConfig[$id]))
  1013. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1014. else
  1015. $this->_moduleConfig[$id]=$module;
  1016. }
  1017. }
  1018. public function hasComponent($id)
  1019. {
  1020. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1021. }
  1022. public function getComponent($id,$createIfNull=true)
  1023. {
  1024. if(isset($this->_components[$id]))
  1025. return $this->_components[$id];
  1026. else if(isset($this->_componentConfig[$id]) && $createIfNull)
  1027. {
  1028. $config=$this->_componentConfig[$id];
  1029. if(!isset($config['enabled']) || $config['enabled'])
  1030. {
  1031. unset($config['enabled']);
  1032. $component=Yii::createComponent($config);
  1033. $component->init();
  1034. return $this->_components[$id]=$component;
  1035. }
  1036. }
  1037. }
  1038. public function setComponent($id,$component)
  1039. {
  1040. if($component===null)
  1041. unset($this->_components[$id]);
  1042. else
  1043. {
  1044. $this->_components[$id]=$component;
  1045. if(!$component->getIsInitialized())
  1046. $component->init();
  1047. }
  1048. }
  1049. public function getComponents($loadedOnly=true)
  1050. {
  1051. if($loadedOnly)
  1052. return $this->_components;
  1053. else
  1054. return array_merge($this->_componentConfig, $this->_components);
  1055. }
  1056. public function setComponents($components,$merge=true)
  1057. {
  1058. foreach($components as $id=>$component)
  1059. {
  1060. if($component instanceof IApplicationComponent)
  1061. $this->setComponent($id,$component);
  1062. else if(isset($this->_componentConfig[$id]) && $merge)
  1063. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1064. else
  1065. $this->_componentConfig[$id]=$component;
  1066. }
  1067. }
  1068. public function configure($config)
  1069. {
  1070. if(is_array($config))
  1071. {
  1072. foreach($config as $key=>$value)
  1073. $this->$key=$value;
  1074. }
  1075. }
  1076. protected function preloadComponents()
  1077. {
  1078. foreach($this->preload as $id)
  1079. $this->getComponent($id);
  1080. }
  1081. protected function preinit()
  1082. {
  1083. }
  1084. protected function init()
  1085. {
  1086. }
  1087. }
  1088. abstract class CApplication extends CModule
  1089. {
  1090. public $name='My Application';
  1091. public $charset='UTF-8';
  1092. public $sourceLanguage='en_us';
  1093. private $_id;
  1094. private $_basePath;
  1095. private $_runtimePath;
  1096. private $_extensionPath;
  1097. private $_globalState;
  1098. private $_stateChanged;
  1099. private $_ended=false;
  1100. private $_language;
  1101. private $_homeUrl;
  1102. abstract public function processRequest();
  1103. public function __construct($config=null)
  1104. {
  1105. Yii::setApplication($this);
  1106. // set basePath at early as possible to avoid trouble
  1107. if(is_string($config))
  1108. $config=require($config);
  1109. if(isset($config['basePath']))
  1110. {
  1111. $this->setBasePath($config['basePath']);
  1112. unset($config['basePath']);
  1113. }
  1114. else
  1115. $this->setBasePath('protected');
  1116. Yii::setPathOfAlias('application',$this->getBasePath());
  1117. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1118. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1119. $this->preinit();
  1120. $this->initSystemHandlers();
  1121. $this->registerCoreComponents();
  1122. $this->configure($config);
  1123. $this->attachBehaviors($this->behaviors);
  1124. $this->preloadComponents();
  1125. $this->init();
  1126. }
  1127. public function run()
  1128. {
  1129. if($this->hasEventHandler('onBeginRequest'))
  1130. $this->onBeginRequest(new CEvent($this));
  1131. $this->processRequest();
  1132. if($this->hasEventHandler('onEndRequest'))
  1133. $this->onEndRequest(new CEvent($this));
  1134. }
  1135. public function end($status=0, $exit=true)
  1136. {
  1137. if($this->hasEventHandler('onEndRequest'))
  1138. $this->onEndRequest(new CEvent($this));
  1139. if($exit)
  1140. exit($status);
  1141. }
  1142. public function onBeginRequest($event)
  1143. {
  1144. $this->raiseEvent('onBeginRequest',$event);
  1145. }
  1146. public function onEndRequest($event)
  1147. {
  1148. if(!$this->_ended)
  1149. {
  1150. $this->_ended=true;
  1151. $this->raiseEvent('onEndRequest',$event);
  1152. }
  1153. }
  1154. public function getId()
  1155. {
  1156. if($this->_id!==null)
  1157. return $this->_id;
  1158. else
  1159. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1160. }
  1161. public function setId($id)
  1162. {
  1163. $this->_id=$id;
  1164. }
  1165. public function getBasePath()
  1166. {
  1167. return $this->_basePath;
  1168. }
  1169. public function setBasePath($path)
  1170. {
  1171. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1172. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1173. array('{path}'=>$path)));
  1174. }
  1175. public function getRuntimePath()
  1176. {
  1177. if($this->_runtimePath!==null)
  1178. return $this->_runtimePath;
  1179. else
  1180. {
  1181. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1182. return $this->_runtimePath;
  1183. }
  1184. }
  1185. public function setRuntimePath($path)
  1186. {
  1187. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1188. 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.',
  1189. array('{path}'=>$path)));
  1190. $this->_runtimePath=$runtimePath;
  1191. }
  1192. public function getExtensionPath()
  1193. {
  1194. return Yii::getPathOfAlias('ext');
  1195. }
  1196. public function setExtensionPath($path)
  1197. {
  1198. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1199. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1200. array('{path}'=>$path)));
  1201. Yii::setPathOfAlias('ext',$extensionPath);
  1202. }
  1203. public function getLanguage()
  1204. {
  1205. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1206. }
  1207. public function setLanguage($language)
  1208. {
  1209. $this->_language=$language;
  1210. }
  1211. public function getTimeZone()
  1212. {
  1213. return date_default_timezone_get();
  1214. }
  1215. public function setTimeZone($value)
  1216. {
  1217. date_default_timezone_set($value);
  1218. }
  1219. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1220. {
  1221. if($srcLanguage===null)
  1222. $srcLanguage=$this->sourceLanguage;
  1223. if($language===null)
  1224. $language=$this->getLanguage();
  1225. if($language===$srcLanguage)
  1226. return $srcFile;
  1227. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1228. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1229. }
  1230. public function getLocale($localeID=null)
  1231. {
  1232. return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID);
  1233. }
  1234. public function getLocaleDataPath()
  1235. {
  1236. return CLocale::$dataPath===null ? Yii::getPathOfAlias('system.i18n.data') : CLocale::$dataPath;
  1237. }
  1238. public function setLocaleDataPath($value)
  1239. {
  1240. CLocale::$dataPath=$value;
  1241. }
  1242. public function getNumberFormatter()
  1243. {
  1244. return $this->getLocale()->getNumberFormatter();
  1245. }
  1246. public function getDateFormatter()
  1247. {
  1248. return $this->getLocale()->getDateFormatter();
  1249. }
  1250. public function getDb()
  1251. {
  1252. return $this->getComponent('db');
  1253. }
  1254. public function getErrorHandler()
  1255. {
  1256. return $this->getComponent('errorHandler');
  1257. }
  1258. public function getSecurityManager()
  1259. {
  1260. return $this->getComponent('securityManager');
  1261. }
  1262. public function getStatePersister()
  1263. {
  1264. return $this->getComponent('statePersister');
  1265. }
  1266. public function getCache()
  1267. {
  1268. return $this->getComponent('cache');
  1269. }
  1270. public function getCoreMessages()
  1271. {
  1272. return $this->getComponent('coreMessages');
  1273. }
  1274. public function getMessages()
  1275. {
  1276. return $this->getComponent('messages');
  1277. }
  1278. public function getRequest()
  1279. {
  1280. return $this->getComponent('request');
  1281. }
  1282. public function getUrlManager()
  1283. {
  1284. return $this->getComponent('urlManager');
  1285. }
  1286. public function getController()
  1287. {
  1288. return null;
  1289. }
  1290. public function createUrl($route,$params=array(),$ampersand='&')
  1291. {
  1292. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1293. }
  1294. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1295. {
  1296. $url=$this->createUrl($route,$params,$ampersand);
  1297. if(strpos($url,'http')===0)
  1298. return $url;
  1299. else
  1300. return $this->getRequest()->getHostInfo($schema).$url;
  1301. }
  1302. public function getBaseUrl($absolute=false)
  1303. {
  1304. return $this->getRequest()->getBaseUrl($absolute);
  1305. }
  1306. public function getHomeUrl()
  1307. {
  1308. if($this->_homeUrl===null)
  1309. {
  1310. if($this->getUrlManager()->showScriptName)
  1311. return $this->getRequest()->getScriptUrl();
  1312. else
  1313. return $this->getRequest()->getBaseUrl().'/';
  1314. }
  1315. else
  1316. return $this->_homeUrl;
  1317. }
  1318. public function setHomeUrl($value)
  1319. {
  1320. $this->_homeUrl=$value;
  1321. }
  1322. public function getGlobalState($key,$defaultValue=null)
  1323. {
  1324. if($this->_globalState===null)
  1325. $this->loadGlobalState();
  1326. if(isset($this->_globalState[$key]))
  1327. return $this->_globalState[$key];
  1328. else
  1329. return $defaultValue;
  1330. }
  1331. public function setGlobalState($key,$value,$defaultValue=null)
  1332. {
  1333. if($this->_globalState===null)
  1334. $this->loadGlobalState();
  1335. $changed=$this->_stateChanged;
  1336. if($value===$defaultValue)
  1337. {
  1338. if(isset($this->_globalState[$key]))
  1339. {
  1340. unset($this->_globalState[$key]);
  1341. $this->_stateChanged=true;
  1342. }
  1343. }
  1344. else if(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1345. {
  1346. $this->_globalState[$key]=$value;
  1347. $this->_stateChanged=true;
  1348. }
  1349. if($this->_stateChanged!==$changed)
  1350. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1351. }
  1352. public function clearGlobalState($key)
  1353. {
  1354. $this->setGlobalState($key,true,true);
  1355. }
  1356. public function loadGlobalState()
  1357. {
  1358. $persister=$this->getStatePersister();
  1359. if(($this->_globalState=$persister->load())===null)
  1360. $this->_globalState=array();
  1361. $this->_stateChanged=false;
  1362. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1363. }
  1364. public function saveGlobalState()
  1365. {
  1366. if($this->_stateChanged)
  1367. {
  1368. $this->_stateChanged=false;
  1369. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1370. $this->getStatePersister()->save($this->_globalState);
  1371. }
  1372. }
  1373. public function handleException($exception)
  1374. {
  1375. // disable error capturing to avoid recursive errors
  1376. restore_error_handler();
  1377. restore_exception_handler();
  1378. $category='exception.'.get_class($exception);
  1379. if($exception instanceof CHttpException)
  1380. $category.='.'.$exception->statusCode;
  1381. // php <5.2 doesn't support string conversion auto-magically
  1382. $message=$exception->__toString();
  1383. if(isset($_SERVER['REQUEST_URI']))
  1384. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  1385. if(isset($_SERVER['HTTP_REFERER']))
  1386. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  1387. $message.="\n---";
  1388. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1389. try
  1390. {
  1391. $event=new CExceptionEvent($this,$exception);
  1392. $this->onException($event);
  1393. if(!$event->handled)
  1394. {
  1395. // try an error handler
  1396. if(($handler=$this->getErrorHandler())!==null)
  1397. $handler->handle($event);
  1398. else
  1399. $this->displayException($exception);
  1400. }
  1401. }
  1402. catch(Exception $e)
  1403. {
  1404. $this->displayException($e);
  1405. }
  1406. try
  1407. {
  1408. $this->end(1);
  1409. }
  1410. catch(Exception $e)
  1411. {
  1412. // use the most primitive way to log error
  1413. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1414. $msg .= $e->getTraceAsString()."\n";
  1415. $msg .= "Previous exception:\n";
  1416. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1417. $msg .= $exception->getTraceAsString()."\n";
  1418. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1419. error_log($msg);
  1420. exit(1);
  1421. }
  1422. }
  1423. public function handleError($code,$message,$file,$line)
  1424. {
  1425. if($code & error_reporting())
  1426. {
  1427. // disable error capturing to avoid recursive errors
  1428. restore_error_handler();
  1429. restore_exception_handler();
  1430. $log="$message ($file:$line)\nStack trace:\n";
  1431. $trace=debug_backtrace();
  1432. // skip the first 3 stacks as they do not tell the error position
  1433. if(count($trace)>3)
  1434. $trace=array_slice($trace,3);
  1435. foreach($trace as $i=>$t)
  1436. {
  1437. if(!isset($t['file']))
  1438. $t['file']='unknown';
  1439. if(!isset($t['line']))
  1440. $t['line']=0;
  1441. if(!isset($t['function']))
  1442. $t['function']='unknown';
  1443. $log.="#$i {$t['file']}({$t['line']}): ";
  1444. if(isset($t['object']) && is_object($t['object']))
  1445. $log.=get_class($t['object']).'->';
  1446. $log.="{$t['function']}()\n";
  1447. }
  1448. if(isset($_SERVER['REQUEST_URI']))
  1449. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1450. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1451. try
  1452. {
  1453. Yii::import('CErrorEvent',true);
  1454. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1455. $this->onError($event);
  1456. if(!$event->handled)
  1457. {
  1458. // try an error handler
  1459. if(($handler=$this->getErrorHandler())!==null)
  1460. $handler->handle($event);
  1461. else
  1462. $this->displayError($code,$message,$file,$line);
  1463. }
  1464. }
  1465. catch(Exception $e)
  1466. {
  1467. $this->displayException($e);
  1468. }
  1469. try
  1470. {
  1471. $this->end(1);
  1472. }
  1473. catch(Exception $e)
  1474. {
  1475. // use the most primitive way to log error
  1476. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1477. $msg .= $e->getTraceAsString()."\n";
  1478. $msg .= "Previous error:\n";
  1479. $msg .= $log."\n";
  1480. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1481. error_log($msg);
  1482. exit(1);
  1483. }
  1484. }
  1485. }
  1486. public function onException($event)
  1487. {
  1488. $this->raiseEvent('onException',$event);
  1489. }
  1490. public function onError($event)
  1491. {
  1492. $this->raiseEvent('onError',$event);
  1493. }
  1494. public function displayError($code,$message,$file,$line)
  1495. {
  1496. if(YII_DEBUG)
  1497. {
  1498. echo "<h1>PHP Error [$code]</h1>\n";
  1499. echo "<p>$message ($file:$line)</p>\n";
  1500. echo '<pre>';
  1501. $trace=debug_backtrace();
  1502. // skip the first 3 stacks as they do not tell the error position
  1503. if(count($trace)>3)
  1504. $trace=array_slice($trace,3);
  1505. foreach($trace as $i=>$t)
  1506. {
  1507. if(!isset($t['file']))
  1508. $t['file']='unknown';
  1509. if(!isset($t['line']))
  1510. $t['line']=0;
  1511. if(!isset($t['function']))
  1512. $t['function']='unknown';
  1513. echo "#$i {$t['file']}({$t['line']}): ";
  1514. if(isset($t['object']) && is_object($t['object']))
  1515. echo get_class($t['object']).'->';
  1516. echo "{$t['function']}()\n";
  1517. }
  1518. echo '</pre>';
  1519. }
  1520. else
  1521. {
  1522. echo "<h1>PHP Error [$code]</h1>\n";
  1523. echo "<p>$message</p>\n";
  1524. }
  1525. }
  1526. public function displayException($exception)
  1527. {
  1528. if(YII_DEBUG)
  1529. {
  1530. echo '<h1>'.get_class($exception)."</h1>\n";
  1531. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1532. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1533. }
  1534. else
  1535. {
  1536. echo '<h1>'.get_class($exception)."</h1>\n";
  1537. echo '<p>'.$exception->getMessage().'</p>';
  1538. }
  1539. }
  1540. protected function initSystemHandlers()
  1541. {
  1542. if(YII_ENABLE_EXCEPTION_HANDLER)
  1543. set_exception_handler(array($this,'handleException'));
  1544. if(YII_ENABLE_ERROR_HANDLER)
  1545. set_error_handler(array($this,'handleError'),error_reporting());
  1546. }
  1547. protected function registerCoreComponents()
  1548. {
  1549. $components=array(
  1550. 'coreMessages'=>array(
  1551. 'class'=>'CPhpMessageSource',
  1552. 'language'=>'en_us',
  1553. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1554. ),
  1555. 'db'=>array(
  1556. 'class'=>'CDbConnection',
  1557. ),
  1558. 'messages'=>array(
  1559. 'class'=>'CPhpMessageSource',
  1560. ),
  1561. 'errorHandler'=>array(
  1562. 'class'=>'CErrorHandler',
  1563. ),
  1564. 'securityManager'=>array(
  1565. 'class'=>'CSecurityManager',
  1566. ),
  1567. 'statePersister'=>array(
  1568. 'class'=>'CStatePersister',
  1569. ),
  1570. 'urlManager'=>array(
  1571. 'class'=>'CUrlManager',
  1572. ),
  1573. 'request'=>array(
  1574. 'class'=>'CHttpRequest',
  1575. ),
  1576. 'format'=>array(
  1577. 'class'=>'CFormatter',
  1578. ),
  1579. );
  1580. $this->setComponents($components);
  1581. }
  1582. }
  1583. class CWebApplication extends CApplication
  1584. {
  1585. public $defaultController='site';
  1586. public $layout='main';
  1587. public $controllerMap=array();
  1588. public $catchAllRequest;
  1589. private $_controllerPath;
  1590. private $_viewPath;
  1591. private $_systemViewPath;
  1592. private $_layoutPath;
  1593. private $_controller;
  1594. private $_theme;
  1595. public function processRequest()
  1596. {
  1597. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1598. {
  1599. $route=$this->catchAllRequest[0];
  1600. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1601. $_GET[$name]=$value;
  1602. }
  1603. else
  1604. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1605. $this->runController($route);
  1606. }
  1607. protected function registerCoreComponents()
  1608. {
  1609. parent::registerCoreComponents();
  1610. $components=array(
  1611. 'session'=>array(
  1612. 'class'=>'CHttpSession',
  1613. ),
  1614. 'assetManager'=>array(
  1615. 'class'=>'CAssetManager',
  1616. ),
  1617. 'user'=>array(
  1618. 'class'=>'CWebUser',
  1619. ),
  1620. 'themeManager'=>array(
  1621. 'class'=>'CThemeManager',
  1622. ),
  1623. 'authManager'=>array(
  1624. 'class'=>'CPhpAuthManager',
  1625. ),
  1626. 'clientScript'=>array(
  1627. 'class'=>'CClientScript',
  1628. ),
  1629. 'widgetFactory'=>array(
  1630. 'class'=>'CWidgetFactory',
  1631. ),
  1632. );
  1633. $this->setComponents($components);
  1634. }
  1635. public function getAuthManager()
  1636. {
  1637. return $this->getComponent('authManager');
  1638. }
  1639. public function getAssetManager()
  1640. {
  1641. return $this->getComponent('assetManager');
  1642. }
  1643. public function getSession()
  1644. {
  1645. return $this->getComponent('session');
  1646. }
  1647. public function getUser()
  1648. {
  1649. return $this->getComponent('user');
  1650. }
  1651. public function getViewRenderer()
  1652. {
  1653. return $this->getComponent('viewRenderer');
  1654. }
  1655. public function getClientScript()
  1656. {
  1657. return $this->getComponent('clientScript');
  1658. }
  1659. public function getWidgetFactory()
  1660. {
  1661. return $this->getComponent('widgetFactory');
  1662. }
  1663. public function getThemeManager()
  1664. {
  1665. return $this->getComponent('themeManager');
  1666. }
  1667. public function getTheme()
  1668. {
  1669. if(is_string($this->_theme))
  1670. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1671. return $this->_theme;
  1672. }
  1673. public function setTheme($value)
  1674. {
  1675. $this->_theme=$value;
  1676. }
  1677. public function runController($route)
  1678. {
  1679. if(($ca=$this->createController($route))!==null)
  1680. {
  1681. list($controller,$actionID)=$ca;
  1682. $oldController=$this->_controller;
  1683. $this->_controller=$controller;
  1684. $controller->init();
  1685. $controller->run($actionID);
  1686. $this->_controller=$oldController;
  1687. }
  1688. else
  1689. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1690. array('{route}'=>$route===''?$this->defaultController:$route)));
  1691. }
  1692. public function createController($route,$owner=null)
  1693. {
  1694. if($owner===null)
  1695. $owner=$this;
  1696. if(($route=trim($route,'/'))==='')
  1697. $route=$owner->defaultController;
  1698. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1699. $route.='/';
  1700. while(($pos=strpos($route,'/'))!==false)
  1701. {
  1702. $id=substr($route,0,$pos);
  1703. if(!preg_match('/^\w+$/',$id))
  1704. return null;
  1705. if(!$caseSensitive)
  1706. $id=strtolower($id);
  1707. $route=(string)substr($route,$pos+1);
  1708. if(!isset($basePath)) // first segment
  1709. {
  1710. if(isset($owner->controllerMap[$id]))
  1711. {
  1712. return array(
  1713. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1714. $this->parseActionParams($route),
  1715. );
  1716. }
  1717. if(($module=$owner->getModule($id))!==null)
  1718. return $this->createController($route,$module);
  1719. $basePath=$owner->getControllerPath();
  1720. $controllerID='';
  1721. }
  1722. else
  1723. $controllerID.='/';
  1724. $className=ucfirst($id).'Controller';
  1725. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1726. if(is_file($classFile))
  1727. {
  1728. if(!class_exists($className,false))
  1729. require($classFile);
  1730. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1731. {
  1732. $id[0]=strtolower($id[0]);
  1733. return array(
  1734. new $className($controllerID.$id,$owner===$this?null:$owner),
  1735. $this->parseActionParams($route),
  1736. );
  1737. }
  1738. return null;
  1739. }
  1740. $controllerID.=$id;
  1741. $basePath.=DIRECTORY_SEPARATOR.$id;
  1742. }
  1743. }
  1744. protected function parseActionParams($pathInfo)
  1745. {
  1746. if(($pos=strpos($pathInfo,'/'))!==false)
  1747. {
  1748. $manager=$this->getUrlManager();
  1749. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1750. $actionID=substr($pathInfo,0,$pos);
  1751. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1752. }
  1753. else
  1754. return $pathInfo;
  1755. }
  1756. public function getController()
  1757. {
  1758. return $this->_controller;
  1759. }
  1760. public function setController($value)
  1761. {
  1762. $this->_controller=$value;
  1763. }
  1764. public function getControllerPath()
  1765. {
  1766. if($this->_controllerPath!==null)
  1767. return $this->_controllerPath;
  1768. else
  1769. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1770. }
  1771. public function setControllerPath($value)
  1772. {
  1773. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1774. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1775. array('{path}'=>$value)));
  1776. }
  1777. public function getViewPath()
  1778. {
  1779. if($this->_viewPath!==null)
  1780. return $this->_viewPath;
  1781. else
  1782. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1783. }
  1784. public function setViewPath($path)
  1785. {
  1786. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1787. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1788. array('{path}'=>$path)));
  1789. }
  1790. public function getSystemViewPath()
  1791. {
  1792. if($this->_systemViewPath!==null)
  1793. return $this->_systemViewPath;
  1794. else
  1795. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1796. }
  1797. public function setSystemViewPath($path)
  1798. {
  1799. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1800. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1801. array('{path}'=>$path)));
  1802. }
  1803. public function getLayoutPath()
  1804. {
  1805. if($this->_layoutPath!==null)
  1806. return $this->_layoutPath;
  1807. else
  1808. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1809. }
  1810. public function setLayoutPath($path)
  1811. {
  1812. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1813. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1814. array('{path}'=>$path)));
  1815. }
  1816. public function beforeControllerAction($controller,$action)
  1817. {
  1818. return true;
  1819. }
  1820. public function afterControllerAction($controller,$action)
  1821. {
  1822. }
  1823. public function findModule($id)
  1824. {
  1825. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1826. {
  1827. do
  1828. {
  1829. if(($m=$module->getModule($id))!==null)
  1830. return $m;
  1831. } while(($module=$module->getParentModule())!==null);
  1832. }
  1833. if(($m=$this->getModule($id))!==null)
  1834. return $m;
  1835. }
  1836. protected function init()
  1837. {
  1838. parent::init();
  1839. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1840. $this->getRequest();
  1841. }
  1842. }
  1843. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1844. {
  1845. private $_d=array();
  1846. private $_r=false;
  1847. public function __construct($data=null,$readOnly=false)
  1848. {
  1849. if($data!==null)
  1850. $this->copyFrom($data);
  1851. $this->setReadOnly($readOnly);
  1852. }
  1853. public function getReadOnly()
  1854. {
  1855. return $this->_r;
  1856. }
  1857. protected function setReadOnly($value)
  1858. {
  1859. $this->_r=$value;
  1860. }
  1861. public function getIterator()
  1862. {
  1863. return new CMapIterator($this->_d);
  1864. }
  1865. public function count()
  1866. {
  1867. return $this->getCount();
  1868. }
  1869. public function getCount()
  1870. {
  1871. return count($this->_d);
  1872. }
  1873. public function getKeys()
  1874. {
  1875. return array_keys($this->_d);
  1876. }
  1877. public function itemAt($key)
  1878. {
  1879. if(isset($this->_d[$key]))
  1880. return $this->_d[$key];
  1881. else
  1882. return null;
  1883. }
  1884. public function add($key,$value)
  1885. {
  1886. if(!$this->_r)
  1887. {
  1888. if($key===null)
  1889. $this->_d[]=$value;
  1890. else
  1891. $this->_d[$key]=$value;
  1892. }
  1893. else
  1894. throw new CException(Yii::t('yii','The map is read only.'));
  1895. }
  1896. public function remove($key)
  1897. {
  1898. if(!$this->_r)
  1899. {
  1900. if(isset($this->_d[$key]))
  1901. {
  1902. $value=$this->_d[$key];
  1903. unset($this->_d[$key]);
  1904. return $value;
  1905. }
  1906. else
  1907. {
  1908. // it is possible the value is null, which is not detected by isset
  1909. unset($this->_d[$key]);
  1910. return null;
  1911. }
  1912. }
  1913. else
  1914. throw new CException(Yii::t('yii','The map is read only.'));
  1915. }
  1916. public function clear()
  1917. {
  1918. foreach(array_keys($this->_d) as $key)
  1919. $this->remove($key);
  1920. }
  1921. public function contains($key)
  1922. {
  1923. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  1924. }
  1925. public function toArray()
  1926. {
  1927. return $this->_d;
  1928. }
  1929. public function copyFrom($data)
  1930. {
  1931. if(is_array($data) || $data instanceof Traversable)
  1932. {
  1933. if($this->getCount()>0)
  1934. $this->clear();
  1935. if($data instanceof CMap)
  1936. $data=$data->_d;
  1937. foreach($data as $key=>$value)
  1938. $this->add($key,$value);
  1939. }
  1940. else if($data!==null)
  1941. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1942. }
  1943. public function mergeWith($data,$recursive=true)
  1944. {
  1945. if(is_array($data) || $data instanceof Traversable)
  1946. {
  1947. if($data instanceof CMap)
  1948. $data=$data->_d;
  1949. if($recursive)
  1950. {
  1951. if($data instanceof Traversable)
  1952. {
  1953. $d=array();
  1954. foreach($data as $key=>$value)
  1955. $d[$key]=$value;
  1956. $this->_d=self::mergeArray($this->_d,$d);
  1957. }
  1958. else
  1959. $this->_d=self::mergeArray($this->_d,$data);
  1960. }
  1961. else
  1962. {
  1963. foreach($data as $key=>$value)
  1964. $this->add($key,$value);
  1965. }
  1966. }
  1967. else if($data!==null)
  1968. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1969. }
  1970. public static function mergeArray($a,$b)
  1971. {
  1972. $args=func_get_args();
  1973. $res=array_shift($args);
  1974. while(!empty($args))
  1975. {
  1976. $next=array_shift($args);
  1977. foreach($next as $k => $v)
  1978. {
  1979. if(is_integer($k))
  1980. isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
  1981. else if(is_array($v) && isset($res[$k]) && is_array($res[$k]))
  1982. $res[$k]=self::mergeArray($res[$k],$v);
  1983. else
  1984. $res[$k]=$v;
  1985. }
  1986. }
  1987. return $res;
  1988. }
  1989. public function offsetExists($offset)
  1990. {
  1991. return $this->contains($offset);
  1992. }
  1993. public function offsetGet($offset)
  1994. {
  1995. return $this->itemAt($offset);
  1996. }
  1997. public function offsetSet($offset,$item)
  1998. {
  1999. $this->add($offset,$item);
  2000. }
  2001. public function offsetUnset($offset)
  2002. {
  2003. $this->remove($offset);
  2004. }
  2005. }
  2006. class CLogger extends CComponent
  2007. {
  2008. const LEVEL_TRACE='trace';
  2009. const LEVEL_WARNING='warning';
  2010. const LEVEL_ERROR='error';
  2011. const LEVEL_INFO='info';
  2012. const LEVEL_PROFILE='profile';
  2013. public $autoFlush=10000;
  2014. public $autoDump=false;
  2015. private $_logs=array();
  2016. private $_logCount=0;
  2017. private $_levels;
  2018. private $_categories;
  2019. private $_timings;
  2020. private $_processing = false;
  2021. public function log($message,$level='info',$category='application')
  2022. {
  2023. $this->_logs[]=array($message,$level,$category,microtime(true));
  2024. $this->_logCount++;
  2025. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
  2026. {
  2027. $this->_processing=true;
  2028. $this->flush($this->autoDump);
  2029. $this->_processing=false;
  2030. }
  2031. }
  2032. public function getLogs($levels='',$categories='')
  2033. {
  2034. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2035. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2036. if(empty($levels) && empty($categories))
  2037. return $this->_logs;
  2038. else if(empty($levels))
  2039. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByCategory'))));
  2040. else if(empty($categories))
  2041. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  2042. else
  2043. {
  2044. $ret=array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  2045. return array_values(array_filter(array_filter($ret,array($this,'filterByCategory'))));
  2046. }
  2047. }
  2048. private function filterByCategory($value)
  2049. {
  2050. foreach($this->_categories as $category)
  2051. {
  2052. $cat=strtolower($value[2]);
  2053. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2054. return $value;
  2055. }
  2056. return false;
  2057. }
  2058. private function filterByLevel($value)
  2059. {
  2060. return in_array(strtolower($value[1]),$this->_levels)?$value:false;
  2061. }
  2062. public function getExecutionTime()
  2063. {
  2064. return microtime(true)-YII_BEGIN_TIME;
  2065. }
  2066. public function getMemoryUsage()
  2067. {
  2068. if(function_exists('memory_get_usage'))
  2069. return memory_get_usage();
  2070. else
  2071. {
  2072. $output=array();
  2073. if(strncmp(PHP_OS,'WIN',3)===0)
  2074. {
  2075. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2076. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2077. }
  2078. else
  2079. {
  2080. $pid=getmypid();
  2081. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2082. $output=explode(" ",$output[0]);
  2083. return isset($output[1]) ? $output[1]*1024 : 0;
  2084. }
  2085. }
  2086. }
  2087. public function getProfilingResults($token=null,$category=null,$refresh=false)
  2088. {
  2089. if($this->_timings===null || $refresh)
  2090. $this->calculateTimings();
  2091. if($token===null && $category===null)
  2092. return $this->_timings;
  2093. $results=array();
  2094. foreach($this->_timings as $timing)
  2095. {
  2096. if(($category===null || $timing[1]===$category) && ($token===null || $timing[0]===$token))
  2097. $results[]=$timing[2];
  2098. }
  2099. return $results;
  2100. }
  2101. private function calculateTimings()
  2102. {
  2103. $this->_timings=array();
  2104. $stack=array();
  2105. foreach($this->_logs as $log)
  2106. {
  2107. if($log[1]!==CLogger::LEVEL_PROFILE)
  2108. continue;
  2109. list($message,$level,$category,$timestamp)=$log;
  2110. if(!strncasecmp($message,'begin:',6))
  2111. {
  2112. $log[0]=substr($message,6);
  2113. $stack[]=$log;
  2114. }
  2115. else if(!strncasecmp($message,'end:',4))
  2116. {
  2117. $token=substr($message,4);
  2118. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2119. {
  2120. $delta=$log[3]-$last[3];
  2121. $this->_timings[]=array($message,$category,$delta);
  2122. }
  2123. else
  2124. 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.',
  2125. array('{token}'=>$token)));
  2126. }
  2127. }
  2128. $now=microtime(true);
  2129. while(($last=array_pop($stack))!==null)
  2130. {
  2131. $delta=$now-$last[3];
  2132. $this->_timings[]=array($last[0],$last[2],$delta);
  2133. }
  2134. }
  2135. public function flush($dumpLogs=false)
  2136. {
  2137. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2138. $this->_logs=array();
  2139. $this->_logCount=0;
  2140. }
  2141. public function onFlush($event)
  2142. {
  2143. $this->raiseEvent('onFlush', $event);
  2144. }
  2145. }
  2146. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2147. {
  2148. public $behaviors=array();
  2149. private $_initialized=false;
  2150. public function init()
  2151. {
  2152. $this->attachBehaviors($this->behaviors);
  2153. $this->_initialized=true;
  2154. }
  2155. public function getIsInitialized()
  2156. {
  2157. return $this->_initialized;
  2158. }
  2159. }
  2160. class CHttpRequest extends CApplicationComponent
  2161. {
  2162. public $enableCookieValidation=false;
  2163. public $enableCsrfValidation=false;
  2164. public $csrfTokenName='YII_CSRF_TOKEN';
  2165. public $csrfCookie;
  2166. private $_requestUri;
  2167. private $_pathInfo;
  2168. private $_scriptFile;
  2169. private $_scriptUrl;
  2170. private $_hostInfo;
  2171. private $_baseUrl;
  2172. private $_cookies;
  2173. private $_preferredLanguage;
  2174. private $_csrfToken;
  2175. private $_deleteParams;
  2176. private $_putParams;
  2177. public function init()
  2178. {
  2179. parent::init();
  2180. $this->normalizeRequest();
  2181. }
  2182. protected function normalizeRequest()
  2183. {
  2184. // normalize request
  2185. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2186. {
  2187. if(isset($_GET))
  2188. $_GET=$this->stripSlashes($_GET);
  2189. if(isset($_POST))
  2190. $_POST=$this->stripSlashes($_POST);
  2191. if(isset($_REQUEST))
  2192. $_REQUEST=$this->stripSlashes($_REQUEST);
  2193. if(isset($_COOKIE))
  2194. $_COOKIE=$this->stripSlashes($_COOKIE);
  2195. }
  2196. if($this->enableCsrfValidation)
  2197. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2198. }
  2199. public function stripSlashes(&$data)
  2200. {
  2201. return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
  2202. }
  2203. public function getParam($name,$defaultValue=null)
  2204. {
  2205. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2206. }
  2207. public function getQuery($name,$defaultValue=null)
  2208. {
  2209. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2210. }
  2211. public function getPost($name,$defaultValue=null)
  2212. {
  2213. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2214. }
  2215. public function getDelete($name,$defaultValue=null)
  2216. {
  2217. if($this->_deleteParams===null)
  2218. $this->_deleteParams=$this->getIsDeleteRequest() ? $this->getRestParams() : array();
  2219. return isset($this->_deleteParams[$name]) ? $this->_deleteParams[$name] : $defaultValue;
  2220. }
  2221. public function getPut($name,$defaultValue=null)
  2222. {
  2223. if($this->_putParams===null)
  2224. $this->_putParams=$this->getIsPutRequest() ? $this->getRestParams() : array();
  2225. return isset($this->_putParams[$name]) ? $this->_putParams[$name] : $defaultValue;
  2226. }
  2227. protected function getRestParams()
  2228. {
  2229. $result=array();
  2230. if(function_exists('mb_parse_str'))
  2231. mb_parse_str(file_get_contents('php://input'), $result);
  2232. else
  2233. parse_str(file_get_contents('php://input'), $result);
  2234. return $result;
  2235. }
  2236. public function getUrl()
  2237. {
  2238. return $this->getRequestUri();
  2239. }
  2240. public function getHostInfo($schema='')
  2241. {
  2242. if($this->_hostInfo===null)
  2243. {
  2244. if($secure=$this->getIsSecureConnection())
  2245. $http='https';
  2246. else
  2247. $http='http';
  2248. if(isset($_SERVER['HTTP_HOST']))
  2249. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2250. else
  2251. {
  2252. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2253. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2254. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2255. $this->_hostInfo.=':'.$port;
  2256. }
  2257. }
  2258. if($schema!=='')
  2259. {
  2260. $secure=$this->getIsSecureConnection();
  2261. if($secure && $schema==='https' || !$secure && $schema==='http')
  2262. return $this->_hostInfo;
  2263. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2264. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2265. $port=':'.$port;
  2266. else
  2267. $port='';
  2268. $pos=strpos($this->_hostInfo,':');
  2269. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2270. }
  2271. else
  2272. return $this->_hostInfo;
  2273. }
  2274. public function setHostInfo($value)
  2275. {
  2276. $this->_hostInfo=rtrim($value,'/');
  2277. }
  2278. public function getBaseUrl($absolute=false)
  2279. {
  2280. if($this->_baseUrl===null)
  2281. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2282. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2283. }
  2284. public function setBaseUrl($value)
  2285. {
  2286. $this->_baseUrl=$value;
  2287. }
  2288. public function getScriptUrl()
  2289. {
  2290. if($this->_scriptUrl===null)
  2291. {
  2292. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2293. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2294. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2295. else if(basename($_SERVER['PHP_SELF'])===$scriptName)
  2296. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2297. else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2298. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2299. else if(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2300. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2301. else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2302. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2303. else
  2304. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2305. }
  2306. return $this->_scriptUrl;
  2307. }
  2308. public function setScriptUrl($value)
  2309. {
  2310. $this->_scriptUrl='/'.trim($value,'/');
  2311. }
  2312. public function getPathInfo()
  2313. {
  2314. if($this->_pathInfo===null)
  2315. {
  2316. $pathInfo=$this->getRequestUri();
  2317. if(($pos=strpos($pathInfo,'?'))!==false)
  2318. $pathInfo=substr($pathInfo,0,$pos);
  2319. $pathInfo=$this->decodePathInfo($pathInfo);
  2320. $scriptUrl=$this->getScriptUrl();
  2321. $baseUrl=$this->getBaseUrl();
  2322. if(strpos($pathInfo,$scriptUrl)===0)
  2323. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2324. else if($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2325. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2326. else if(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2327. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2328. else
  2329. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2330. $this->_pathInfo=trim($pathInfo,'/');
  2331. }
  2332. return $this->_pathInfo;
  2333. }
  2334. protected function decodePathInfo($pathInfo)
  2335. {
  2336. $pathInfo = urldecode($pathInfo);
  2337. // is it UTF-8?
  2338. // http://w3.org/International/questions/qa-forms-utf-8.html
  2339. if(preg_match('%^(?:
  2340. [\x09\x0A\x0D\x20-\x7E] # ASCII
  2341. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  2342. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  2343. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  2344. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  2345. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  2346. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  2347. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  2348. )*$%xs', $pathInfo))
  2349. {
  2350. return $pathInfo;
  2351. }
  2352. else
  2353. {
  2354. return utf8_encode($pathInfo);
  2355. }
  2356. }
  2357. public function getRequestUri()
  2358. {
  2359. if($this->_requestUri===null)
  2360. {
  2361. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2362. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2363. else if(isset($_SERVER['REQUEST_URI']))
  2364. {
  2365. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2366. if(!empty($_SERVER['HTTP_HOST']))
  2367. {
  2368. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2369. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2370. }
  2371. else
  2372. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2373. }
  2374. else if(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2375. {
  2376. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2377. if(!empty($_SERVER['QUERY_STRING']))
  2378. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2379. }
  2380. else
  2381. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2382. }
  2383. return $this->_requestUri;
  2384. }
  2385. public function getQueryString()
  2386. {
  2387. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2388. }
  2389. public function getIsSecureConnection()
  2390. {
  2391. return isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'],'on');
  2392. }
  2393. public function getRequestType()
  2394. {
  2395. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2396. }
  2397. public function getIsPostRequest()
  2398. {
  2399. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2400. }
  2401. public function getIsDeleteRequest()
  2402. {
  2403. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE');
  2404. }
  2405. public function getIsPutRequest()
  2406. {
  2407. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT');
  2408. }
  2409. public function getIsAjaxRequest()
  2410. {
  2411. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2412. }
  2413. public function getServerName()
  2414. {
  2415. return $_SERVER['SERVER_NAME'];
  2416. }
  2417. public function getServerPort()
  2418. {
  2419. return $_SERVER['SERVER_PORT'];
  2420. }
  2421. public function getUrlReferrer()
  2422. {
  2423. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2424. }
  2425. public function getUserAgent()
  2426. {
  2427. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2428. }
  2429. public function getUserHostAddress()
  2430. {
  2431. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2432. }
  2433. public function getUserHost()
  2434. {
  2435. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2436. }
  2437. public function getScriptFile()
  2438. {
  2439. if($this->_scriptFile!==null)
  2440. return $this->_scriptFile;
  2441. else
  2442. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2443. }
  2444. public function getBrowser($userAgent=null)
  2445. {
  2446. return get_browser($userAgent,true);
  2447. }
  2448. public function getAcceptTypes()
  2449. {
  2450. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2451. }
  2452. private $_port;
  2453. public function getPort()
  2454. {
  2455. if($this->_port===null)
  2456. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2457. return $this->_port;
  2458. }
  2459. public function setPort($value)
  2460. {
  2461. $this->_port=(int)$value;
  2462. $this->_hostInfo=null;
  2463. }
  2464. private $_securePort;
  2465. public function getSecurePort()
  2466. {
  2467. if($this->_securePort===null)
  2468. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2469. return $this->_securePort;
  2470. }
  2471. public function setSecurePort($value)
  2472. {
  2473. $this->_securePort=(int)$value;
  2474. $this->_hostInfo=null;
  2475. }
  2476. public function getCookies()
  2477. {
  2478. if($this->_cookies!==null)
  2479. return $this->_cookies;
  2480. else
  2481. return $this->_cookies=new CCookieCollection($this);
  2482. }
  2483. public function redirect($url,$terminate=true,$statusCode=302)
  2484. {
  2485. if(strpos($url,'/')===0)
  2486. $url=$this->getHostInfo().$url;
  2487. header('Location: '.$url, true, $statusCode);
  2488. if($terminate)
  2489. Yii::app()->end();
  2490. }
  2491. public function getPreferredLanguage()
  2492. {
  2493. if($this->_preferredLanguage===null)
  2494. {
  2495. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && ($n=preg_match_all('/([\w\-_]+)\s*(;\s*q\s*=\s*(\d*\.\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))>0)
  2496. {
  2497. $languages=array();
  2498. for($i=0;$i<$n;++$i)
  2499. $languages[$matches[1][$i]]=empty($matches[3][$i]) ? 1.0 : floatval($matches[3][$i]);
  2500. arsort($languages);
  2501. foreach($languages as $language=>$pref)
  2502. return $this->_preferredLanguage=CLocale::getCanonicalID($language);
  2503. }
  2504. return $this->_preferredLanguage=false;
  2505. }
  2506. return $this->_preferredLanguage;
  2507. }
  2508. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2509. {
  2510. if($mimeType===null)
  2511. {
  2512. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2513. $mimeType='text/plain';
  2514. }
  2515. header('Pragma: public');
  2516. header('Expires: 0');
  2517. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2518. header("Content-type: $mimeType");
  2519. if(ob_get_length()===false)
  2520. header('Content-Length: '.(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content)));
  2521. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2522. header('Content-Transfer-Encoding: binary');
  2523. if($terminate)
  2524. {
  2525. // clean up the application first because the file downloading could take long time
  2526. // which may cause timeout of some resources (such as DB connection)
  2527. Yii::app()->end(0,false);
  2528. echo $content;
  2529. exit(0);
  2530. }
  2531. else
  2532. echo $content;
  2533. }
  2534. public function xSendFile($filePath, $options=array())
  2535. {
  2536. if(!isset($options['forceDownload']) || $options['forceDownload'])
  2537. $disposition='attachment';
  2538. else
  2539. $disposition='inline';
  2540. if(!isset($options['saveName']))
  2541. $options['saveName']=basename($filePath);
  2542. if(!isset($options['mimeType']))
  2543. {
  2544. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2545. $options['mimeType']='text/plain';
  2546. }
  2547. if(!isset($options['xHeader']))
  2548. $options['xHeader']='X-Sendfile';
  2549. if($options['mimeType'] !== null)
  2550. header('Content-type: '.$options['mimeType']);
  2551. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  2552. if(isset($options['addHeaders']))
  2553. {
  2554. foreach($options['addHeaders'] as $header=>$value)
  2555. header($header.': '.$value);
  2556. }
  2557. header(trim($options['xHeader']).': '.$filePath);
  2558. if(!isset($options['terminate']) || $options['terminate'])
  2559. Yii::app()->end();
  2560. }
  2561. public function getCsrfToken()
  2562. {
  2563. if($this->_csrfToken===null)
  2564. {
  2565. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2566. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2567. {
  2568. $cookie=$this->createCsrfCookie();
  2569. $this->_csrfToken=$cookie->value;
  2570. $this->getCookies()->add($cookie->name,$cookie);
  2571. }
  2572. }
  2573. return $this->_csrfToken;
  2574. }
  2575. protected function createCsrfCookie()
  2576. {
  2577. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2578. if(is_array($this->csrfCookie))
  2579. {
  2580. foreach($this->csrfCookie as $name=>$value)
  2581. $cookie->$name=$value;
  2582. }
  2583. return $cookie;
  2584. }
  2585. public function validateCsrfToken($event)
  2586. {
  2587. if($this->getIsPostRequest())
  2588. {
  2589. // only validate POST requests
  2590. $cookies=$this->getCookies();
  2591. if($cookies->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName]))
  2592. {
  2593. $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value;
  2594. $tokenFromPost=$_POST[$this->csrfTokenName];
  2595. $valid=$tokenFromCookie===$tokenFromPost;
  2596. }
  2597. else
  2598. $valid=false;
  2599. if(!$valid)
  2600. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2601. }
  2602. }
  2603. }
  2604. class CCookieCollection extends CMap
  2605. {
  2606. private $_request;
  2607. private $_initialized=false;
  2608. public function __construct(CHttpRequest $request)
  2609. {
  2610. $this->_request=$request;
  2611. $this->copyfrom($this->getCookies());
  2612. $this->_initialized=true;
  2613. }
  2614. public function getRequest()
  2615. {
  2616. return $this->_request;
  2617. }
  2618. protected function getCookies()
  2619. {
  2620. $cookies=array();
  2621. if($this->_request->enableCookieValidation)
  2622. {
  2623. $sm=Yii::app()->getSecurityManager();
  2624. foreach($_COOKIE as $name=>$value)
  2625. {
  2626. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  2627. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  2628. }
  2629. }
  2630. else
  2631. {
  2632. foreach($_COOKIE as $name=>$value)
  2633. $cookies[$name]=new CHttpCookie($name,$value);
  2634. }
  2635. return $cookies;
  2636. }
  2637. public function add($name,$cookie)
  2638. {
  2639. if($cookie instanceof CHttpCookie)
  2640. {
  2641. $this->remove($name);
  2642. parent::add($name,$cookie);
  2643. if($this->_initialized)
  2644. $this->addCookie($cookie);
  2645. }
  2646. else
  2647. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  2648. }
  2649. public function remove($name)
  2650. {
  2651. if(($cookie=parent::remove($name))!==null)
  2652. {
  2653. if($this->_initialized)
  2654. $this->removeCookie($cookie);
  2655. }
  2656. return $cookie;
  2657. }
  2658. protected function addCookie($cookie)
  2659. {
  2660. $value=$cookie->value;
  2661. if($this->_request->enableCookieValidation)
  2662. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  2663. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2664. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2665. else
  2666. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  2667. }
  2668. protected function removeCookie($cookie)
  2669. {
  2670. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2671. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2672. else
  2673. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure);
  2674. }
  2675. }
  2676. class CUrlManager extends CApplicationComponent
  2677. {
  2678. const CACHE_KEY='Yii.CUrlManager.rules';
  2679. const GET_FORMAT='get';
  2680. const PATH_FORMAT='path';
  2681. public $rules=array();
  2682. public $urlSuffix='';
  2683. public $showScriptName=true;
  2684. public $appendParams=true;
  2685. public $routeVar='r';
  2686. public $caseSensitive=true;
  2687. public $matchValue=false;
  2688. public $cacheID='cache';
  2689. public $useStrictParsing=false;
  2690. public $urlRuleClass='CUrlRule';
  2691. private $_urlFormat=self::GET_FORMAT;
  2692. private $_rules=array();
  2693. private $_baseUrl;
  2694. public function init()
  2695. {
  2696. parent::init();
  2697. $this->processRules();
  2698. }
  2699. protected function processRules()
  2700. {
  2701. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  2702. return;
  2703. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  2704. {
  2705. $hash=md5(serialize($this->rules));
  2706. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  2707. {
  2708. $this->_rules=$data[0];
  2709. return;
  2710. }
  2711. }
  2712. foreach($this->rules as $pattern=>$route)
  2713. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2714. if(isset($cache))
  2715. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  2716. }
  2717. public function addRules($rules, $append=true)
  2718. {
  2719. if ($append)
  2720. {
  2721. foreach($rules as $pattern=>$route)
  2722. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2723. }
  2724. else
  2725. {
  2726. foreach($rules as $pattern=>$route)
  2727. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  2728. }
  2729. }
  2730. protected function createUrlRule($route,$pattern)
  2731. {
  2732. if(is_array($route) && isset($route['class']))
  2733. return $route;
  2734. else
  2735. return new $this->urlRuleClass($route,$pattern);
  2736. }
  2737. public function createUrl($route,$params=array(),$ampersand='&')
  2738. {
  2739. unset($params[$this->routeVar]);
  2740. foreach($params as $i=>$param)
  2741. if($param===null)
  2742. $params[$i]='';
  2743. if(isset($params['#']))
  2744. {
  2745. $anchor='#'.$params['#'];
  2746. unset($params['#']);
  2747. }
  2748. else
  2749. $anchor='';
  2750. $route=trim($route,'/');
  2751. foreach($this->_rules as $i=>$rule)
  2752. {
  2753. if(is_array($rule))
  2754. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2755. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  2756. {
  2757. if($rule->hasHostInfo)
  2758. return $url==='' ? '/'.$anchor : $url.$anchor;
  2759. else
  2760. return $this->getBaseUrl().'/'.$url.$anchor;
  2761. }
  2762. }
  2763. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  2764. }
  2765. protected function createUrlDefault($route,$params,$ampersand)
  2766. {
  2767. if($this->getUrlFormat()===self::PATH_FORMAT)
  2768. {
  2769. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  2770. if($this->appendParams)
  2771. {
  2772. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  2773. return $route==='' ? $url : $url.$this->urlSuffix;
  2774. }
  2775. else
  2776. {
  2777. if($route!=='')
  2778. $url.=$this->urlSuffix;
  2779. $query=$this->createPathInfo($params,'=',$ampersand);
  2780. return $query==='' ? $url : $url.'?'.$query;
  2781. }
  2782. }
  2783. else
  2784. {
  2785. $url=$this->getBaseUrl();
  2786. if(!$this->showScriptName)
  2787. $url.='/';
  2788. if($route!=='')
  2789. {
  2790. $url.='?'.$this->routeVar.'='.$route;
  2791. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2792. $url.=$ampersand.$query;
  2793. }
  2794. else if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2795. $url.='?'.$query;
  2796. return $url;
  2797. }
  2798. }
  2799. public function parseUrl($request)
  2800. {
  2801. if($this->getUrlFormat()===self::PATH_FORMAT)
  2802. {
  2803. $rawPathInfo=$request->getPathInfo();
  2804. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  2805. foreach($this->_rules as $i=>$rule)
  2806. {
  2807. if(is_array($rule))
  2808. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2809. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  2810. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  2811. }
  2812. if($this->useStrictParsing)
  2813. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  2814. array('{route}'=>$pathInfo)));
  2815. else
  2816. return $pathInfo;
  2817. }
  2818. else if(isset($_GET[$this->routeVar]))
  2819. return $_GET[$this->routeVar];
  2820. else if(isset($_POST[$this->routeVar]))
  2821. return $_POST[$this->routeVar];
  2822. else
  2823. return '';
  2824. }
  2825. public function parsePathInfo($pathInfo)
  2826. {
  2827. if($pathInfo==='')
  2828. return;
  2829. $segs=explode('/',$pathInfo.'/');
  2830. $n=count($segs);
  2831. for($i=0;$i<$n-1;$i+=2)
  2832. {
  2833. $key=$segs[$i];
  2834. if($key==='') continue;
  2835. $value=$segs[$i+1];
  2836. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  2837. {
  2838. $name=substr($key,0,$pos);
  2839. for($j=$m-1;$j>=0;--$j)
  2840. {
  2841. if($matches[1][$j]==='')
  2842. $value=array($value);
  2843. else
  2844. $value=array($matches[1][$j]=>$value);
  2845. }
  2846. if(isset($_GET[$name]) && is_array($_GET[$name]))
  2847. $value=CMap::mergeArray($_GET[$name],$value);
  2848. $_REQUEST[$name]=$_GET[$name]=$value;
  2849. }
  2850. else
  2851. $_REQUEST[$key]=$_GET[$key]=$value;
  2852. }
  2853. }
  2854. public function createPathInfo($params,$equal,$ampersand, $key=null)
  2855. {
  2856. $pairs = array();
  2857. foreach($params as $k => $v)
  2858. {
  2859. if ($key!==null)
  2860. $k = $key.'['.$k.']';
  2861. if (is_array($v))
  2862. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  2863. else
  2864. $pairs[]=urlencode($k).$equal.urlencode($v);
  2865. }
  2866. return implode($ampersand,$pairs);
  2867. }
  2868. public function removeUrlSuffix($pathInfo,$urlSuffix)
  2869. {
  2870. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  2871. return substr($pathInfo,0,-strlen($urlSuffix));
  2872. else
  2873. return $pathInfo;
  2874. }
  2875. public function getBaseUrl()
  2876. {
  2877. if($this->_baseUrl!==null)
  2878. return $this->_baseUrl;
  2879. else
  2880. {
  2881. if($this->showScriptName)
  2882. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  2883. else
  2884. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  2885. return $this->_baseUrl;
  2886. }
  2887. }
  2888. public function setBaseUrl($value)
  2889. {
  2890. $this->_baseUrl=$value;
  2891. }
  2892. public function getUrlFormat()
  2893. {
  2894. return $this->_urlFormat;
  2895. }
  2896. public function setUrlFormat($value)
  2897. {
  2898. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  2899. $this->_urlFormat=$value;
  2900. else
  2901. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  2902. }
  2903. }
  2904. abstract class CBaseUrlRule extends CComponent
  2905. {
  2906. public $hasHostInfo=false;
  2907. abstract public function createUrl($manager,$route,$params,$ampersand);
  2908. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  2909. }
  2910. class CUrlRule extends CBaseUrlRule
  2911. {
  2912. public $urlSuffix;
  2913. public $caseSensitive;
  2914. public $defaultParams=array();
  2915. public $matchValue;
  2916. public $verb;
  2917. public $parsingOnly=false;
  2918. public $route;
  2919. public $references=array();
  2920. public $routePattern;
  2921. public $pattern;
  2922. public $template;
  2923. public $params=array();
  2924. public $append;
  2925. public $hasHostInfo;
  2926. public function __construct($route,$pattern)
  2927. {
  2928. if(is_array($route))
  2929. {
  2930. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  2931. {
  2932. if(isset($route[$name]))
  2933. $this->$name=$route[$name];
  2934. }
  2935. if(isset($route['pattern']))
  2936. $pattern=$route['pattern'];
  2937. $route=$route[0];
  2938. }
  2939. $this->route=trim($route,'/');
  2940. $tr2['/']=$tr['/']='\\/';
  2941. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  2942. {
  2943. foreach($matches2[1] as $name)
  2944. $this->references[$name]="<$name>";
  2945. }
  2946. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  2947. if($this->verb!==null)
  2948. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  2949. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  2950. {
  2951. $tokens=array_combine($matches[1],$matches[2]);
  2952. foreach($tokens as $name=>$value)
  2953. {
  2954. if($value==='')
  2955. $value='[^\/]+';
  2956. $tr["<$name>"]="(?P<$name>$value)";
  2957. if(isset($this->references[$name]))
  2958. $tr2["<$name>"]=$tr["<$name>"];
  2959. else
  2960. $this->params[$name]=$value;
  2961. }
  2962. }
  2963. $p=rtrim($pattern,'*');
  2964. $this->append=$p!==$pattern;
  2965. $p=trim($p,'/');
  2966. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  2967. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  2968. if($this->append)
  2969. $this->pattern.='/u';
  2970. else
  2971. $this->pattern.='$/u';
  2972. if($this->references!==array())
  2973. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  2974. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  2975. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  2976. array('{route}'=>$route,'{pattern}'=>$pattern)));
  2977. }
  2978. public function createUrl($manager,$route,$params,$ampersand)
  2979. {
  2980. if($this->parsingOnly)
  2981. return false;
  2982. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  2983. $case='';
  2984. else
  2985. $case='i';
  2986. $tr=array();
  2987. if($route!==$this->route)
  2988. {
  2989. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  2990. {
  2991. foreach($this->references as $key=>$name)
  2992. $tr[$name]=$matches[$key];
  2993. }
  2994. else
  2995. return false;
  2996. }
  2997. foreach($this->defaultParams as $key=>$value)
  2998. {
  2999. if(isset($params[$key]))
  3000. {
  3001. if($params[$key]==$value)
  3002. unset($params[$key]);
  3003. else
  3004. return false;
  3005. }
  3006. }
  3007. foreach($this->params as $key=>$value)
  3008. if(!isset($params[$key]))
  3009. return false;
  3010. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  3011. {
  3012. foreach($this->params as $key=>$value)
  3013. {
  3014. if(!preg_match('/'.$value.'/'.$case,$params[$key]))
  3015. return false;
  3016. }
  3017. }
  3018. foreach($this->params as $key=>$value)
  3019. {
  3020. $tr["<$key>"]=urlencode($params[$key]);
  3021. unset($params[$key]);
  3022. }
  3023. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3024. $url=strtr($this->template,$tr);
  3025. if($this->hasHostInfo)
  3026. {
  3027. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  3028. if(stripos($url,$hostInfo)===0)
  3029. $url=substr($url,strlen($hostInfo));
  3030. }
  3031. if(empty($params))
  3032. return $url!=='' ? $url.$suffix : $url;
  3033. if($this->append)
  3034. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  3035. else
  3036. {
  3037. if($url!=='')
  3038. $url.=$suffix;
  3039. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  3040. }
  3041. return $url;
  3042. }
  3043. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  3044. {
  3045. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  3046. return false;
  3047. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3048. $case='';
  3049. else
  3050. $case='i';
  3051. if($this->urlSuffix!==null)
  3052. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3053. // URL suffix required, but not found in the requested URL
  3054. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3055. {
  3056. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3057. if($urlSuffix!='' && $urlSuffix!=='/')
  3058. return false;
  3059. }
  3060. if($this->hasHostInfo)
  3061. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3062. $pathInfo.='/';
  3063. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3064. {
  3065. foreach($this->defaultParams as $name=>$value)
  3066. {
  3067. if(!isset($_GET[$name]))
  3068. $_REQUEST[$name]=$_GET[$name]=$value;
  3069. }
  3070. $tr=array();
  3071. foreach($matches as $key=>$value)
  3072. {
  3073. if(isset($this->references[$key]))
  3074. $tr[$this->references[$key]]=$value;
  3075. else if(isset($this->params[$key]))
  3076. $_REQUEST[$key]=$_GET[$key]=$value;
  3077. }
  3078. if($pathInfo!==$matches[0]) // there're additional GET params
  3079. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3080. if($this->routePattern!==null)
  3081. return strtr($this->route,$tr);
  3082. else
  3083. return $this->route;
  3084. }
  3085. else
  3086. return false;
  3087. }
  3088. }
  3089. abstract class CBaseController extends CComponent
  3090. {
  3091. private $_widgetStack=array();
  3092. abstract public function getViewFile($viewName);
  3093. public function renderFile($viewFile,$data=null,$return=false)
  3094. {
  3095. $widgetCount=count($this->_widgetStack);
  3096. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3097. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3098. else
  3099. $content=$this->renderInternal($viewFile,$data,$return);
  3100. if(count($this->_widgetStack)===$widgetCount)
  3101. return $content;
  3102. else
  3103. {
  3104. $widget=end($this->_widgetStack);
  3105. 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.',
  3106. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3107. }
  3108. }
  3109. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3110. {
  3111. // we use special variable names here to avoid conflict when extracting data
  3112. if(is_array($_data_))
  3113. extract($_data_,EXTR_PREFIX_SAME,'data');
  3114. else
  3115. $data=$_data_;
  3116. if($_return_)
  3117. {
  3118. ob_start();
  3119. ob_implicit_flush(false);
  3120. require($_viewFile_);
  3121. return ob_get_clean();
  3122. }
  3123. else
  3124. require($_viewFile_);
  3125. }
  3126. public function createWidget($className,$properties=array())
  3127. {
  3128. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3129. $widget->init();
  3130. return $widget;
  3131. }
  3132. public function widget($className,$properties=array(),$captureOutput=false)
  3133. {
  3134. if($captureOutput)
  3135. {
  3136. ob_start();
  3137. ob_implicit_flush(false);
  3138. $widget=$this->createWidget($className,$properties);
  3139. $widget->run();
  3140. return ob_get_clean();
  3141. }
  3142. else
  3143. {
  3144. $widget=$this->createWidget($className,$properties);
  3145. $widget->run();
  3146. return $widget;
  3147. }
  3148. }
  3149. public function beginWidget($className,$properties=array())
  3150. {
  3151. $widget=$this->createWidget($className,$properties);
  3152. $this->_widgetStack[]=$widget;
  3153. return $widget;
  3154. }
  3155. public function endWidget($id='')
  3156. {
  3157. if(($widget=array_pop($this->_widgetStack))!==null)
  3158. {
  3159. $widget->run();
  3160. return $widget;
  3161. }
  3162. else
  3163. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3164. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3165. }
  3166. public function beginClip($id,$properties=array())
  3167. {
  3168. $properties['id']=$id;
  3169. $this->beginWidget('CClipWidget',$properties);
  3170. }
  3171. public function endClip()
  3172. {
  3173. $this->endWidget('CClipWidget');
  3174. }
  3175. public function beginCache($id,$properties=array())
  3176. {
  3177. $properties['id']=$id;
  3178. $cache=$this->beginWidget('COutputCache',$properties);
  3179. if($cache->getIsContentCached())
  3180. {
  3181. $this->endCache();
  3182. return false;
  3183. }
  3184. else
  3185. return true;
  3186. }
  3187. public function endCache()
  3188. {
  3189. $this->endWidget('COutputCache');
  3190. }
  3191. public function beginContent($view=null,$data=array())
  3192. {
  3193. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3194. }
  3195. public function endContent()
  3196. {
  3197. $this->endWidget('CContentDecorator');
  3198. }
  3199. }
  3200. class CController extends CBaseController
  3201. {
  3202. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3203. public $layout;
  3204. public $defaultAction='index';
  3205. private $_id;
  3206. private $_action;
  3207. private $_pageTitle;
  3208. private $_cachingStack;
  3209. private $_clips;
  3210. private $_dynamicOutput;
  3211. private $_pageStates;
  3212. private $_module;
  3213. public function __construct($id,$module=null)
  3214. {
  3215. $this->_id=$id;
  3216. $this->_module=$module;
  3217. $this->attachBehaviors($this->behaviors());
  3218. }
  3219. public function init()
  3220. {
  3221. }
  3222. public function filters()
  3223. {
  3224. return array();
  3225. }
  3226. public function actions()
  3227. {
  3228. return array();
  3229. }
  3230. public function behaviors()
  3231. {
  3232. return array();
  3233. }
  3234. public function accessRules()
  3235. {
  3236. return array();
  3237. }
  3238. public function run($actionID)
  3239. {
  3240. if(($action=$this->createAction($actionID))!==null)
  3241. {
  3242. if(($parent=$this->getModule())===null)
  3243. $parent=Yii::app();
  3244. if($parent->beforeControllerAction($this,$action))
  3245. {
  3246. $this->runActionWithFilters($action,$this->filters());
  3247. $parent->afterControllerAction($this,$action);
  3248. }
  3249. }
  3250. else
  3251. $this->missingAction($actionID);
  3252. }
  3253. public function runActionWithFilters($action,$filters)
  3254. {
  3255. if(empty($filters))
  3256. $this->runAction($action);
  3257. else
  3258. {
  3259. $priorAction=$this->_action;
  3260. $this->_action=$action;
  3261. CFilterChain::create($this,$action,$filters)->run();
  3262. $this->_action=$priorAction;
  3263. }
  3264. }
  3265. public function runAction($action)
  3266. {
  3267. $priorAction=$this->_action;
  3268. $this->_action=$action;
  3269. if($this->beforeAction($action))
  3270. {
  3271. if($action->runWithParams($this->getActionParams())===false)
  3272. $this->invalidActionParams($action);
  3273. else
  3274. $this->afterAction($action);
  3275. }
  3276. $this->_action=$priorAction;
  3277. }
  3278. public function getActionParams()
  3279. {
  3280. return $_GET;
  3281. }
  3282. public function invalidActionParams($action)
  3283. {
  3284. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3285. }
  3286. public function processOutput($output)
  3287. {
  3288. Yii::app()->getClientScript()->render($output);
  3289. // if using page caching, we should delay dynamic output replacement
  3290. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3291. {
  3292. $output=$this->processDynamicOutput($output);
  3293. $this->_dynamicOutput=null;
  3294. }
  3295. if($this->_pageStates===null)
  3296. $this->_pageStates=$this->loadPageStates();
  3297. if(!empty($this->_pageStates))
  3298. $this->savePageStates($this->_pageStates,$output);
  3299. return $output;
  3300. }
  3301. public function processDynamicOutput($output)
  3302. {
  3303. if($this->_dynamicOutput)
  3304. {
  3305. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3306. }
  3307. return $output;
  3308. }
  3309. protected function replaceDynamicOutput($matches)
  3310. {
  3311. $content=$matches[0];
  3312. if(isset($this->_dynamicOutput[$matches[1]]))
  3313. {
  3314. $content=$this->_dynamicOutput[$matches[1]];
  3315. $this->_dynamicOutput[$matches[1]]=null;
  3316. }
  3317. return $content;
  3318. }
  3319. public function createAction($actionID)
  3320. {
  3321. if($actionID==='')
  3322. $actionID=$this->defaultAction;
  3323. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3324. return new CInlineAction($this,$actionID);
  3325. else
  3326. {
  3327. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3328. if($action!==null && !method_exists($action,'run'))
  3329. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3330. return $action;
  3331. }
  3332. }
  3333. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3334. {
  3335. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3336. {
  3337. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3338. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3339. }
  3340. else if($pos===false)
  3341. return null;
  3342. // the action is defined in a provider
  3343. $prefix=substr($actionID,0,$pos+1);
  3344. if(!isset($actionMap[$prefix]))
  3345. return null;
  3346. $actionID=(string)substr($actionID,$pos+1);
  3347. $provider=$actionMap[$prefix];
  3348. if(is_string($provider))
  3349. $providerType=$provider;
  3350. else if(is_array($provider) && isset($provider['class']))
  3351. {
  3352. $providerType=$provider['class'];
  3353. if(isset($provider[$actionID]))
  3354. {
  3355. if(is_string($provider[$actionID]))
  3356. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3357. else
  3358. $config=array_merge($provider[$actionID],$config);
  3359. }
  3360. }
  3361. else
  3362. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3363. $class=Yii::import($providerType,true);
  3364. $map=call_user_func(array($class,'actions'));
  3365. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3366. }
  3367. public function missingAction($actionID)
  3368. {
  3369. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3370. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3371. }
  3372. public function getAction()
  3373. {
  3374. return $this->_action;
  3375. }
  3376. public function setAction($value)
  3377. {
  3378. $this->_action=$value;
  3379. }
  3380. public function getId()
  3381. {
  3382. return $this->_id;
  3383. }
  3384. public function getUniqueId()
  3385. {
  3386. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3387. }
  3388. public function getRoute()
  3389. {
  3390. if(($action=$this->getAction())!==null)
  3391. return $this->getUniqueId().'/'.$action->getId();
  3392. else
  3393. return $this->getUniqueId();
  3394. }
  3395. public function getModule()
  3396. {
  3397. return $this->_module;
  3398. }
  3399. public function getViewPath()
  3400. {
  3401. if(($module=$this->getModule())===null)
  3402. $module=Yii::app();
  3403. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3404. }
  3405. public function getViewFile($viewName)
  3406. {
  3407. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3408. return $viewFile;
  3409. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3410. if(($module=$this->getModule())!==null)
  3411. $moduleViewPath=$module->getViewPath();
  3412. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3413. }
  3414. public function getLayoutFile($layoutName)
  3415. {
  3416. if($layoutName===false)
  3417. return false;
  3418. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3419. return $layoutFile;
  3420. if(empty($layoutName))
  3421. {
  3422. $module=$this->getModule();
  3423. while($module!==null)
  3424. {
  3425. if($module->layout===false)
  3426. return false;
  3427. if(!empty($module->layout))
  3428. break;
  3429. $module=$module->getParentModule();
  3430. }
  3431. if($module===null)
  3432. $module=Yii::app();
  3433. $layoutName=$module->layout;
  3434. }
  3435. else if(($module=$this->getModule())===null)
  3436. $module=Yii::app();
  3437. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3438. }
  3439. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3440. {
  3441. if(empty($viewName))
  3442. return false;
  3443. if($moduleViewPath===null)
  3444. $moduleViewPath=$basePath;
  3445. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3446. $extension=$renderer->fileExtension;
  3447. else
  3448. $extension='.php';
  3449. if($viewName[0]==='/')
  3450. {
  3451. if(strncmp($viewName,'//',2)===0)
  3452. $viewFile=$basePath.$viewName;
  3453. else
  3454. $viewFile=$moduleViewPath.$viewName;
  3455. }
  3456. else if(strpos($viewName,'.'))
  3457. $viewFile=Yii::getPathOfAlias($viewName);
  3458. else
  3459. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3460. if(is_file($viewFile.$extension))
  3461. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3462. else if($extension!=='.php' && is_file($viewFile.'.php'))
  3463. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3464. else
  3465. return false;
  3466. }
  3467. public function getClips()
  3468. {
  3469. if($this->_clips!==null)
  3470. return $this->_clips;
  3471. else
  3472. return $this->_clips=new CMap;
  3473. }
  3474. public function forward($route,$exit=true)
  3475. {
  3476. if(strpos($route,'/')===false)
  3477. $this->run($route);
  3478. else
  3479. {
  3480. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3481. $route=$module->getId().'/'.$route;
  3482. Yii::app()->runController($route);
  3483. }
  3484. if($exit)
  3485. Yii::app()->end();
  3486. }
  3487. public function render($view,$data=null,$return=false)
  3488. {
  3489. if($this->beforeRender($view))
  3490. {
  3491. $output=$this->renderPartial($view,$data,true);
  3492. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3493. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3494. $this->afterRender($view,$output);
  3495. $output=$this->processOutput($output);
  3496. if($return)
  3497. return $output;
  3498. else
  3499. echo $output;
  3500. }
  3501. }
  3502. protected function beforeRender($view)
  3503. {
  3504. return true;
  3505. }
  3506. protected function afterRender($view, &$output)
  3507. {
  3508. }
  3509. public function renderText($text,$return=false)
  3510. {
  3511. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3512. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3513. $text=$this->processOutput($text);
  3514. if($return)
  3515. return $text;
  3516. else
  3517. echo $text;
  3518. }
  3519. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3520. {
  3521. if(($viewFile=$this->getViewFile($view))!==false)
  3522. {
  3523. $output=$this->renderFile($viewFile,$data,true);
  3524. if($processOutput)
  3525. $output=$this->processOutput($output);
  3526. if($return)
  3527. return $output;
  3528. else
  3529. echo $output;
  3530. }
  3531. else
  3532. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3533. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3534. }
  3535. public function renderClip($name,$params=array(),$return=false)
  3536. {
  3537. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  3538. if($return)
  3539. return $text;
  3540. else
  3541. echo $text;
  3542. }
  3543. public function renderDynamic($callback)
  3544. {
  3545. $n=count($this->_dynamicOutput);
  3546. echo "<###dynamic-$n###>";
  3547. $params=func_get_args();
  3548. array_shift($params);
  3549. $this->renderDynamicInternal($callback,$params);
  3550. }
  3551. public function renderDynamicInternal($callback,$params)
  3552. {
  3553. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3554. if(is_string($callback) && method_exists($this,$callback))
  3555. $callback=array($this,$callback);
  3556. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3557. }
  3558. public function createUrl($route,$params=array(),$ampersand='&')
  3559. {
  3560. if($route==='')
  3561. $route=$this->getId().'/'.$this->getAction()->getId();
  3562. else if(strpos($route,'/')===false)
  3563. $route=$this->getId().'/'.$route;
  3564. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3565. $route=$module->getId().'/'.$route;
  3566. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3567. }
  3568. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3569. {
  3570. $url=$this->createUrl($route,$params,$ampersand);
  3571. if(strpos($url,'http')===0)
  3572. return $url;
  3573. else
  3574. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  3575. }
  3576. public function getPageTitle()
  3577. {
  3578. if($this->_pageTitle!==null)
  3579. return $this->_pageTitle;
  3580. else
  3581. {
  3582. $name=ucfirst(basename($this->getId()));
  3583. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3584. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3585. else
  3586. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3587. }
  3588. }
  3589. public function setPageTitle($value)
  3590. {
  3591. $this->_pageTitle=$value;
  3592. }
  3593. public function redirect($url,$terminate=true,$statusCode=302)
  3594. {
  3595. if(is_array($url))
  3596. {
  3597. $route=isset($url[0]) ? $url[0] : '';
  3598. $url=$this->createUrl($route,array_splice($url,1));
  3599. }
  3600. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  3601. }
  3602. public function refresh($terminate=true,$anchor='')
  3603. {
  3604. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  3605. }
  3606. public function recordCachingAction($context,$method,$params)
  3607. {
  3608. if($this->_cachingStack) // record only when there is an active output cache
  3609. {
  3610. foreach($this->_cachingStack as $cache)
  3611. $cache->recordAction($context,$method,$params);
  3612. }
  3613. }
  3614. public function getCachingStack($createIfNull=true)
  3615. {
  3616. if(!$this->_cachingStack)
  3617. $this->_cachingStack=new CStack;
  3618. return $this->_cachingStack;
  3619. }
  3620. public function isCachingStackEmpty()
  3621. {
  3622. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  3623. }
  3624. protected function beforeAction($action)
  3625. {
  3626. return true;
  3627. }
  3628. protected function afterAction($action)
  3629. {
  3630. }
  3631. public function filterPostOnly($filterChain)
  3632. {
  3633. if(Yii::app()->getRequest()->getIsPostRequest())
  3634. $filterChain->run();
  3635. else
  3636. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3637. }
  3638. public function filterAjaxOnly($filterChain)
  3639. {
  3640. if(Yii::app()->getRequest()->getIsAjaxRequest())
  3641. $filterChain->run();
  3642. else
  3643. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3644. }
  3645. public function filterAccessControl($filterChain)
  3646. {
  3647. $filter=new CAccessControlFilter;
  3648. $filter->setRules($this->accessRules());
  3649. $filter->filter($filterChain);
  3650. }
  3651. public function getPageState($name,$defaultValue=null)
  3652. {
  3653. if($this->_pageStates===null)
  3654. $this->_pageStates=$this->loadPageStates();
  3655. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  3656. }
  3657. public function setPageState($name,$value,$defaultValue=null)
  3658. {
  3659. if($this->_pageStates===null)
  3660. $this->_pageStates=$this->loadPageStates();
  3661. if($value===$defaultValue)
  3662. unset($this->_pageStates[$name]);
  3663. else
  3664. $this->_pageStates[$name]=$value;
  3665. $params=func_get_args();
  3666. $this->recordCachingAction('','setPageState',$params);
  3667. }
  3668. public function clearPageStates()
  3669. {
  3670. $this->_pageStates=array();
  3671. }
  3672. protected function loadPageStates()
  3673. {
  3674. if(!empty($_POST[self::STATE_INPUT_NAME]))
  3675. {
  3676. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  3677. {
  3678. if(extension_loaded('zlib'))
  3679. $data=@gzuncompress($data);
  3680. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  3681. return unserialize($data);
  3682. }
  3683. }
  3684. return array();
  3685. }
  3686. protected function savePageStates($states,&$output)
  3687. {
  3688. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  3689. if(extension_loaded('zlib'))
  3690. $data=gzcompress($data);
  3691. $value=base64_encode($data);
  3692. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  3693. }
  3694. }
  3695. abstract class CAction extends CComponent implements IAction
  3696. {
  3697. private $_id;
  3698. private $_controller;
  3699. public function __construct($controller,$id)
  3700. {
  3701. $this->_controller=$controller;
  3702. $this->_id=$id;
  3703. }
  3704. public function getController()
  3705. {
  3706. return $this->_controller;
  3707. }
  3708. public function getId()
  3709. {
  3710. return $this->_id;
  3711. }
  3712. public function runWithParams($params)
  3713. {
  3714. $method=new ReflectionMethod($this, 'run');
  3715. if($method->getNumberOfParameters()>0)
  3716. return $this->runWithParamsInternal($this, $method, $params);
  3717. else
  3718. return $this->run();
  3719. }
  3720. protected function runWithParamsInternal($object, $method, $params)
  3721. {
  3722. $ps=array();
  3723. foreach($method->getParameters() as $i=>$param)
  3724. {
  3725. $name=$param->getName();
  3726. if(isset($params[$name]))
  3727. {
  3728. if($param->isArray())
  3729. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  3730. else if(!is_array($params[$name]))
  3731. $ps[]=$params[$name];
  3732. else
  3733. return false;
  3734. }
  3735. else if($param->isDefaultValueAvailable())
  3736. $ps[]=$param->getDefaultValue();
  3737. else
  3738. return false;
  3739. }
  3740. $method->invokeArgs($object,$ps);
  3741. return true;
  3742. }
  3743. }
  3744. class CInlineAction extends CAction
  3745. {
  3746. public function run()
  3747. {
  3748. $method='action'.$this->getId();
  3749. $this->getController()->$method();
  3750. }
  3751. public function runWithParams($params)
  3752. {
  3753. $methodName='action'.$this->getId();
  3754. $controller=$this->getController();
  3755. $method=new ReflectionMethod($controller, $methodName);
  3756. if($method->getNumberOfParameters()>0)
  3757. return $this->runWithParamsInternal($controller, $method, $params);
  3758. else
  3759. return $controller->$methodName();
  3760. }
  3761. }
  3762. class CWebUser extends CApplicationComponent implements IWebUser
  3763. {
  3764. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  3765. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  3766. const STATES_VAR='__states';
  3767. const AUTH_TIMEOUT_VAR='__timeout';
  3768. public $allowAutoLogin=false;
  3769. public $guestName='Guest';
  3770. public $loginUrl=array('/site/login');
  3771. public $identityCookie;
  3772. public $authTimeout;
  3773. public $autoRenewCookie=false;
  3774. public $autoUpdateFlash=true;
  3775. public $loginRequiredAjaxResponse;
  3776. private $_keyPrefix;
  3777. private $_access=array();
  3778. public function __get($name)
  3779. {
  3780. if($this->hasState($name))
  3781. return $this->getState($name);
  3782. else
  3783. return parent::__get($name);
  3784. }
  3785. public function __set($name,$value)
  3786. {
  3787. if($this->hasState($name))
  3788. $this->setState($name,$value);
  3789. else
  3790. parent::__set($name,$value);
  3791. }
  3792. public function __isset($name)
  3793. {
  3794. if($this->hasState($name))
  3795. return $this->getState($name)!==null;
  3796. else
  3797. return parent::__isset($name);
  3798. }
  3799. public function __unset($name)
  3800. {
  3801. if($this->hasState($name))
  3802. $this->setState($name,null);
  3803. else
  3804. parent::__unset($name);
  3805. }
  3806. public function init()
  3807. {
  3808. parent::init();
  3809. Yii::app()->getSession()->open();
  3810. if($this->getIsGuest() && $this->allowAutoLogin)
  3811. $this->restoreFromCookie();
  3812. else if($this->autoRenewCookie && $this->allowAutoLogin)
  3813. $this->renewCookie();
  3814. if($this->autoUpdateFlash)
  3815. $this->updateFlash();
  3816. $this->updateAuthStatus();
  3817. }
  3818. public function login($identity,$duration=0)
  3819. {
  3820. $id=$identity->getId();
  3821. $states=$identity->getPersistentStates();
  3822. if($this->beforeLogin($id,$states,false))
  3823. {
  3824. $this->changeIdentity($id,$identity->getName(),$states);
  3825. if($duration>0)
  3826. {
  3827. if($this->allowAutoLogin)
  3828. $this->saveToCookie($duration);
  3829. else
  3830. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  3831. array('{class}'=>get_class($this))));
  3832. }
  3833. $this->afterLogin(false);
  3834. }
  3835. return !$this->getIsGuest();
  3836. }
  3837. public function logout($destroySession=true)
  3838. {
  3839. if($this->beforeLogout())
  3840. {
  3841. if($this->allowAutoLogin)
  3842. {
  3843. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  3844. if($this->identityCookie!==null)
  3845. {
  3846. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3847. $cookie->value=null;
  3848. $cookie->expire=0;
  3849. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  3850. }
  3851. }
  3852. if($destroySession)
  3853. Yii::app()->getSession()->destroy();
  3854. else
  3855. $this->clearStates();
  3856. $this->afterLogout();
  3857. }
  3858. }
  3859. public function getIsGuest()
  3860. {
  3861. return $this->getState('__id')===null;
  3862. }
  3863. public function getId()
  3864. {
  3865. return $this->getState('__id');
  3866. }
  3867. public function setId($value)
  3868. {
  3869. $this->setState('__id',$value);
  3870. }
  3871. public function getName()
  3872. {
  3873. if(($name=$this->getState('__name'))!==null)
  3874. return $name;
  3875. else
  3876. return $this->guestName;
  3877. }
  3878. public function setName($value)
  3879. {
  3880. $this->setState('__name',$value);
  3881. }
  3882. public function getReturnUrl($defaultUrl=null)
  3883. {
  3884. return $this->getState('__returnUrl', $defaultUrl===null ? Yii::app()->getRequest()->getScriptUrl() : CHtml::normalizeUrl($defaultUrl));
  3885. }
  3886. public function setReturnUrl($value)
  3887. {
  3888. $this->setState('__returnUrl',$value);
  3889. }
  3890. public function loginRequired()
  3891. {
  3892. $app=Yii::app();
  3893. $request=$app->getRequest();
  3894. if(!$request->getIsAjaxRequest())
  3895. $this->setReturnUrl($request->getUrl());
  3896. elseif(isset($this->loginRequiredAjaxResponse))
  3897. {
  3898. echo $this->loginRequiredAjaxResponse;
  3899. Yii::app()->end();
  3900. }
  3901. if(($url=$this->loginUrl)!==null)
  3902. {
  3903. if(is_array($url))
  3904. {
  3905. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  3906. $url=$app->createUrl($route,array_splice($url,1));
  3907. }
  3908. $request->redirect($url);
  3909. }
  3910. else
  3911. throw new CHttpException(403,Yii::t('yii','Login Required'));
  3912. }
  3913. protected function beforeLogin($id,$states,$fromCookie)
  3914. {
  3915. return true;
  3916. }
  3917. protected function afterLogin($fromCookie)
  3918. {
  3919. }
  3920. protected function beforeLogout()
  3921. {
  3922. return true;
  3923. }
  3924. protected function afterLogout()
  3925. {
  3926. }
  3927. protected function restoreFromCookie()
  3928. {
  3929. $app=Yii::app();
  3930. $request=$app->getRequest();
  3931. $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  3932. if($cookie && !empty($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  3933. {
  3934. $data=@unserialize($data);
  3935. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3936. {
  3937. list($id,$name,$duration,$states)=$data;
  3938. if($this->beforeLogin($id,$states,true))
  3939. {
  3940. $this->changeIdentity($id,$name,$states);
  3941. if($this->autoRenewCookie)
  3942. {
  3943. $cookie->expire=time()+$duration;
  3944. $request->getCookies()->add($cookie->name,$cookie);
  3945. }
  3946. $this->afterLogin(true);
  3947. }
  3948. }
  3949. }
  3950. }
  3951. protected function renewCookie()
  3952. {
  3953. $request=Yii::app()->getRequest();
  3954. $cookies=$request->getCookies();
  3955. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  3956. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  3957. {
  3958. $data=@unserialize($data);
  3959. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3960. {
  3961. $cookie->expire=time()+$data[2];
  3962. $cookies->add($cookie->name,$cookie);
  3963. }
  3964. }
  3965. }
  3966. protected function saveToCookie($duration)
  3967. {
  3968. $app=Yii::app();
  3969. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3970. $cookie->expire=time()+$duration;
  3971. $data=array(
  3972. $this->getId(),
  3973. $this->getName(),
  3974. $duration,
  3975. $this->saveIdentityStates(),
  3976. );
  3977. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  3978. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  3979. }
  3980. protected function createIdentityCookie($name)
  3981. {
  3982. $cookie=new CHttpCookie($name,'');
  3983. if(is_array($this->identityCookie))
  3984. {
  3985. foreach($this->identityCookie as $name=>$value)
  3986. $cookie->$name=$value;
  3987. }
  3988. return $cookie;
  3989. }
  3990. public function getStateKeyPrefix()
  3991. {
  3992. if($this->_keyPrefix!==null)
  3993. return $this->_keyPrefix;
  3994. else
  3995. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  3996. }
  3997. public function setStateKeyPrefix($value)
  3998. {
  3999. $this->_keyPrefix=$value;
  4000. }
  4001. public function getState($key,$defaultValue=null)
  4002. {
  4003. $key=$this->getStateKeyPrefix().$key;
  4004. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4005. }
  4006. public function setState($key,$value,$defaultValue=null)
  4007. {
  4008. $key=$this->getStateKeyPrefix().$key;
  4009. if($value===$defaultValue)
  4010. unset($_SESSION[$key]);
  4011. else
  4012. $_SESSION[$key]=$value;
  4013. }
  4014. public function hasState($key)
  4015. {
  4016. $key=$this->getStateKeyPrefix().$key;
  4017. return isset($_SESSION[$key]);
  4018. }
  4019. public function clearStates()
  4020. {
  4021. $keys=array_keys($_SESSION);
  4022. $prefix=$this->getStateKeyPrefix();
  4023. $n=strlen($prefix);
  4024. foreach($keys as $key)
  4025. {
  4026. if(!strncmp($key,$prefix,$n))
  4027. unset($_SESSION[$key]);
  4028. }
  4029. }
  4030. public function getFlashes($delete=true)
  4031. {
  4032. $flashes=array();
  4033. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  4034. $keys=array_keys($_SESSION);
  4035. $n=strlen($prefix);
  4036. foreach($keys as $key)
  4037. {
  4038. if(!strncmp($key,$prefix,$n))
  4039. {
  4040. $flashes[substr($key,$n)]=$_SESSION[$key];
  4041. if($delete)
  4042. unset($_SESSION[$key]);
  4043. }
  4044. }
  4045. if($delete)
  4046. $this->setState(self::FLASH_COUNTERS,array());
  4047. return $flashes;
  4048. }
  4049. public function getFlash($key,$defaultValue=null,$delete=true)
  4050. {
  4051. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4052. if($delete)
  4053. $this->setFlash($key,null);
  4054. return $value;
  4055. }
  4056. public function setFlash($key,$value,$defaultValue=null)
  4057. {
  4058. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4059. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4060. if($value===$defaultValue)
  4061. unset($counters[$key]);
  4062. else
  4063. $counters[$key]=0;
  4064. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4065. }
  4066. public function hasFlash($key)
  4067. {
  4068. return $this->getFlash($key, null, false)!==null;
  4069. }
  4070. protected function changeIdentity($id,$name,$states)
  4071. {
  4072. Yii::app()->getSession()->regenerateID();
  4073. $this->setId($id);
  4074. $this->setName($name);
  4075. $this->loadIdentityStates($states);
  4076. }
  4077. protected function saveIdentityStates()
  4078. {
  4079. $states=array();
  4080. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4081. $states[$name]=$this->getState($name);
  4082. return $states;
  4083. }
  4084. protected function loadIdentityStates($states)
  4085. {
  4086. $names=array();
  4087. if(is_array($states))
  4088. {
  4089. foreach($states as $name=>$value)
  4090. {
  4091. $this->setState($name,$value);
  4092. $names[$name]=true;
  4093. }
  4094. }
  4095. $this->setState(self::STATES_VAR,$names);
  4096. }
  4097. protected function updateFlash()
  4098. {
  4099. $counters=$this->getState(self::FLASH_COUNTERS);
  4100. if(!is_array($counters))
  4101. return;
  4102. foreach($counters as $key=>$count)
  4103. {
  4104. if($count)
  4105. {
  4106. unset($counters[$key]);
  4107. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4108. }
  4109. else
  4110. $counters[$key]++;
  4111. }
  4112. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4113. }
  4114. protected function updateAuthStatus()
  4115. {
  4116. if($this->authTimeout!==null && !$this->getIsGuest())
  4117. {
  4118. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4119. if ($expires!==null && $expires < time())
  4120. $this->logout(false);
  4121. else
  4122. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4123. }
  4124. }
  4125. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4126. {
  4127. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4128. return $this->_access[$operation];
  4129. else
  4130. return $this->_access[$operation]=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4131. }
  4132. }
  4133. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4134. {
  4135. public $autoStart=true;
  4136. public function init()
  4137. {
  4138. parent::init();
  4139. if($this->autoStart)
  4140. $this->open();
  4141. register_shutdown_function(array($this,'close'));
  4142. }
  4143. public function getUseCustomStorage()
  4144. {
  4145. return false;
  4146. }
  4147. public function open()
  4148. {
  4149. if($this->getUseCustomStorage())
  4150. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4151. @session_start();
  4152. if(YII_DEBUG && session_id()=='')
  4153. {
  4154. $message=Yii::t('yii','Failed to start session.');
  4155. if(function_exists('error_get_last'))
  4156. {
  4157. $error=error_get_last();
  4158. if(isset($error['message']))
  4159. $message=$error['message'];
  4160. }
  4161. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4162. }
  4163. }
  4164. public function close()
  4165. {
  4166. if(session_id()!=='')
  4167. @session_write_close();
  4168. }
  4169. public function destroy()
  4170. {
  4171. if(session_id()!=='')
  4172. {
  4173. @session_unset();
  4174. @session_destroy();
  4175. }
  4176. }
  4177. public function getIsStarted()
  4178. {
  4179. return session_id()!=='';
  4180. }
  4181. public function getSessionID()
  4182. {
  4183. return session_id();
  4184. }
  4185. public function setSessionID($value)
  4186. {
  4187. session_id($value);
  4188. }
  4189. public function regenerateID($deleteOldSession=false)
  4190. {
  4191. session_regenerate_id($deleteOldSession);
  4192. }
  4193. public function getSessionName()
  4194. {
  4195. return session_name();
  4196. }
  4197. public function setSessionName($value)
  4198. {
  4199. session_name($value);
  4200. }
  4201. public function getSavePath()
  4202. {
  4203. return session_save_path();
  4204. }
  4205. public function setSavePath($value)
  4206. {
  4207. if(is_dir($value))
  4208. session_save_path($value);
  4209. else
  4210. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4211. array('{path}'=>$value)));
  4212. }
  4213. public function getCookieParams()
  4214. {
  4215. return session_get_cookie_params();
  4216. }
  4217. public function setCookieParams($value)
  4218. {
  4219. $data=session_get_cookie_params();
  4220. extract($data);
  4221. extract($value);
  4222. if(isset($httponly))
  4223. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4224. else
  4225. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4226. }
  4227. public function getCookieMode()
  4228. {
  4229. if(ini_get('session.use_cookies')==='0')
  4230. return 'none';
  4231. else if(ini_get('session.use_only_cookies')==='0')
  4232. return 'allow';
  4233. else
  4234. return 'only';
  4235. }
  4236. public function setCookieMode($value)
  4237. {
  4238. if($value==='none')
  4239. {
  4240. ini_set('session.use_cookies','0');
  4241. ini_set('session.use_only_cookies','0');
  4242. }
  4243. else if($value==='allow')
  4244. {
  4245. ini_set('session.use_cookies','1');
  4246. ini_set('session.use_only_cookies','0');
  4247. }
  4248. else if($value==='only')
  4249. {
  4250. ini_set('session.use_cookies','1');
  4251. ini_set('session.use_only_cookies','1');
  4252. }
  4253. else
  4254. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4255. }
  4256. public function getGCProbability()
  4257. {
  4258. return (int)ini_get('session.gc_probability');
  4259. }
  4260. public function setGCProbability($value)
  4261. {
  4262. $value=(int)$value;
  4263. if($value>=0 && $value<=100)
  4264. {
  4265. ini_set('session.gc_probability',$value);
  4266. ini_set('session.gc_divisor','100');
  4267. }
  4268. else
  4269. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be an integer between 0 and 100.',
  4270. array('{value}'=>$value)));
  4271. }
  4272. public function getUseTransparentSessionID()
  4273. {
  4274. return ini_get('session.use_trans_sid')==1;
  4275. }
  4276. public function setUseTransparentSessionID($value)
  4277. {
  4278. ini_set('session.use_trans_sid',$value?'1':'0');
  4279. }
  4280. public function getTimeout()
  4281. {
  4282. return (int)ini_get('session.gc_maxlifetime');
  4283. }
  4284. public function setTimeout($value)
  4285. {
  4286. ini_set('session.gc_maxlifetime',$value);
  4287. }
  4288. public function openSession($savePath,$sessionName)
  4289. {
  4290. return true;
  4291. }
  4292. public function closeSession()
  4293. {
  4294. return true;
  4295. }
  4296. public function readSession($id)
  4297. {
  4298. return '';
  4299. }
  4300. public function writeSession($id,$data)
  4301. {
  4302. return true;
  4303. }
  4304. public function destroySession($id)
  4305. {
  4306. return true;
  4307. }
  4308. public function gcSession($maxLifetime)
  4309. {
  4310. return true;
  4311. }
  4312. //------ The following methods enable CHttpSession to be CMap-like -----
  4313. public function getIterator()
  4314. {
  4315. return new CHttpSessionIterator;
  4316. }
  4317. public function getCount()
  4318. {
  4319. return count($_SESSION);
  4320. }
  4321. public function count()
  4322. {
  4323. return $this->getCount();
  4324. }
  4325. public function getKeys()
  4326. {
  4327. return array_keys($_SESSION);
  4328. }
  4329. public function get($key,$defaultValue=null)
  4330. {
  4331. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4332. }
  4333. public function itemAt($key)
  4334. {
  4335. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4336. }
  4337. public function add($key,$value)
  4338. {
  4339. $_SESSION[$key]=$value;
  4340. }
  4341. public function remove($key)
  4342. {
  4343. if(isset($_SESSION[$key]))
  4344. {
  4345. $value=$_SESSION[$key];
  4346. unset($_SESSION[$key]);
  4347. return $value;
  4348. }
  4349. else
  4350. return null;
  4351. }
  4352. public function clear()
  4353. {
  4354. foreach(array_keys($_SESSION) as $key)
  4355. unset($_SESSION[$key]);
  4356. }
  4357. public function contains($key)
  4358. {
  4359. return isset($_SESSION[$key]);
  4360. }
  4361. public function toArray()
  4362. {
  4363. return $_SESSION;
  4364. }
  4365. public function offsetExists($offset)
  4366. {
  4367. return isset($_SESSION[$offset]);
  4368. }
  4369. public function offsetGet($offset)
  4370. {
  4371. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4372. }
  4373. public function offsetSet($offset,$item)
  4374. {
  4375. $_SESSION[$offset]=$item;
  4376. }
  4377. public function offsetUnset($offset)
  4378. {
  4379. unset($_SESSION[$offset]);
  4380. }
  4381. }
  4382. class CHtml
  4383. {
  4384. const ID_PREFIX='yt';
  4385. public static $errorSummaryCss='errorSummary';
  4386. public static $errorMessageCss='errorMessage';
  4387. public static $errorCss='error';
  4388. public static $requiredCss='required';
  4389. public static $beforeRequiredLabel='';
  4390. public static $afterRequiredLabel=' <span class="required">*</span>';
  4391. public static $count=0;
  4392. public static $liveEvents = true;
  4393. public static function encode($text)
  4394. {
  4395. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4396. }
  4397. public static function decode($text)
  4398. {
  4399. return htmlspecialchars_decode($text,ENT_QUOTES);
  4400. }
  4401. public static function encodeArray($data)
  4402. {
  4403. $d=array();
  4404. foreach($data as $key=>$value)
  4405. {
  4406. if(is_string($key))
  4407. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4408. if(is_string($value))
  4409. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4410. else if(is_array($value))
  4411. $value=self::encodeArray($value);
  4412. $d[$key]=$value;
  4413. }
  4414. return $d;
  4415. }
  4416. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4417. {
  4418. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4419. if($content===false)
  4420. return $closeTag ? $html.' />' : $html.'>';
  4421. else
  4422. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4423. }
  4424. public static function openTag($tag,$htmlOptions=array())
  4425. {
  4426. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4427. }
  4428. public static function closeTag($tag)
  4429. {
  4430. return '</'.$tag.'>';
  4431. }
  4432. public static function cdata($text)
  4433. {
  4434. return '<![CDATA[' . $text . ']]>';
  4435. }
  4436. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4437. {
  4438. if($name!==null)
  4439. $options['name']=$name;
  4440. if($httpEquiv!==null)
  4441. $options['http-equiv']=$httpEquiv;
  4442. $options['content']=$content;
  4443. return self::tag('meta',$options);
  4444. }
  4445. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4446. {
  4447. if($relation!==null)
  4448. $options['rel']=$relation;
  4449. if($type!==null)
  4450. $options['type']=$type;
  4451. if($href!==null)
  4452. $options['href']=$href;
  4453. if($media!==null)
  4454. $options['media']=$media;
  4455. return self::tag('link',$options);
  4456. }
  4457. public static function css($text,$media='')
  4458. {
  4459. if($media!=='')
  4460. $media=' media="'.$media.'"';
  4461. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4462. }
  4463. public static function refresh($seconds, $url='')
  4464. {
  4465. $content="$seconds";
  4466. if($url!=='')
  4467. $content.=';'.self::normalizeUrl($url);
  4468. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4469. }
  4470. public static function cssFile($url,$media='')
  4471. {
  4472. if($media!=='')
  4473. $media=' media="'.$media.'"';
  4474. return '<link rel="stylesheet" type="text/css" href="'.self::encode($url).'"'.$media.' />';
  4475. }
  4476. public static function script($text)
  4477. {
  4478. return "<script type=\"text/javascript\">\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</script>";
  4479. }
  4480. public static function scriptFile($url)
  4481. {
  4482. return '<script type="text/javascript" src="'.self::encode($url).'"></script>';
  4483. }
  4484. public static function form($action='',$method='post',$htmlOptions=array())
  4485. {
  4486. return self::beginForm($action,$method,$htmlOptions);
  4487. }
  4488. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4489. {
  4490. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4491. $htmlOptions['method']=$method;
  4492. $form=self::tag('form',$htmlOptions,false,false);
  4493. $hiddens=array();
  4494. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4495. {
  4496. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4497. {
  4498. if(($pos=strpos($pair,'='))!==false)
  4499. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4500. }
  4501. }
  4502. $request=Yii::app()->request;
  4503. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4504. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4505. if($hiddens!==array())
  4506. $form.="\n".self::tag('div',array('style'=>'display:none'),implode("\n",$hiddens));
  4507. return $form;
  4508. }
  4509. public static function endForm()
  4510. {
  4511. return '</form>';
  4512. }
  4513. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4514. {
  4515. return self::form($action,$method,$htmlOptions)."\n".
  4516. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4517. }
  4518. public static function pageStateField($value)
  4519. {
  4520. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4521. }
  4522. public static function link($text,$url='#',$htmlOptions=array())
  4523. {
  4524. if($url!=='')
  4525. $htmlOptions['href']=self::normalizeUrl($url);
  4526. self::clientChange('click',$htmlOptions);
  4527. return self::tag('a',$htmlOptions,$text);
  4528. }
  4529. public static function mailto($text,$email='',$htmlOptions=array())
  4530. {
  4531. if($email==='')
  4532. $email=$text;
  4533. return self::link($text,'mailto:'.$email,$htmlOptions);
  4534. }
  4535. public static function image($src,$alt='',$htmlOptions=array())
  4536. {
  4537. $htmlOptions['src']=$src;
  4538. $htmlOptions['alt']=$alt;
  4539. return self::tag('img',$htmlOptions);
  4540. }
  4541. public static function button($label='button',$htmlOptions=array())
  4542. {
  4543. if(!isset($htmlOptions['name']))
  4544. {
  4545. if(!array_key_exists('name',$htmlOptions))
  4546. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4547. }
  4548. if(!isset($htmlOptions['type']))
  4549. $htmlOptions['type']='button';
  4550. if(!isset($htmlOptions['value']))
  4551. $htmlOptions['value']=$label;
  4552. self::clientChange('click',$htmlOptions);
  4553. return self::tag('input',$htmlOptions);
  4554. }
  4555. public static function htmlButton($label='button',$htmlOptions=array())
  4556. {
  4557. if(!isset($htmlOptions['name']))
  4558. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4559. if(!isset($htmlOptions['type']))
  4560. $htmlOptions['type']='button';
  4561. self::clientChange('click',$htmlOptions);
  4562. return self::tag('button',$htmlOptions,$label);
  4563. }
  4564. public static function submitButton($label='submit',$htmlOptions=array())
  4565. {
  4566. $htmlOptions['type']='submit';
  4567. return self::button($label,$htmlOptions);
  4568. }
  4569. public static function resetButton($label='reset',$htmlOptions=array())
  4570. {
  4571. $htmlOptions['type']='reset';
  4572. return self::button($label,$htmlOptions);
  4573. }
  4574. public static function imageButton($src,$htmlOptions=array())
  4575. {
  4576. $htmlOptions['src']=$src;
  4577. $htmlOptions['type']='image';
  4578. return self::button('submit',$htmlOptions);
  4579. }
  4580. public static function linkButton($label='submit',$htmlOptions=array())
  4581. {
  4582. if(!isset($htmlOptions['submit']))
  4583. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  4584. return self::link($label,'#',$htmlOptions);
  4585. }
  4586. public static function label($label,$for,$htmlOptions=array())
  4587. {
  4588. if($for===false)
  4589. unset($htmlOptions['for']);
  4590. else
  4591. $htmlOptions['for']=$for;
  4592. if(isset($htmlOptions['required']))
  4593. {
  4594. if($htmlOptions['required'])
  4595. {
  4596. if(isset($htmlOptions['class']))
  4597. $htmlOptions['class'].=' '.self::$requiredCss;
  4598. else
  4599. $htmlOptions['class']=self::$requiredCss;
  4600. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  4601. }
  4602. unset($htmlOptions['required']);
  4603. }
  4604. return self::tag('label',$htmlOptions,$label);
  4605. }
  4606. public static function textField($name,$value='',$htmlOptions=array())
  4607. {
  4608. self::clientChange('change',$htmlOptions);
  4609. return self::inputField('text',$name,$value,$htmlOptions);
  4610. }
  4611. public static function hiddenField($name,$value='',$htmlOptions=array())
  4612. {
  4613. return self::inputField('hidden',$name,$value,$htmlOptions);
  4614. }
  4615. public static function passwordField($name,$value='',$htmlOptions=array())
  4616. {
  4617. self::clientChange('change',$htmlOptions);
  4618. return self::inputField('password',$name,$value,$htmlOptions);
  4619. }
  4620. public static function fileField($name,$value='',$htmlOptions=array())
  4621. {
  4622. return self::inputField('file',$name,$value,$htmlOptions);
  4623. }
  4624. public static function textArea($name,$value='',$htmlOptions=array())
  4625. {
  4626. $htmlOptions['name']=$name;
  4627. if(!isset($htmlOptions['id']))
  4628. $htmlOptions['id']=self::getIdByName($name);
  4629. else if($htmlOptions['id']===false)
  4630. unset($htmlOptions['id']);
  4631. self::clientChange('change',$htmlOptions);
  4632. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  4633. }
  4634. public static function radioButton($name,$checked=false,$htmlOptions=array())
  4635. {
  4636. if($checked)
  4637. $htmlOptions['checked']='checked';
  4638. else
  4639. unset($htmlOptions['checked']);
  4640. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4641. self::clientChange('click',$htmlOptions);
  4642. if(array_key_exists('uncheckValue',$htmlOptions))
  4643. {
  4644. $uncheck=$htmlOptions['uncheckValue'];
  4645. unset($htmlOptions['uncheckValue']);
  4646. }
  4647. else
  4648. $uncheck=null;
  4649. if($uncheck!==null)
  4650. {
  4651. // add a hidden field so that if the radio button is not selected, it still submits a value
  4652. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4653. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4654. else
  4655. $uncheckOptions=array('id'=>false);
  4656. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4657. }
  4658. else
  4659. $hidden='';
  4660. // add a hidden field so that if the radio button is not selected, it still submits a value
  4661. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  4662. }
  4663. public static function checkBox($name,$checked=false,$htmlOptions=array())
  4664. {
  4665. if($checked)
  4666. $htmlOptions['checked']='checked';
  4667. else
  4668. unset($htmlOptions['checked']);
  4669. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4670. self::clientChange('click',$htmlOptions);
  4671. if(array_key_exists('uncheckValue',$htmlOptions))
  4672. {
  4673. $uncheck=$htmlOptions['uncheckValue'];
  4674. unset($htmlOptions['uncheckValue']);
  4675. }
  4676. else
  4677. $uncheck=null;
  4678. if($uncheck!==null)
  4679. {
  4680. // add a hidden field so that if the radio button is not selected, it still submits a value
  4681. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4682. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4683. else
  4684. $uncheckOptions=array('id'=>false);
  4685. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4686. }
  4687. else
  4688. $hidden='';
  4689. // add a hidden field so that if the checkbox is not selected, it still submits a value
  4690. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  4691. }
  4692. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  4693. {
  4694. $htmlOptions['name']=$name;
  4695. if(!isset($htmlOptions['id']))
  4696. $htmlOptions['id']=self::getIdByName($name);
  4697. else if($htmlOptions['id']===false)
  4698. unset($htmlOptions['id']);
  4699. self::clientChange('change',$htmlOptions);
  4700. $options="\n".self::listOptions($select,$data,$htmlOptions);
  4701. return self::tag('select',$htmlOptions,$options);
  4702. }
  4703. public static function listBox($name,$select,$data,$htmlOptions=array())
  4704. {
  4705. if(!isset($htmlOptions['size']))
  4706. $htmlOptions['size']=4;
  4707. if(isset($htmlOptions['multiple']))
  4708. {
  4709. if(substr($name,-2)!=='[]')
  4710. $name.='[]';
  4711. }
  4712. return self::dropDownList($name,$select,$data,$htmlOptions);
  4713. }
  4714. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  4715. {
  4716. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4717. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4718. unset($htmlOptions['template'],$htmlOptions['separator']);
  4719. if(substr($name,-2)!=='[]')
  4720. $name.='[]';
  4721. if(isset($htmlOptions['checkAll']))
  4722. {
  4723. $checkAllLabel=$htmlOptions['checkAll'];
  4724. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  4725. }
  4726. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  4727. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4728. unset($htmlOptions['labelOptions']);
  4729. $items=array();
  4730. $baseID=self::getIdByName($name);
  4731. $id=0;
  4732. $checkAll=true;
  4733. foreach($data as $value=>$label)
  4734. {
  4735. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  4736. $checkAll=$checkAll && $checked;
  4737. $htmlOptions['value']=$value;
  4738. $htmlOptions['id']=$baseID.'_'.$id++;
  4739. $option=self::checkBox($name,$checked,$htmlOptions);
  4740. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4741. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4742. }
  4743. if(isset($checkAllLabel))
  4744. {
  4745. $htmlOptions['value']=1;
  4746. $htmlOptions['id']=$id=$baseID.'_all';
  4747. $option=self::checkBox($id,$checkAll,$htmlOptions);
  4748. $label=self::label($checkAllLabel,$id,$labelOptions);
  4749. $item=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4750. if($checkAllLast)
  4751. $items[]=$item;
  4752. else
  4753. array_unshift($items,$item);
  4754. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  4755. $js=<<<EOD
  4756. $('#$id').click(function() {
  4757. $("input[name='$name']").prop('checked', this.checked);
  4758. });
  4759. $("input[name='$name']").click(function() {
  4760. $('#$id').prop('checked', !$("input[name='$name']:not(:checked)").length);
  4761. });
  4762. $('#$id').prop('checked', !$("input[name='$name']:not(:checked)").length);
  4763. EOD;
  4764. $cs=Yii::app()->getClientScript();
  4765. $cs->registerCoreScript('jquery');
  4766. $cs->registerScript($id,$js);
  4767. }
  4768. return self::tag('span',array('id'=>$baseID),implode($separator,$items));
  4769. }
  4770. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  4771. {
  4772. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4773. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4774. unset($htmlOptions['template'],$htmlOptions['separator']);
  4775. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4776. unset($htmlOptions['labelOptions']);
  4777. $items=array();
  4778. $baseID=self::getIdByName($name);
  4779. $id=0;
  4780. foreach($data as $value=>$label)
  4781. {
  4782. $checked=!strcmp($value,$select);
  4783. $htmlOptions['value']=$value;
  4784. $htmlOptions['id']=$baseID.'_'.$id++;
  4785. $option=self::radioButton($name,$checked,$htmlOptions);
  4786. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4787. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4788. }
  4789. return self::tag('span',array('id'=>$baseID),implode($separator,$items));
  4790. }
  4791. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  4792. {
  4793. if(!isset($htmlOptions['href']))
  4794. $htmlOptions['href']='#';
  4795. $ajaxOptions['url']=$url;
  4796. $htmlOptions['ajax']=$ajaxOptions;
  4797. self::clientChange('click',$htmlOptions);
  4798. return self::tag('a',$htmlOptions,$text);
  4799. }
  4800. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4801. {
  4802. $ajaxOptions['url']=$url;
  4803. $htmlOptions['ajax']=$ajaxOptions;
  4804. return self::button($label,$htmlOptions);
  4805. }
  4806. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4807. {
  4808. $ajaxOptions['type']='POST';
  4809. $htmlOptions['type']='submit';
  4810. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  4811. }
  4812. public static function ajax($options)
  4813. {
  4814. Yii::app()->getClientScript()->registerCoreScript('jquery');
  4815. if(!isset($options['url']))
  4816. $options['url']='js:location.href';
  4817. else
  4818. $options['url']=self::normalizeUrl($options['url']);
  4819. if(!isset($options['cache']))
  4820. $options['cache']=false;
  4821. if(!isset($options['data']) && isset($options['type']))
  4822. $options['data']='js:jQuery(this).parents("form").serialize()';
  4823. foreach(array('beforeSend','complete','error','success') as $name)
  4824. {
  4825. if(isset($options[$name]) && strpos($options[$name],'js:')!==0)
  4826. $options[$name]='js:'.$options[$name];
  4827. }
  4828. if(isset($options['update']))
  4829. {
  4830. if(!isset($options['success']))
  4831. $options['success']='js:function(html){jQuery("'.$options['update'].'").html(html)}';
  4832. unset($options['update']);
  4833. }
  4834. if(isset($options['replace']))
  4835. {
  4836. if(!isset($options['success']))
  4837. $options['success']='js:function(html){jQuery("'.$options['replace'].'").replaceWith(html)}';
  4838. unset($options['replace']);
  4839. }
  4840. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  4841. }
  4842. public static function asset($path,$hashByName=false)
  4843. {
  4844. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  4845. }
  4846. public static function normalizeUrl($url)
  4847. {
  4848. if(is_array($url))
  4849. {
  4850. if(isset($url[0]))
  4851. {
  4852. if(($c=Yii::app()->getController())!==null)
  4853. $url=$c->createUrl($url[0],array_splice($url,1));
  4854. else
  4855. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  4856. }
  4857. else
  4858. $url='';
  4859. }
  4860. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  4861. }
  4862. protected static function inputField($type,$name,$value,$htmlOptions)
  4863. {
  4864. $htmlOptions['type']=$type;
  4865. $htmlOptions['value']=$value;
  4866. $htmlOptions['name']=$name;
  4867. if(!isset($htmlOptions['id']))
  4868. $htmlOptions['id']=self::getIdByName($name);
  4869. else if($htmlOptions['id']===false)
  4870. unset($htmlOptions['id']);
  4871. return self::tag('input',$htmlOptions);
  4872. }
  4873. public static function activeLabel($model,$attribute,$htmlOptions=array())
  4874. {
  4875. if(isset($htmlOptions['for']))
  4876. {
  4877. $for=$htmlOptions['for'];
  4878. unset($htmlOptions['for']);
  4879. }
  4880. else
  4881. $for=self::getIdByName(self::resolveName($model,$attribute));
  4882. if(isset($htmlOptions['label']))
  4883. {
  4884. if(($label=$htmlOptions['label'])===false)
  4885. return '';
  4886. unset($htmlOptions['label']);
  4887. }
  4888. else
  4889. $label=$model->getAttributeLabel($attribute);
  4890. if($model->hasErrors($attribute))
  4891. self::addErrorCss($htmlOptions);
  4892. return self::label($label,$for,$htmlOptions);
  4893. }
  4894. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  4895. {
  4896. $realAttribute=$attribute;
  4897. self::resolveName($model,$attribute); // strip off square brackets if any
  4898. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  4899. return self::activeLabel($model,$realAttribute,$htmlOptions);
  4900. }
  4901. public static function activeTextField($model,$attribute,$htmlOptions=array())
  4902. {
  4903. self::resolveNameID($model,$attribute,$htmlOptions);
  4904. self::clientChange('change',$htmlOptions);
  4905. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  4906. }
  4907. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  4908. {
  4909. self::resolveNameID($model,$attribute,$htmlOptions);
  4910. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  4911. }
  4912. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  4913. {
  4914. self::resolveNameID($model,$attribute,$htmlOptions);
  4915. self::clientChange('change',$htmlOptions);
  4916. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  4917. }
  4918. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  4919. {
  4920. self::resolveNameID($model,$attribute,$htmlOptions);
  4921. self::clientChange('change',$htmlOptions);
  4922. if($model->hasErrors($attribute))
  4923. self::addErrorCss($htmlOptions);
  4924. $text=self::resolveValue($model,$attribute);
  4925. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  4926. }
  4927. public static function activeFileField($model,$attribute,$htmlOptions=array())
  4928. {
  4929. self::resolveNameID($model,$attribute,$htmlOptions);
  4930. // add a hidden field so that if a model only has a file field, we can
  4931. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  4932. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4933. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  4934. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  4935. }
  4936. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  4937. {
  4938. self::resolveNameID($model,$attribute,$htmlOptions);
  4939. if(!isset($htmlOptions['value']))
  4940. $htmlOptions['value']=1;
  4941. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  4942. $htmlOptions['checked']='checked';
  4943. self::clientChange('click',$htmlOptions);
  4944. if(array_key_exists('uncheckValue',$htmlOptions))
  4945. {
  4946. $uncheck=$htmlOptions['uncheckValue'];
  4947. unset($htmlOptions['uncheckValue']);
  4948. }
  4949. else
  4950. $uncheck='0';
  4951. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4952. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  4953. // add a hidden field so that if the radio button is not selected, it still submits a value
  4954. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  4955. }
  4956. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  4957. {
  4958. self::resolveNameID($model,$attribute,$htmlOptions);
  4959. if(!isset($htmlOptions['value']))
  4960. $htmlOptions['value']=1;
  4961. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  4962. $htmlOptions['checked']='checked';
  4963. self::clientChange('click',$htmlOptions);
  4964. if(array_key_exists('uncheckValue',$htmlOptions))
  4965. {
  4966. $uncheck=$htmlOptions['uncheckValue'];
  4967. unset($htmlOptions['uncheckValue']);
  4968. }
  4969. else
  4970. $uncheck='0';
  4971. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4972. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  4973. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  4974. }
  4975. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  4976. {
  4977. self::resolveNameID($model,$attribute,$htmlOptions);
  4978. $selection=self::resolveValue($model,$attribute);
  4979. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  4980. self::clientChange('change',$htmlOptions);
  4981. if($model->hasErrors($attribute))
  4982. self::addErrorCss($htmlOptions);
  4983. if(isset($htmlOptions['multiple']))
  4984. {
  4985. if(substr($htmlOptions['name'],-2)!=='[]')
  4986. $htmlOptions['name'].='[]';
  4987. }
  4988. return self::tag('select',$htmlOptions,$options);
  4989. }
  4990. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  4991. {
  4992. if(!isset($htmlOptions['size']))
  4993. $htmlOptions['size']=4;
  4994. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  4995. }
  4996. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  4997. {
  4998. self::resolveNameID($model,$attribute,$htmlOptions);
  4999. $selection=self::resolveValue($model,$attribute);
  5000. if($model->hasErrors($attribute))
  5001. self::addErrorCss($htmlOptions);
  5002. $name=$htmlOptions['name'];
  5003. unset($htmlOptions['name']);
  5004. if(array_key_exists('uncheckValue',$htmlOptions))
  5005. {
  5006. $uncheck=$htmlOptions['uncheckValue'];
  5007. unset($htmlOptions['uncheckValue']);
  5008. }
  5009. else
  5010. $uncheck='';
  5011. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5012. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5013. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  5014. }
  5015. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  5016. {
  5017. self::resolveNameID($model,$attribute,$htmlOptions);
  5018. $selection=self::resolveValue($model,$attribute);
  5019. if($model->hasErrors($attribute))
  5020. self::addErrorCss($htmlOptions);
  5021. $name=$htmlOptions['name'];
  5022. unset($htmlOptions['name']);
  5023. if(array_key_exists('uncheckValue',$htmlOptions))
  5024. {
  5025. $uncheck=$htmlOptions['uncheckValue'];
  5026. unset($htmlOptions['uncheckValue']);
  5027. }
  5028. else
  5029. $uncheck='';
  5030. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5031. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5032. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  5033. }
  5034. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  5035. {
  5036. $content='';
  5037. if(!is_array($model))
  5038. $model=array($model);
  5039. if(isset($htmlOptions['firstError']))
  5040. {
  5041. $firstError=$htmlOptions['firstError'];
  5042. unset($htmlOptions['firstError']);
  5043. }
  5044. else
  5045. $firstError=false;
  5046. foreach($model as $m)
  5047. {
  5048. foreach($m->getErrors() as $errors)
  5049. {
  5050. foreach($errors as $error)
  5051. {
  5052. if($error!='')
  5053. $content.="<li>$error</li>\n";
  5054. if($firstError)
  5055. break;
  5056. }
  5057. }
  5058. }
  5059. if($content!=='')
  5060. {
  5061. if($header===null)
  5062. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5063. if(!isset($htmlOptions['class']))
  5064. $htmlOptions['class']=self::$errorSummaryCss;
  5065. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5066. }
  5067. else
  5068. return '';
  5069. }
  5070. public static function error($model,$attribute,$htmlOptions=array())
  5071. {
  5072. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5073. $error=$model->getError($attribute);
  5074. if($error!='')
  5075. {
  5076. if(!isset($htmlOptions['class']))
  5077. $htmlOptions['class']=self::$errorMessageCss;
  5078. return self::tag('div',$htmlOptions,$error);
  5079. }
  5080. else
  5081. return '';
  5082. }
  5083. public static function listData($models,$valueField,$textField,$groupField='')
  5084. {
  5085. $listData=array();
  5086. if($groupField==='')
  5087. {
  5088. foreach($models as $model)
  5089. {
  5090. $value=self::value($model,$valueField);
  5091. $text=self::value($model,$textField);
  5092. $listData[$value]=$text;
  5093. }
  5094. }
  5095. else
  5096. {
  5097. foreach($models as $model)
  5098. {
  5099. $group=self::value($model,$groupField);
  5100. $value=self::value($model,$valueField);
  5101. $text=self::value($model,$textField);
  5102. $listData[$group][$value]=$text;
  5103. }
  5104. }
  5105. return $listData;
  5106. }
  5107. public static function value($model,$attribute,$defaultValue=null)
  5108. {
  5109. foreach(explode('.',$attribute) as $name)
  5110. {
  5111. if(is_object($model))
  5112. $model=$model->$name;
  5113. else if(is_array($model) && isset($model[$name]))
  5114. $model=$model[$name];
  5115. else
  5116. return $defaultValue;
  5117. }
  5118. return $model;
  5119. }
  5120. public static function getIdByName($name)
  5121. {
  5122. return str_replace(array('[]', '][', '[', ']'), array('', '_', '_', ''), $name);
  5123. }
  5124. public static function activeId($model,$attribute)
  5125. {
  5126. return self::getIdByName(self::activeName($model,$attribute));
  5127. }
  5128. public static function activeName($model,$attribute)
  5129. {
  5130. $a=$attribute; // because the attribute name may be changed by resolveName
  5131. return self::resolveName($model,$a);
  5132. }
  5133. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5134. {
  5135. $htmlOptions['type']=$type;
  5136. if($type==='text' || $type==='password')
  5137. {
  5138. if(!isset($htmlOptions['maxlength']))
  5139. {
  5140. foreach($model->getValidators($attribute) as $validator)
  5141. {
  5142. if($validator instanceof CStringValidator && $validator->max!==null)
  5143. {
  5144. $htmlOptions['maxlength']=$validator->max;
  5145. break;
  5146. }
  5147. }
  5148. }
  5149. else if($htmlOptions['maxlength']===false)
  5150. unset($htmlOptions['maxlength']);
  5151. }
  5152. if($type==='file')
  5153. unset($htmlOptions['value']);
  5154. else if(!isset($htmlOptions['value']))
  5155. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5156. if($model->hasErrors($attribute))
  5157. self::addErrorCss($htmlOptions);
  5158. return self::tag('input',$htmlOptions);
  5159. }
  5160. public static function listOptions($selection,$listData,&$htmlOptions)
  5161. {
  5162. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5163. $content='';
  5164. if(isset($htmlOptions['prompt']))
  5165. {
  5166. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5167. unset($htmlOptions['prompt']);
  5168. }
  5169. if(isset($htmlOptions['empty']))
  5170. {
  5171. if(!is_array($htmlOptions['empty']))
  5172. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5173. foreach($htmlOptions['empty'] as $value=>$label)
  5174. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5175. unset($htmlOptions['empty']);
  5176. }
  5177. if(isset($htmlOptions['options']))
  5178. {
  5179. $options=$htmlOptions['options'];
  5180. unset($htmlOptions['options']);
  5181. }
  5182. else
  5183. $options=array();
  5184. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  5185. if(is_array($selection))
  5186. {
  5187. foreach($selection as $i=>$item)
  5188. {
  5189. if(is_object($item))
  5190. $selection[$i]=$item->$key;
  5191. }
  5192. }
  5193. else if(is_object($selection))
  5194. $selection=$selection->$key;
  5195. foreach($listData as $key=>$value)
  5196. {
  5197. if(is_array($value))
  5198. {
  5199. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  5200. $dummy=array('options'=>$options);
  5201. if(isset($htmlOptions['encode']))
  5202. $dummy['encode']=$htmlOptions['encode'];
  5203. $content.=self::listOptions($selection,$value,$dummy);
  5204. $content.='</optgroup>'."\n";
  5205. }
  5206. else
  5207. {
  5208. $attributes=array('value'=>(string)$key, 'encode'=>!$raw);
  5209. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  5210. $attributes['selected']='selected';
  5211. if(isset($options[$key]))
  5212. $attributes=array_merge($attributes,$options[$key]);
  5213. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  5214. }
  5215. }
  5216. unset($htmlOptions['key']);
  5217. return $content;
  5218. }
  5219. protected static function clientChange($event,&$htmlOptions)
  5220. {
  5221. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  5222. return;
  5223. if(isset($htmlOptions['live']))
  5224. {
  5225. $live=$htmlOptions['live'];
  5226. unset($htmlOptions['live']);
  5227. }
  5228. else
  5229. $live = self::$liveEvents;
  5230. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  5231. $return='return true';
  5232. else
  5233. $return='return false';
  5234. if(isset($htmlOptions['on'.$event]))
  5235. {
  5236. $handler=trim($htmlOptions['on'.$event],';').';';
  5237. unset($htmlOptions['on'.$event]);
  5238. }
  5239. else
  5240. $handler='';
  5241. if(isset($htmlOptions['id']))
  5242. $id=$htmlOptions['id'];
  5243. else
  5244. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  5245. $cs=Yii::app()->getClientScript();
  5246. $cs->registerCoreScript('jquery');
  5247. if(isset($htmlOptions['submit']))
  5248. {
  5249. $cs->registerCoreScript('yii');
  5250. $request=Yii::app()->getRequest();
  5251. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  5252. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  5253. if(isset($htmlOptions['params']))
  5254. $params=CJavaScript::encode($htmlOptions['params']);
  5255. else
  5256. $params='{}';
  5257. if($htmlOptions['submit']!=='')
  5258. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  5259. else
  5260. $url='';
  5261. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  5262. }
  5263. if(isset($htmlOptions['ajax']))
  5264. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  5265. if(isset($htmlOptions['confirm']))
  5266. {
  5267. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  5268. if($handler!=='')
  5269. $handler="if($confirm) {".$handler."} else return false;";
  5270. else
  5271. $handler="return $confirm;";
  5272. }
  5273. if($live)
  5274. $cs->registerScript('Yii.CHtml.#' . $id, "$('body').on('$event','#$id',function(){{$handler}});");
  5275. else
  5276. $cs->registerScript('Yii.CHtml.#' . $id, "$('#$id').on('$event', function(){{$handler}});");
  5277. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  5278. }
  5279. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  5280. {
  5281. if(!isset($htmlOptions['name']))
  5282. $htmlOptions['name']=self::resolveName($model,$attribute);
  5283. if(!isset($htmlOptions['id']))
  5284. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  5285. else if($htmlOptions['id']===false)
  5286. unset($htmlOptions['id']);
  5287. }
  5288. public static function resolveName($model,&$attribute)
  5289. {
  5290. if(($pos=strpos($attribute,'['))!==false)
  5291. {
  5292. if($pos!==0) // e.g. name[a][b]
  5293. return get_class($model).'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5294. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5295. {
  5296. $sub=substr($attribute,0,$pos+1);
  5297. $attribute=substr($attribute,$pos+1);
  5298. return get_class($model).$sub.'['.$attribute.']';
  5299. }
  5300. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5301. {
  5302. $name=get_class($model).'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5303. $attribute=$matches[1];
  5304. return $name;
  5305. }
  5306. }
  5307. return get_class($model).'['.$attribute.']';
  5308. }
  5309. public static function resolveValue($model,$attribute)
  5310. {
  5311. if(($pos=strpos($attribute,'['))!==false)
  5312. {
  5313. if($pos===0) // [a]name[b][c], should ignore [a]
  5314. {
  5315. if(preg_match('/\](\w+)/',$attribute,$matches))
  5316. $attribute=$matches[1];
  5317. if(($pos=strpos($attribute,'['))===false)
  5318. return $model->$attribute;
  5319. }
  5320. $name=substr($attribute,0,$pos);
  5321. $value=$model->$name;
  5322. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5323. {
  5324. if(is_array($value) && isset($value[$id]))
  5325. $value=$value[$id];
  5326. else
  5327. return null;
  5328. }
  5329. return $value;
  5330. }
  5331. else
  5332. return $model->$attribute;
  5333. }
  5334. protected static function addErrorCss(&$htmlOptions)
  5335. {
  5336. if(isset($htmlOptions['class']))
  5337. $htmlOptions['class'].=' '.self::$errorCss;
  5338. else
  5339. $htmlOptions['class']=self::$errorCss;
  5340. }
  5341. public static function renderAttributes($htmlOptions)
  5342. {
  5343. static $specialAttributes=array(
  5344. 'checked'=>1,
  5345. 'declare'=>1,
  5346. 'defer'=>1,
  5347. 'disabled'=>1,
  5348. 'ismap'=>1,
  5349. 'multiple'=>1,
  5350. 'nohref'=>1,
  5351. 'noresize'=>1,
  5352. 'readonly'=>1,
  5353. 'selected'=>1,
  5354. );
  5355. if($htmlOptions===array())
  5356. return '';
  5357. $html='';
  5358. if(isset($htmlOptions['encode']))
  5359. {
  5360. $raw=!$htmlOptions['encode'];
  5361. unset($htmlOptions['encode']);
  5362. }
  5363. else
  5364. $raw=false;
  5365. if($raw)
  5366. {
  5367. foreach($htmlOptions as $name=>$value)
  5368. {
  5369. if(isset($specialAttributes[$name]))
  5370. {
  5371. if($value)
  5372. $html .= ' ' . $name . '="' . $name . '"';
  5373. }
  5374. else if($value!==null)
  5375. $html .= ' ' . $name . '="' . $value . '"';
  5376. }
  5377. }
  5378. else
  5379. {
  5380. foreach($htmlOptions as $name=>$value)
  5381. {
  5382. if(isset($specialAttributes[$name]))
  5383. {
  5384. if($value)
  5385. $html .= ' ' . $name . '="' . $name . '"';
  5386. }
  5387. else if($value!==null)
  5388. $html .= ' ' . $name . '="' . self::encode($value) . '"';
  5389. }
  5390. }
  5391. return $html;
  5392. }
  5393. }
  5394. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  5395. {
  5396. public $enableSkin=false;
  5397. public $widgets=array();
  5398. public $skinnableWidgets;
  5399. public $skinPath;
  5400. private $_skins=array(); // class name, skin name, property name => value
  5401. public function init()
  5402. {
  5403. parent::init();
  5404. if($this->enableSkin && $this->skinPath===null)
  5405. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  5406. }
  5407. public function createWidget($owner,$className,$properties=array())
  5408. {
  5409. $className=Yii::import($className,true);
  5410. $widget=new $className($owner);
  5411. if(isset($this->widgets[$className]))
  5412. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  5413. if($this->enableSkin)
  5414. {
  5415. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  5416. {
  5417. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  5418. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  5419. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  5420. }
  5421. }
  5422. foreach($properties as $name=>$value)
  5423. $widget->$name=$value;
  5424. return $widget;
  5425. }
  5426. protected function getSkin($className,$skinName)
  5427. {
  5428. if(!isset($this->_skins[$className][$skinName]))
  5429. {
  5430. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  5431. if(is_file($skinFile))
  5432. $this->_skins[$className]=require($skinFile);
  5433. else
  5434. $this->_skins[$className]=array();
  5435. if(($theme=Yii::app()->getTheme())!==null)
  5436. {
  5437. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  5438. if(is_file($skinFile))
  5439. {
  5440. $skins=require($skinFile);
  5441. foreach($skins as $name=>$skin)
  5442. $this->_skins[$className][$name]=$skin;
  5443. }
  5444. }
  5445. if(!isset($this->_skins[$className][$skinName]))
  5446. $this->_skins[$className][$skinName]=array();
  5447. }
  5448. return $this->_skins[$className][$skinName];
  5449. }
  5450. }
  5451. class CWidget extends CBaseController
  5452. {
  5453. public $actionPrefix;
  5454. public $skin='default';
  5455. private static $_viewPaths;
  5456. private static $_counter=0;
  5457. private $_id;
  5458. private $_owner;
  5459. public static function actions()
  5460. {
  5461. return array();
  5462. }
  5463. public function __construct($owner=null)
  5464. {
  5465. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  5466. }
  5467. public function getOwner()
  5468. {
  5469. return $this->_owner;
  5470. }
  5471. public function getId($autoGenerate=true)
  5472. {
  5473. if($this->_id!==null)
  5474. return $this->_id;
  5475. else if($autoGenerate)
  5476. return $this->_id='yw'.self::$_counter++;
  5477. }
  5478. public function setId($value)
  5479. {
  5480. $this->_id=$value;
  5481. }
  5482. public function getController()
  5483. {
  5484. if($this->_owner instanceof CController)
  5485. return $this->_owner;
  5486. else
  5487. return Yii::app()->getController();
  5488. }
  5489. public function init()
  5490. {
  5491. }
  5492. public function run()
  5493. {
  5494. }
  5495. public function getViewPath($checkTheme=false)
  5496. {
  5497. $className=get_class($this);
  5498. if(isset(self::$_viewPaths[$className]))
  5499. return self::$_viewPaths[$className];
  5500. else
  5501. {
  5502. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  5503. {
  5504. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  5505. if(strpos($className,'\\')!==false) // namespaced class
  5506. $path.=str_replace('\\','_',ltrim($className,'\\'));
  5507. else
  5508. $path.=$className;
  5509. if(is_dir($path))
  5510. return self::$_viewPaths[$className]=$path;
  5511. }
  5512. $class=new ReflectionClass($className);
  5513. return self::$_viewPaths[$className]=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  5514. }
  5515. }
  5516. public function getViewFile($viewName)
  5517. {
  5518. if(($renderer=Yii::app()->getViewRenderer())!==null)
  5519. $extension=$renderer->fileExtension;
  5520. else
  5521. $extension='.php';
  5522. if(strpos($viewName,'.')) // a path alias
  5523. $viewFile=Yii::getPathOfAlias($viewName);
  5524. else
  5525. {
  5526. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  5527. if(is_file($viewFile.$extension))
  5528. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5529. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5530. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5531. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  5532. }
  5533. if(is_file($viewFile.$extension))
  5534. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5535. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5536. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5537. else
  5538. return false;
  5539. }
  5540. public function render($view,$data=null,$return=false)
  5541. {
  5542. if(($viewFile=$this->getViewFile($view))!==false)
  5543. return $this->renderFile($viewFile,$data,$return);
  5544. else
  5545. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  5546. array('{widget}'=>get_class($this), '{view}'=>$view)));
  5547. }
  5548. }
  5549. class CClientScript extends CApplicationComponent
  5550. {
  5551. const POS_HEAD=0;
  5552. const POS_BEGIN=1;
  5553. const POS_END=2;
  5554. const POS_LOAD=3;
  5555. const POS_READY=4;
  5556. public $enableJavaScript=true;
  5557. public $scriptMap=array();
  5558. public $packages=array();
  5559. public $corePackages;
  5560. protected $cssFiles=array();
  5561. protected $scriptFiles=array();
  5562. protected $scripts=array();
  5563. protected $metaTags=array();
  5564. protected $linkTags=array();
  5565. protected $css=array();
  5566. protected $hasScripts=false;
  5567. protected $coreScripts=array();
  5568. public $coreScriptPosition=self::POS_HEAD;
  5569. private $_baseUrl;
  5570. public function reset()
  5571. {
  5572. $this->hasScripts=false;
  5573. $this->coreScripts=array();
  5574. $this->cssFiles=array();
  5575. $this->css=array();
  5576. $this->scriptFiles=array();
  5577. $this->scripts=array();
  5578. $this->metaTags=array();
  5579. $this->linkTags=array();
  5580. $this->recordCachingAction('clientScript','reset',array());
  5581. }
  5582. public function render(&$output)
  5583. {
  5584. if(!$this->hasScripts)
  5585. return;
  5586. $this->renderCoreScripts();
  5587. if(!empty($this->scriptMap))
  5588. $this->remapScripts();
  5589. $this->unifyScripts();
  5590. $this->renderHead($output);
  5591. if($this->enableJavaScript)
  5592. {
  5593. $this->renderBodyBegin($output);
  5594. $this->renderBodyEnd($output);
  5595. }
  5596. }
  5597. protected function unifyScripts()
  5598. {
  5599. if(!$this->enableJavaScript)
  5600. return;
  5601. $map=array();
  5602. if(isset($this->scriptFiles[self::POS_HEAD]))
  5603. $map=$this->scriptFiles[self::POS_HEAD];
  5604. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5605. {
  5606. foreach($this->scriptFiles[self::POS_BEGIN] as $key=>$scriptFile)
  5607. {
  5608. if(isset($map[$scriptFile]))
  5609. unset($this->scriptFiles[self::POS_BEGIN][$key]);
  5610. else
  5611. $map[$scriptFile]=true;
  5612. }
  5613. }
  5614. if(isset($this->scriptFiles[self::POS_END]))
  5615. {
  5616. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  5617. {
  5618. if(isset($map[$scriptFile]))
  5619. unset($this->scriptFiles[self::POS_END][$key]);
  5620. }
  5621. }
  5622. }
  5623. protected function remapScripts()
  5624. {
  5625. $cssFiles=array();
  5626. foreach($this->cssFiles as $url=>$media)
  5627. {
  5628. $name=basename($url);
  5629. if(isset($this->scriptMap[$name]))
  5630. {
  5631. if($this->scriptMap[$name]!==false)
  5632. $cssFiles[$this->scriptMap[$name]]=$media;
  5633. }
  5634. else if(isset($this->scriptMap['*.css']))
  5635. {
  5636. if($this->scriptMap['*.css']!==false)
  5637. $cssFiles[$this->scriptMap['*.css']]=$media;
  5638. }
  5639. else
  5640. $cssFiles[$url]=$media;
  5641. }
  5642. $this->cssFiles=$cssFiles;
  5643. $jsFiles=array();
  5644. foreach($this->scriptFiles as $position=>$scripts)
  5645. {
  5646. $jsFiles[$position]=array();
  5647. foreach($scripts as $key=>$script)
  5648. {
  5649. $name=basename($script);
  5650. if(isset($this->scriptMap[$name]))
  5651. {
  5652. if($this->scriptMap[$name]!==false)
  5653. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  5654. }
  5655. else if(isset($this->scriptMap['*.js']))
  5656. {
  5657. if($this->scriptMap['*.js']!==false)
  5658. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  5659. }
  5660. else
  5661. $jsFiles[$position][$key]=$script;
  5662. }
  5663. }
  5664. $this->scriptFiles=$jsFiles;
  5665. }
  5666. public function renderCoreScripts()
  5667. {
  5668. if($this->coreScripts===null)
  5669. return;
  5670. $cssFiles=array();
  5671. $jsFiles=array();
  5672. foreach($this->coreScripts as $name=>$package)
  5673. {
  5674. $baseUrl=$this->getPackageBaseUrl($name);
  5675. if(!empty($package['js']))
  5676. {
  5677. foreach($package['js'] as $js)
  5678. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  5679. }
  5680. if(!empty($package['css']))
  5681. {
  5682. foreach($package['css'] as $css)
  5683. $cssFiles[$baseUrl.'/'.$css]='';
  5684. }
  5685. }
  5686. // merge in place
  5687. if($cssFiles!==array())
  5688. {
  5689. foreach($this->cssFiles as $cssFile=>$media)
  5690. $cssFiles[$cssFile]=$media;
  5691. $this->cssFiles=$cssFiles;
  5692. }
  5693. if($jsFiles!==array())
  5694. {
  5695. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  5696. {
  5697. foreach($this->scriptFiles[$this->coreScriptPosition] as $url)
  5698. $jsFiles[$url]=$url;
  5699. }
  5700. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  5701. }
  5702. }
  5703. public function renderHead(&$output)
  5704. {
  5705. $html='';
  5706. foreach($this->metaTags as $meta)
  5707. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  5708. foreach($this->linkTags as $link)
  5709. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  5710. foreach($this->cssFiles as $url=>$media)
  5711. $html.=CHtml::cssFile($url,$media)."\n";
  5712. foreach($this->css as $css)
  5713. $html.=CHtml::css($css[0],$css[1])."\n";
  5714. if($this->enableJavaScript)
  5715. {
  5716. if(isset($this->scriptFiles[self::POS_HEAD]))
  5717. {
  5718. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFile)
  5719. $html.=CHtml::scriptFile($scriptFile)."\n";
  5720. }
  5721. if(isset($this->scripts[self::POS_HEAD]))
  5722. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_HEAD]))."\n";
  5723. }
  5724. if($html!=='')
  5725. {
  5726. $count=0;
  5727. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  5728. if($count)
  5729. $output=str_replace('<###head###>',$html,$output);
  5730. else
  5731. $output=$html.$output;
  5732. }
  5733. }
  5734. public function renderBodyBegin(&$output)
  5735. {
  5736. $html='';
  5737. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5738. {
  5739. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile)
  5740. $html.=CHtml::scriptFile($scriptFile)."\n";
  5741. }
  5742. if(isset($this->scripts[self::POS_BEGIN]))
  5743. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_BEGIN]))."\n";
  5744. if($html!=='')
  5745. {
  5746. $count=0;
  5747. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  5748. if($count)
  5749. $output=str_replace('<###begin###>',$html,$output);
  5750. else
  5751. $output=$html.$output;
  5752. }
  5753. }
  5754. public function renderBodyEnd(&$output)
  5755. {
  5756. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  5757. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  5758. return;
  5759. $fullPage=0;
  5760. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  5761. $html='';
  5762. if(isset($this->scriptFiles[self::POS_END]))
  5763. {
  5764. foreach($this->scriptFiles[self::POS_END] as $scriptFile)
  5765. $html.=CHtml::scriptFile($scriptFile)."\n";
  5766. }
  5767. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  5768. if(isset($this->scripts[self::POS_READY]))
  5769. {
  5770. if($fullPage)
  5771. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  5772. else
  5773. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  5774. }
  5775. if(isset($this->scripts[self::POS_LOAD]))
  5776. {
  5777. if($fullPage)
  5778. $scripts[]="jQuery(window).load(function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  5779. else
  5780. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  5781. }
  5782. if(!empty($scripts))
  5783. $html.=CHtml::script(implode("\n",$scripts))."\n";
  5784. if($fullPage)
  5785. $output=str_replace('<###end###>',$html,$output);
  5786. else
  5787. $output=$output.$html;
  5788. }
  5789. public function getCoreScriptUrl()
  5790. {
  5791. if($this->_baseUrl!==null)
  5792. return $this->_baseUrl;
  5793. else
  5794. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  5795. }
  5796. public function setCoreScriptUrl($value)
  5797. {
  5798. $this->_baseUrl=$value;
  5799. }
  5800. public function getPackageBaseUrl($name)
  5801. {
  5802. if(!isset($this->coreScripts[$name]))
  5803. return false;
  5804. $package=$this->coreScripts[$name];
  5805. if(isset($package['baseUrl']))
  5806. {
  5807. $baseUrl=$package['baseUrl'];
  5808. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  5809. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  5810. $baseUrl=rtrim($baseUrl,'/');
  5811. }
  5812. else if(isset($package['basePath']))
  5813. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  5814. else
  5815. $baseUrl=$this->getCoreScriptUrl();
  5816. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  5817. }
  5818. public function registerPackage($name)
  5819. {
  5820. return $this->registerCoreScript($name);
  5821. }
  5822. public function registerCoreScript($name)
  5823. {
  5824. if(isset($this->coreScripts[$name]))
  5825. return $this;
  5826. if(isset($this->packages[$name]))
  5827. $package=$this->packages[$name];
  5828. else
  5829. {
  5830. if($this->corePackages===null)
  5831. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  5832. if(isset($this->corePackages[$name]))
  5833. $package=$this->corePackages[$name];
  5834. }
  5835. if(isset($package))
  5836. {
  5837. if(!empty($package['depends']))
  5838. {
  5839. foreach($package['depends'] as $p)
  5840. $this->registerCoreScript($p);
  5841. }
  5842. $this->coreScripts[$name]=$package;
  5843. $this->hasScripts=true;
  5844. $params=func_get_args();
  5845. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  5846. }
  5847. return $this;
  5848. }
  5849. public function registerCssFile($url,$media='')
  5850. {
  5851. $this->hasScripts=true;
  5852. $this->cssFiles[$url]=$media;
  5853. $params=func_get_args();
  5854. $this->recordCachingAction('clientScript','registerCssFile',$params);
  5855. return $this;
  5856. }
  5857. public function registerCss($id,$css,$media='')
  5858. {
  5859. $this->hasScripts=true;
  5860. $this->css[$id]=array($css,$media);
  5861. $params=func_get_args();
  5862. $this->recordCachingAction('clientScript','registerCss',$params);
  5863. return $this;
  5864. }
  5865. public function registerScriptFile($url,$position=self::POS_HEAD)
  5866. {
  5867. $this->hasScripts=true;
  5868. $this->scriptFiles[$position][$url]=$url;
  5869. $params=func_get_args();
  5870. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  5871. return $this;
  5872. }
  5873. public function registerScript($id,$script,$position=self::POS_READY)
  5874. {
  5875. $this->hasScripts=true;
  5876. $this->scripts[$position][$id]=$script;
  5877. if($position===self::POS_READY || $position===self::POS_LOAD)
  5878. $this->registerCoreScript('jquery');
  5879. $params=func_get_args();
  5880. $this->recordCachingAction('clientScript','registerScript',$params);
  5881. return $this;
  5882. }
  5883. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array())
  5884. {
  5885. $this->hasScripts=true;
  5886. if($name!==null)
  5887. $options['name']=$name;
  5888. if($httpEquiv!==null)
  5889. $options['http-equiv']=$httpEquiv;
  5890. $options['content']=$content;
  5891. $this->metaTags[serialize($options)]=$options;
  5892. $params=func_get_args();
  5893. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  5894. return $this;
  5895. }
  5896. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  5897. {
  5898. $this->hasScripts=true;
  5899. if($relation!==null)
  5900. $options['rel']=$relation;
  5901. if($type!==null)
  5902. $options['type']=$type;
  5903. if($href!==null)
  5904. $options['href']=$href;
  5905. if($media!==null)
  5906. $options['media']=$media;
  5907. $this->linkTags[serialize($options)]=$options;
  5908. $params=func_get_args();
  5909. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  5910. return $this;
  5911. }
  5912. public function isCssFileRegistered($url)
  5913. {
  5914. return isset($this->cssFiles[$url]);
  5915. }
  5916. public function isCssRegistered($id)
  5917. {
  5918. return isset($this->css[$id]);
  5919. }
  5920. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  5921. {
  5922. return isset($this->scriptFiles[$position][$url]);
  5923. }
  5924. public function isScriptRegistered($id,$position=self::POS_READY)
  5925. {
  5926. return isset($this->scripts[$position][$id]);
  5927. }
  5928. protected function recordCachingAction($context,$method,$params)
  5929. {
  5930. if(($controller=Yii::app()->getController())!==null)
  5931. $controller->recordCachingAction($context,$method,$params);
  5932. }
  5933. public function addPackage($name,$definition)
  5934. {
  5935. $this->packages[$name]=$definition;
  5936. return $this;
  5937. }
  5938. }
  5939. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  5940. {
  5941. private $_d=array();
  5942. private $_c=0;
  5943. private $_r=false;
  5944. public function __construct($data=null,$readOnly=false)
  5945. {
  5946. if($data!==null)
  5947. $this->copyFrom($data);
  5948. $this->setReadOnly($readOnly);
  5949. }
  5950. public function getReadOnly()
  5951. {
  5952. return $this->_r;
  5953. }
  5954. protected function setReadOnly($value)
  5955. {
  5956. $this->_r=$value;
  5957. }
  5958. public function getIterator()
  5959. {
  5960. return new CListIterator($this->_d);
  5961. }
  5962. public function count()
  5963. {
  5964. return $this->getCount();
  5965. }
  5966. public function getCount()
  5967. {
  5968. return $this->_c;
  5969. }
  5970. public function itemAt($index)
  5971. {
  5972. if(isset($this->_d[$index]))
  5973. return $this->_d[$index];
  5974. else if($index>=0 && $index<$this->_c) // in case the value is null
  5975. return $this->_d[$index];
  5976. else
  5977. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  5978. array('{index}'=>$index)));
  5979. }
  5980. public function add($item)
  5981. {
  5982. $this->insertAt($this->_c,$item);
  5983. return $this->_c-1;
  5984. }
  5985. public function insertAt($index,$item)
  5986. {
  5987. if(!$this->_r)
  5988. {
  5989. if($index===$this->_c)
  5990. $this->_d[$this->_c++]=$item;
  5991. else if($index>=0 && $index<$this->_c)
  5992. {
  5993. array_splice($this->_d,$index,0,array($item));
  5994. $this->_c++;
  5995. }
  5996. else
  5997. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  5998. array('{index}'=>$index)));
  5999. }
  6000. else
  6001. throw new CException(Yii::t('yii','The list is read only.'));
  6002. }
  6003. public function remove($item)
  6004. {
  6005. if(($index=$this->indexOf($item))>=0)
  6006. {
  6007. $this->removeAt($index);
  6008. return $index;
  6009. }
  6010. else
  6011. return false;
  6012. }
  6013. public function removeAt($index)
  6014. {
  6015. if(!$this->_r)
  6016. {
  6017. if($index>=0 && $index<$this->_c)
  6018. {
  6019. $this->_c--;
  6020. if($index===$this->_c)
  6021. return array_pop($this->_d);
  6022. else
  6023. {
  6024. $item=$this->_d[$index];
  6025. array_splice($this->_d,$index,1);
  6026. return $item;
  6027. }
  6028. }
  6029. else
  6030. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6031. array('{index}'=>$index)));
  6032. }
  6033. else
  6034. throw new CException(Yii::t('yii','The list is read only.'));
  6035. }
  6036. public function clear()
  6037. {
  6038. for($i=$this->_c-1;$i>=0;--$i)
  6039. $this->removeAt($i);
  6040. }
  6041. public function contains($item)
  6042. {
  6043. return $this->indexOf($item)>=0;
  6044. }
  6045. public function indexOf($item)
  6046. {
  6047. if(($index=array_search($item,$this->_d,true))!==false)
  6048. return $index;
  6049. else
  6050. return -1;
  6051. }
  6052. public function toArray()
  6053. {
  6054. return $this->_d;
  6055. }
  6056. public function copyFrom($data)
  6057. {
  6058. if(is_array($data) || ($data instanceof Traversable))
  6059. {
  6060. if($this->_c>0)
  6061. $this->clear();
  6062. if($data instanceof CList)
  6063. $data=$data->_d;
  6064. foreach($data as $item)
  6065. $this->add($item);
  6066. }
  6067. else if($data!==null)
  6068. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6069. }
  6070. public function mergeWith($data)
  6071. {
  6072. if(is_array($data) || ($data instanceof Traversable))
  6073. {
  6074. if($data instanceof CList)
  6075. $data=$data->_d;
  6076. foreach($data as $item)
  6077. $this->add($item);
  6078. }
  6079. else if($data!==null)
  6080. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6081. }
  6082. public function offsetExists($offset)
  6083. {
  6084. return ($offset>=0 && $offset<$this->_c);
  6085. }
  6086. public function offsetGet($offset)
  6087. {
  6088. return $this->itemAt($offset);
  6089. }
  6090. public function offsetSet($offset,$item)
  6091. {
  6092. if($offset===null || $offset===$this->_c)
  6093. $this->insertAt($this->_c,$item);
  6094. else
  6095. {
  6096. $this->removeAt($offset);
  6097. $this->insertAt($offset,$item);
  6098. }
  6099. }
  6100. public function offsetUnset($offset)
  6101. {
  6102. $this->removeAt($offset);
  6103. }
  6104. }
  6105. class CFilterChain extends CList
  6106. {
  6107. public $controller;
  6108. public $action;
  6109. public $filterIndex=0;
  6110. public function __construct($controller,$action)
  6111. {
  6112. $this->controller=$controller;
  6113. $this->action=$action;
  6114. }
  6115. public static function create($controller,$action,$filters)
  6116. {
  6117. $chain=new CFilterChain($controller,$action);
  6118. $actionID=$action->getId();
  6119. foreach($filters as $filter)
  6120. {
  6121. if(is_string($filter)) // filterName [+|- action1 action2]
  6122. {
  6123. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  6124. {
  6125. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  6126. if(($filter[$pos]==='+')===$matched)
  6127. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  6128. }
  6129. else
  6130. $filter=CInlineFilter::create($controller,$filter);
  6131. }
  6132. else if(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  6133. {
  6134. if(!isset($filter[0]))
  6135. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  6136. $filterClass=$filter[0];
  6137. unset($filter[0]);
  6138. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  6139. {
  6140. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  6141. if(($filterClass[$pos]==='+')===$matched)
  6142. $filterClass=trim(substr($filterClass,0,$pos));
  6143. else
  6144. continue;
  6145. }
  6146. $filter['class']=$filterClass;
  6147. $filter=Yii::createComponent($filter);
  6148. }
  6149. if(is_object($filter))
  6150. {
  6151. $filter->init();
  6152. $chain->add($filter);
  6153. }
  6154. }
  6155. return $chain;
  6156. }
  6157. public function insertAt($index,$item)
  6158. {
  6159. if($item instanceof IFilter)
  6160. parent::insertAt($index,$item);
  6161. else
  6162. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  6163. }
  6164. public function run()
  6165. {
  6166. if($this->offsetExists($this->filterIndex))
  6167. {
  6168. $filter=$this->itemAt($this->filterIndex++);
  6169. $filter->filter($this);
  6170. }
  6171. else
  6172. $this->controller->runAction($this->action);
  6173. }
  6174. }
  6175. class CFilter extends CComponent implements IFilter
  6176. {
  6177. public function filter($filterChain)
  6178. {
  6179. if($this->preFilter($filterChain))
  6180. {
  6181. $filterChain->run();
  6182. $this->postFilter($filterChain);
  6183. }
  6184. }
  6185. public function init()
  6186. {
  6187. }
  6188. protected function preFilter($filterChain)
  6189. {
  6190. return true;
  6191. }
  6192. protected function postFilter($filterChain)
  6193. {
  6194. }
  6195. }
  6196. class CInlineFilter extends CFilter
  6197. {
  6198. public $name;
  6199. public static function create($controller,$filterName)
  6200. {
  6201. if(method_exists($controller,'filter'.$filterName))
  6202. {
  6203. $filter=new CInlineFilter;
  6204. $filter->name=$filterName;
  6205. return $filter;
  6206. }
  6207. else
  6208. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  6209. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  6210. }
  6211. public function filter($filterChain)
  6212. {
  6213. $method='filter'.$this->name;
  6214. $filterChain->controller->$method($filterChain);
  6215. }
  6216. }
  6217. class CAccessControlFilter extends CFilter
  6218. {
  6219. public $message;
  6220. private $_rules=array();
  6221. public function getRules()
  6222. {
  6223. return $this->_rules;
  6224. }
  6225. public function setRules($rules)
  6226. {
  6227. foreach($rules as $rule)
  6228. {
  6229. if(is_array($rule) && isset($rule[0]))
  6230. {
  6231. $r=new CAccessRule;
  6232. $r->allow=$rule[0]==='allow';
  6233. foreach(array_slice($rule,1) as $name=>$value)
  6234. {
  6235. if($name==='expression' || $name==='roles' || $name==='message')
  6236. $r->$name=$value;
  6237. else
  6238. $r->$name=array_map('strtolower',$value);
  6239. }
  6240. $this->_rules[]=$r;
  6241. }
  6242. }
  6243. }
  6244. protected function preFilter($filterChain)
  6245. {
  6246. $app=Yii::app();
  6247. $request=$app->getRequest();
  6248. $user=$app->getUser();
  6249. $verb=$request->getRequestType();
  6250. $ip=$request->getUserHostAddress();
  6251. foreach($this->getRules() as $rule)
  6252. {
  6253. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  6254. break;
  6255. else if($allow<0) // denied
  6256. {
  6257. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  6258. return false;
  6259. }
  6260. }
  6261. return true;
  6262. }
  6263. protected function resolveErrorMessage($rule)
  6264. {
  6265. if($rule->message!==null)
  6266. return $rule->message;
  6267. else if($this->message!==null)
  6268. return $this->message;
  6269. else
  6270. return Yii::t('yii','You are not authorized to perform this action.');
  6271. }
  6272. protected function accessDenied($user,$message)
  6273. {
  6274. if($user->getIsGuest())
  6275. $user->loginRequired();
  6276. else
  6277. throw new CHttpException(403,$message);
  6278. }
  6279. }
  6280. class CAccessRule extends CComponent
  6281. {
  6282. public $allow;
  6283. public $actions;
  6284. public $controllers;
  6285. public $users;
  6286. public $roles;
  6287. public $ips;
  6288. public $verbs;
  6289. public $expression;
  6290. public $message;
  6291. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  6292. {
  6293. if($this->isActionMatched($action)
  6294. && $this->isUserMatched($user)
  6295. && $this->isRoleMatched($user)
  6296. && $this->isIpMatched($ip)
  6297. && $this->isVerbMatched($verb)
  6298. && $this->isControllerMatched($controller)
  6299. && $this->isExpressionMatched($user))
  6300. return $this->allow ? 1 : -1;
  6301. else
  6302. return 0;
  6303. }
  6304. protected function isActionMatched($action)
  6305. {
  6306. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  6307. }
  6308. protected function isControllerMatched($controller)
  6309. {
  6310. return empty($this->controllers) || in_array(strtolower($controller->getId()),$this->controllers);
  6311. }
  6312. protected function isUserMatched($user)
  6313. {
  6314. if(empty($this->users))
  6315. return true;
  6316. foreach($this->users as $u)
  6317. {
  6318. if($u==='*')
  6319. return true;
  6320. else if($u==='?' && $user->getIsGuest())
  6321. return true;
  6322. else if($u==='@' && !$user->getIsGuest())
  6323. return true;
  6324. else if(!strcasecmp($u,$user->getName()))
  6325. return true;
  6326. }
  6327. return false;
  6328. }
  6329. protected function isRoleMatched($user)
  6330. {
  6331. if(empty($this->roles))
  6332. return true;
  6333. foreach($this->roles as $role)
  6334. {
  6335. if($user->checkAccess($role))
  6336. return true;
  6337. }
  6338. return false;
  6339. }
  6340. protected function isIpMatched($ip)
  6341. {
  6342. if(empty($this->ips))
  6343. return true;
  6344. foreach($this->ips as $rule)
  6345. {
  6346. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  6347. return true;
  6348. }
  6349. return false;
  6350. }
  6351. protected function isVerbMatched($verb)
  6352. {
  6353. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  6354. }
  6355. protected function isExpressionMatched($user)
  6356. {
  6357. if($this->expression===null)
  6358. return true;
  6359. else
  6360. return $this->evaluateExpression($this->expression, array('user'=>$user));
  6361. }
  6362. }
  6363. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  6364. {
  6365. private $_errors=array(); // attribute name => array of errors
  6366. private $_validators; // validators
  6367. private $_scenario=''; // scenario
  6368. abstract public function attributeNames();
  6369. public function rules()
  6370. {
  6371. return array();
  6372. }
  6373. public function behaviors()
  6374. {
  6375. return array();
  6376. }
  6377. public function attributeLabels()
  6378. {
  6379. return array();
  6380. }
  6381. public function validate($attributes=null, $clearErrors=true)
  6382. {
  6383. if($clearErrors)
  6384. $this->clearErrors();
  6385. if($this->beforeValidate())
  6386. {
  6387. foreach($this->getValidators() as $validator)
  6388. $validator->validate($this,$attributes);
  6389. $this->afterValidate();
  6390. return !$this->hasErrors();
  6391. }
  6392. else
  6393. return false;
  6394. }
  6395. protected function afterConstruct()
  6396. {
  6397. if($this->hasEventHandler('onAfterConstruct'))
  6398. $this->onAfterConstruct(new CEvent($this));
  6399. }
  6400. protected function beforeValidate()
  6401. {
  6402. $event=new CModelEvent($this);
  6403. $this->onBeforeValidate($event);
  6404. return $event->isValid;
  6405. }
  6406. protected function afterValidate()
  6407. {
  6408. $this->onAfterValidate(new CEvent($this));
  6409. }
  6410. public function onAfterConstruct($event)
  6411. {
  6412. $this->raiseEvent('onAfterConstruct',$event);
  6413. }
  6414. public function onBeforeValidate($event)
  6415. {
  6416. $this->raiseEvent('onBeforeValidate',$event);
  6417. }
  6418. public function onAfterValidate($event)
  6419. {
  6420. $this->raiseEvent('onAfterValidate',$event);
  6421. }
  6422. public function getValidatorList()
  6423. {
  6424. if($this->_validators===null)
  6425. $this->_validators=$this->createValidators();
  6426. return $this->_validators;
  6427. }
  6428. public function getValidators($attribute=null)
  6429. {
  6430. if($this->_validators===null)
  6431. $this->_validators=$this->createValidators();
  6432. $validators=array();
  6433. $scenario=$this->getScenario();
  6434. foreach($this->_validators as $validator)
  6435. {
  6436. if($validator->applyTo($scenario))
  6437. {
  6438. if($attribute===null || in_array($attribute,$validator->attributes,true))
  6439. $validators[]=$validator;
  6440. }
  6441. }
  6442. return $validators;
  6443. }
  6444. public function createValidators()
  6445. {
  6446. $validators=new CList;
  6447. foreach($this->rules() as $rule)
  6448. {
  6449. if(isset($rule[0],$rule[1])) // attributes, validator name
  6450. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  6451. else
  6452. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  6453. array('{class}'=>get_class($this))));
  6454. }
  6455. return $validators;
  6456. }
  6457. public function isAttributeRequired($attribute)
  6458. {
  6459. foreach($this->getValidators($attribute) as $validator)
  6460. {
  6461. if($validator instanceof CRequiredValidator)
  6462. return true;
  6463. }
  6464. return false;
  6465. }
  6466. public function isAttributeSafe($attribute)
  6467. {
  6468. $attributes=$this->getSafeAttributeNames();
  6469. return in_array($attribute,$attributes);
  6470. }
  6471. public function getAttributeLabel($attribute)
  6472. {
  6473. $labels=$this->attributeLabels();
  6474. if(isset($labels[$attribute]))
  6475. return $labels[$attribute];
  6476. else
  6477. return $this->generateAttributeLabel($attribute);
  6478. }
  6479. public function hasErrors($attribute=null)
  6480. {
  6481. if($attribute===null)
  6482. return $this->_errors!==array();
  6483. else
  6484. return isset($this->_errors[$attribute]);
  6485. }
  6486. public function getErrors($attribute=null)
  6487. {
  6488. if($attribute===null)
  6489. return $this->_errors;
  6490. else
  6491. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  6492. }
  6493. public function getError($attribute)
  6494. {
  6495. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  6496. }
  6497. public function addError($attribute,$error)
  6498. {
  6499. $this->_errors[$attribute][]=$error;
  6500. }
  6501. public function addErrors($errors)
  6502. {
  6503. foreach($errors as $attribute=>$error)
  6504. {
  6505. if(is_array($error))
  6506. {
  6507. foreach($error as $e)
  6508. $this->_errors[$attribute][]=$e;
  6509. }
  6510. else
  6511. $this->_errors[$attribute][]=$error;
  6512. }
  6513. }
  6514. public function clearErrors($attribute=null)
  6515. {
  6516. if($attribute===null)
  6517. $this->_errors=array();
  6518. else
  6519. unset($this->_errors[$attribute]);
  6520. }
  6521. public function generateAttributeLabel($name)
  6522. {
  6523. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  6524. }
  6525. public function getAttributes($names=null)
  6526. {
  6527. $values=array();
  6528. foreach($this->attributeNames() as $name)
  6529. $values[$name]=$this->$name;
  6530. if(is_array($names))
  6531. {
  6532. $values2=array();
  6533. foreach($names as $name)
  6534. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  6535. return $values2;
  6536. }
  6537. else
  6538. return $values;
  6539. }
  6540. public function setAttributes($values,$safeOnly=true)
  6541. {
  6542. if(!is_array($values))
  6543. return;
  6544. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  6545. foreach($values as $name=>$value)
  6546. {
  6547. if(isset($attributes[$name]))
  6548. $this->$name=$value;
  6549. else if($safeOnly)
  6550. $this->onUnsafeAttribute($name,$value);
  6551. }
  6552. }
  6553. public function unsetAttributes($names=null)
  6554. {
  6555. if($names===null)
  6556. $names=$this->attributeNames();
  6557. foreach($names as $name)
  6558. $this->$name=null;
  6559. }
  6560. public function onUnsafeAttribute($name,$value)
  6561. {
  6562. if(YII_DEBUG)
  6563. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  6564. }
  6565. public function getScenario()
  6566. {
  6567. return $this->_scenario;
  6568. }
  6569. public function setScenario($value)
  6570. {
  6571. $this->_scenario=$value;
  6572. }
  6573. public function getSafeAttributeNames()
  6574. {
  6575. $attributes=array();
  6576. $unsafe=array();
  6577. foreach($this->getValidators() as $validator)
  6578. {
  6579. if(!$validator->safe)
  6580. {
  6581. foreach($validator->attributes as $name)
  6582. $unsafe[]=$name;
  6583. }
  6584. else
  6585. {
  6586. foreach($validator->attributes as $name)
  6587. $attributes[$name]=true;
  6588. }
  6589. }
  6590. foreach($unsafe as $name)
  6591. unset($attributes[$name]);
  6592. return array_keys($attributes);
  6593. }
  6594. public function getIterator()
  6595. {
  6596. $attributes=$this->getAttributes();
  6597. return new CMapIterator($attributes);
  6598. }
  6599. public function offsetExists($offset)
  6600. {
  6601. return property_exists($this,$offset);
  6602. }
  6603. public function offsetGet($offset)
  6604. {
  6605. return $this->$offset;
  6606. }
  6607. public function offsetSet($offset,$item)
  6608. {
  6609. $this->$offset=$item;
  6610. }
  6611. public function offsetUnset($offset)
  6612. {
  6613. unset($this->$offset);
  6614. }
  6615. }
  6616. abstract class CActiveRecord extends CModel
  6617. {
  6618. const BELONGS_TO='CBelongsToRelation';
  6619. const HAS_ONE='CHasOneRelation';
  6620. const HAS_MANY='CHasManyRelation';
  6621. const MANY_MANY='CManyManyRelation';
  6622. const STAT='CStatRelation';
  6623. public static $db;
  6624. private static $_models=array(); // class name => model
  6625. private $_md; // meta data
  6626. private $_new=false; // whether this instance is new or not
  6627. private $_attributes=array(); // attribute name => attribute value
  6628. private $_related=array(); // attribute name => related objects
  6629. private $_c; // query criteria (used by finder only)
  6630. private $_pk; // old primary key value
  6631. private $_alias='t'; // the table alias being used for query
  6632. public function __construct($scenario='insert')
  6633. {
  6634. if($scenario===null) // internally used by populateRecord() and model()
  6635. return;
  6636. $this->setScenario($scenario);
  6637. $this->setIsNewRecord(true);
  6638. $this->_attributes=$this->getMetaData()->attributeDefaults;
  6639. $this->init();
  6640. $this->attachBehaviors($this->behaviors());
  6641. $this->afterConstruct();
  6642. }
  6643. public function init()
  6644. {
  6645. }
  6646. public function cache($duration, $dependency=null, $queryCount=1)
  6647. {
  6648. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  6649. return $this;
  6650. }
  6651. public function __sleep()
  6652. {
  6653. $this->_md=null;
  6654. return array_keys((array)$this);
  6655. }
  6656. public function __get($name)
  6657. {
  6658. if(isset($this->_attributes[$name]))
  6659. return $this->_attributes[$name];
  6660. else if(isset($this->getMetaData()->columns[$name]))
  6661. return null;
  6662. else if(isset($this->_related[$name]))
  6663. return $this->_related[$name];
  6664. else if(isset($this->getMetaData()->relations[$name]))
  6665. return $this->getRelated($name);
  6666. else
  6667. return parent::__get($name);
  6668. }
  6669. public function __set($name,$value)
  6670. {
  6671. if($this->setAttribute($name,$value)===false)
  6672. {
  6673. if(isset($this->getMetaData()->relations[$name]))
  6674. $this->_related[$name]=$value;
  6675. else
  6676. parent::__set($name,$value);
  6677. }
  6678. }
  6679. public function __isset($name)
  6680. {
  6681. if(isset($this->_attributes[$name]))
  6682. return true;
  6683. else if(isset($this->getMetaData()->columns[$name]))
  6684. return false;
  6685. else if(isset($this->_related[$name]))
  6686. return true;
  6687. else if(isset($this->getMetaData()->relations[$name]))
  6688. return $this->getRelated($name)!==null;
  6689. else
  6690. return parent::__isset($name);
  6691. }
  6692. public function __unset($name)
  6693. {
  6694. if(isset($this->getMetaData()->columns[$name]))
  6695. unset($this->_attributes[$name]);
  6696. else if(isset($this->getMetaData()->relations[$name]))
  6697. unset($this->_related[$name]);
  6698. else
  6699. parent::__unset($name);
  6700. }
  6701. public function __call($name,$parameters)
  6702. {
  6703. if(isset($this->getMetaData()->relations[$name]))
  6704. {
  6705. if(empty($parameters))
  6706. return $this->getRelated($name,false);
  6707. else
  6708. return $this->getRelated($name,false,$parameters[0]);
  6709. }
  6710. $scopes=$this->scopes();
  6711. if(isset($scopes[$name]))
  6712. {
  6713. $this->getDbCriteria()->mergeWith($scopes[$name]);
  6714. return $this;
  6715. }
  6716. return parent::__call($name,$parameters);
  6717. }
  6718. public function getRelated($name,$refresh=false,$params=array())
  6719. {
  6720. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  6721. return $this->_related[$name];
  6722. $md=$this->getMetaData();
  6723. if(!isset($md->relations[$name]))
  6724. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  6725. array('{class}'=>get_class($this), '{name}'=>$name)));
  6726. $relation=$md->relations[$name];
  6727. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  6728. return $relation instanceof CHasOneRelation ? null : array();
  6729. if($params!==array()) // dynamic query
  6730. {
  6731. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6732. if($exists)
  6733. $save=$this->_related[$name];
  6734. $r=array($name=>$params);
  6735. }
  6736. else
  6737. $r=$name;
  6738. unset($this->_related[$name]);
  6739. $finder=new CActiveFinder($this,$r);
  6740. $finder->lazyFind($this);
  6741. if(!isset($this->_related[$name]))
  6742. {
  6743. if($relation instanceof CHasManyRelation)
  6744. $this->_related[$name]=array();
  6745. else if($relation instanceof CStatRelation)
  6746. $this->_related[$name]=$relation->defaultValue;
  6747. else
  6748. $this->_related[$name]=null;
  6749. }
  6750. if($params!==array())
  6751. {
  6752. $results=$this->_related[$name];
  6753. if($exists)
  6754. $this->_related[$name]=$save;
  6755. else
  6756. unset($this->_related[$name]);
  6757. return $results;
  6758. }
  6759. else
  6760. return $this->_related[$name];
  6761. }
  6762. public function hasRelated($name)
  6763. {
  6764. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6765. }
  6766. public function getDbCriteria($createIfNull=true)
  6767. {
  6768. if($this->_c===null)
  6769. {
  6770. if(($c=$this->defaultScope())!==array() || $createIfNull)
  6771. $this->_c=new CDbCriteria($c);
  6772. }
  6773. return $this->_c;
  6774. }
  6775. public function setDbCriteria($criteria)
  6776. {
  6777. $this->_c=$criteria;
  6778. }
  6779. public function defaultScope()
  6780. {
  6781. return array();
  6782. }
  6783. public function resetScope()
  6784. {
  6785. $this->_c=new CDbCriteria();
  6786. return $this;
  6787. }
  6788. public static function model($className=__CLASS__)
  6789. {
  6790. if(isset(self::$_models[$className]))
  6791. return self::$_models[$className];
  6792. else
  6793. {
  6794. $model=self::$_models[$className]=new $className(null);
  6795. $model->_md=new CActiveRecordMetaData($model);
  6796. $model->attachBehaviors($model->behaviors());
  6797. return $model;
  6798. }
  6799. }
  6800. public function getMetaData()
  6801. {
  6802. if($this->_md!==null)
  6803. return $this->_md;
  6804. else
  6805. return $this->_md=self::model(get_class($this))->_md;
  6806. }
  6807. public function refreshMetaData()
  6808. {
  6809. $finder=self::model(get_class($this));
  6810. $finder->_md=new CActiveRecordMetaData($finder);
  6811. if($this!==$finder)
  6812. $this->_md=$finder->_md;
  6813. }
  6814. public function tableName()
  6815. {
  6816. return get_class($this);
  6817. }
  6818. public function primaryKey()
  6819. {
  6820. }
  6821. public function relations()
  6822. {
  6823. return array();
  6824. }
  6825. public function scopes()
  6826. {
  6827. return array();
  6828. }
  6829. public function attributeNames()
  6830. {
  6831. return array_keys($this->getMetaData()->columns);
  6832. }
  6833. public function getAttributeLabel($attribute)
  6834. {
  6835. $labels=$this->attributeLabels();
  6836. if(isset($labels[$attribute]))
  6837. return $labels[$attribute];
  6838. else if(strpos($attribute,'.')!==false)
  6839. {
  6840. $segs=explode('.',$attribute);
  6841. $name=array_pop($segs);
  6842. $model=$this;
  6843. foreach($segs as $seg)
  6844. {
  6845. $relations=$model->getMetaData()->relations;
  6846. if(isset($relations[$seg]))
  6847. $model=CActiveRecord::model($relations[$seg]->className);
  6848. else
  6849. break;
  6850. }
  6851. return $model->getAttributeLabel($name);
  6852. }
  6853. else
  6854. return $this->generateAttributeLabel($attribute);
  6855. }
  6856. public function getDbConnection()
  6857. {
  6858. if(self::$db!==null)
  6859. return self::$db;
  6860. else
  6861. {
  6862. self::$db=Yii::app()->getDb();
  6863. if(self::$db instanceof CDbConnection)
  6864. return self::$db;
  6865. else
  6866. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  6867. }
  6868. }
  6869. public function getActiveRelation($name)
  6870. {
  6871. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  6872. }
  6873. public function getTableSchema()
  6874. {
  6875. return $this->getMetaData()->tableSchema;
  6876. }
  6877. public function getCommandBuilder()
  6878. {
  6879. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  6880. }
  6881. public function hasAttribute($name)
  6882. {
  6883. return isset($this->getMetaData()->columns[$name]);
  6884. }
  6885. public function getAttribute($name)
  6886. {
  6887. if(property_exists($this,$name))
  6888. return $this->$name;
  6889. else if(isset($this->_attributes[$name]))
  6890. return $this->_attributes[$name];
  6891. }
  6892. public function setAttribute($name,$value)
  6893. {
  6894. if(property_exists($this,$name))
  6895. $this->$name=$value;
  6896. else if(isset($this->getMetaData()->columns[$name]))
  6897. $this->_attributes[$name]=$value;
  6898. else
  6899. return false;
  6900. return true;
  6901. }
  6902. public function addRelatedRecord($name,$record,$index)
  6903. {
  6904. if($index!==false)
  6905. {
  6906. if(!isset($this->_related[$name]))
  6907. $this->_related[$name]=array();
  6908. if($record instanceof CActiveRecord)
  6909. {
  6910. if($index===true)
  6911. $this->_related[$name][]=$record;
  6912. else
  6913. $this->_related[$name][$index]=$record;
  6914. }
  6915. }
  6916. else if(!isset($this->_related[$name]))
  6917. $this->_related[$name]=$record;
  6918. }
  6919. public function getAttributes($names=true)
  6920. {
  6921. $attributes=$this->_attributes;
  6922. foreach($this->getMetaData()->columns as $name=>$column)
  6923. {
  6924. if(property_exists($this,$name))
  6925. $attributes[$name]=$this->$name;
  6926. else if($names===true && !isset($attributes[$name]))
  6927. $attributes[$name]=null;
  6928. }
  6929. if(is_array($names))
  6930. {
  6931. $attrs=array();
  6932. foreach($names as $name)
  6933. {
  6934. if(property_exists($this,$name))
  6935. $attrs[$name]=$this->$name;
  6936. else
  6937. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  6938. }
  6939. return $attrs;
  6940. }
  6941. else
  6942. return $attributes;
  6943. }
  6944. public function save($runValidation=true,$attributes=null)
  6945. {
  6946. if(!$runValidation || $this->validate($attributes))
  6947. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  6948. else
  6949. return false;
  6950. }
  6951. public function getIsNewRecord()
  6952. {
  6953. return $this->_new;
  6954. }
  6955. public function setIsNewRecord($value)
  6956. {
  6957. $this->_new=$value;
  6958. }
  6959. public function onBeforeSave($event)
  6960. {
  6961. $this->raiseEvent('onBeforeSave',$event);
  6962. }
  6963. public function onAfterSave($event)
  6964. {
  6965. $this->raiseEvent('onAfterSave',$event);
  6966. }
  6967. public function onBeforeDelete($event)
  6968. {
  6969. $this->raiseEvent('onBeforeDelete',$event);
  6970. }
  6971. public function onAfterDelete($event)
  6972. {
  6973. $this->raiseEvent('onAfterDelete',$event);
  6974. }
  6975. public function onBeforeFind($event)
  6976. {
  6977. $this->raiseEvent('onBeforeFind',$event);
  6978. }
  6979. public function onAfterFind($event)
  6980. {
  6981. $this->raiseEvent('onAfterFind',$event);
  6982. }
  6983. protected function beforeSave()
  6984. {
  6985. if($this->hasEventHandler('onBeforeSave'))
  6986. {
  6987. $event=new CModelEvent($this);
  6988. $this->onBeforeSave($event);
  6989. return $event->isValid;
  6990. }
  6991. else
  6992. return true;
  6993. }
  6994. protected function afterSave()
  6995. {
  6996. if($this->hasEventHandler('onAfterSave'))
  6997. $this->onAfterSave(new CEvent($this));
  6998. }
  6999. protected function beforeDelete()
  7000. {
  7001. if($this->hasEventHandler('onBeforeDelete'))
  7002. {
  7003. $event=new CModelEvent($this);
  7004. $this->onBeforeDelete($event);
  7005. return $event->isValid;
  7006. }
  7007. else
  7008. return true;
  7009. }
  7010. protected function afterDelete()
  7011. {
  7012. if($this->hasEventHandler('onAfterDelete'))
  7013. $this->onAfterDelete(new CEvent($this));
  7014. }
  7015. protected function beforeFind()
  7016. {
  7017. if($this->hasEventHandler('onBeforeFind'))
  7018. {
  7019. $event=new CModelEvent($this);
  7020. // for backward compatibility
  7021. $event->criteria=func_num_args()>0 ? func_get_arg(0) : null;
  7022. $this->onBeforeFind($event);
  7023. }
  7024. }
  7025. protected function afterFind()
  7026. {
  7027. if($this->hasEventHandler('onAfterFind'))
  7028. $this->onAfterFind(new CEvent($this));
  7029. }
  7030. public function beforeFindInternal()
  7031. {
  7032. $this->beforeFind();
  7033. }
  7034. public function afterFindInternal()
  7035. {
  7036. $this->afterFind();
  7037. }
  7038. public function insert($attributes=null)
  7039. {
  7040. if(!$this->getIsNewRecord())
  7041. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  7042. if($this->beforeSave())
  7043. {
  7044. $builder=$this->getCommandBuilder();
  7045. $table=$this->getMetaData()->tableSchema;
  7046. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  7047. if($command->execute())
  7048. {
  7049. $primaryKey=$table->primaryKey;
  7050. if($table->sequenceName!==null)
  7051. {
  7052. if(is_string($primaryKey) && $this->$primaryKey===null)
  7053. $this->$primaryKey=$builder->getLastInsertID($table);
  7054. else if(is_array($primaryKey))
  7055. {
  7056. foreach($primaryKey as $pk)
  7057. {
  7058. if($this->$pk===null)
  7059. {
  7060. $this->$pk=$builder->getLastInsertID($table);
  7061. break;
  7062. }
  7063. }
  7064. }
  7065. }
  7066. $this->_pk=$this->getPrimaryKey();
  7067. $this->afterSave();
  7068. $this->setIsNewRecord(false);
  7069. $this->setScenario('update');
  7070. return true;
  7071. }
  7072. }
  7073. return false;
  7074. }
  7075. public function update($attributes=null)
  7076. {
  7077. if($this->getIsNewRecord())
  7078. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7079. if($this->beforeSave())
  7080. {
  7081. if($this->_pk===null)
  7082. $this->_pk=$this->getPrimaryKey();
  7083. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  7084. $this->_pk=$this->getPrimaryKey();
  7085. $this->afterSave();
  7086. return true;
  7087. }
  7088. else
  7089. return false;
  7090. }
  7091. public function saveAttributes($attributes)
  7092. {
  7093. if(!$this->getIsNewRecord())
  7094. {
  7095. $values=array();
  7096. foreach($attributes as $name=>$value)
  7097. {
  7098. if(is_integer($name))
  7099. $values[$value]=$this->$value;
  7100. else
  7101. $values[$name]=$this->$name=$value;
  7102. }
  7103. if($this->_pk===null)
  7104. $this->_pk=$this->getPrimaryKey();
  7105. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  7106. {
  7107. $this->_pk=$this->getPrimaryKey();
  7108. return true;
  7109. }
  7110. else
  7111. return false;
  7112. }
  7113. else
  7114. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7115. }
  7116. public function saveCounters($counters)
  7117. {
  7118. $builder=$this->getCommandBuilder();
  7119. $table=$this->getTableSchema();
  7120. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  7121. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7122. if($command->execute())
  7123. {
  7124. foreach($counters as $name=>$value)
  7125. $this->$name=$this->$name+$value;
  7126. return true;
  7127. }
  7128. else
  7129. return false;
  7130. }
  7131. public function delete()
  7132. {
  7133. if(!$this->getIsNewRecord())
  7134. {
  7135. if($this->beforeDelete())
  7136. {
  7137. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  7138. $this->afterDelete();
  7139. return $result;
  7140. }
  7141. else
  7142. return false;
  7143. }
  7144. else
  7145. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  7146. }
  7147. public function refresh()
  7148. {
  7149. if(!$this->getIsNewRecord() && ($record=$this->findByPk($this->getPrimaryKey()))!==null)
  7150. {
  7151. $this->_attributes=array();
  7152. $this->_related=array();
  7153. foreach($this->getMetaData()->columns as $name=>$column)
  7154. {
  7155. if(property_exists($this,$name))
  7156. $this->$name=$record->$name;
  7157. else
  7158. $this->_attributes[$name]=$record->$name;
  7159. }
  7160. return true;
  7161. }
  7162. else
  7163. return false;
  7164. }
  7165. public function equals($record)
  7166. {
  7167. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  7168. }
  7169. public function getPrimaryKey()
  7170. {
  7171. $table=$this->getMetaData()->tableSchema;
  7172. if(is_string($table->primaryKey))
  7173. return $this->{$table->primaryKey};
  7174. else if(is_array($table->primaryKey))
  7175. {
  7176. $values=array();
  7177. foreach($table->primaryKey as $name)
  7178. $values[$name]=$this->$name;
  7179. return $values;
  7180. }
  7181. else
  7182. return null;
  7183. }
  7184. public function setPrimaryKey($value)
  7185. {
  7186. $this->_pk=$this->getPrimaryKey();
  7187. $table=$this->getMetaData()->tableSchema;
  7188. if(is_string($table->primaryKey))
  7189. $this->{$table->primaryKey}=$value;
  7190. else if(is_array($table->primaryKey))
  7191. {
  7192. foreach($table->primaryKey as $name)
  7193. $this->$name=$value[$name];
  7194. }
  7195. }
  7196. public function getOldPrimaryKey()
  7197. {
  7198. return $this->_pk;
  7199. }
  7200. public function setOldPrimaryKey($value)
  7201. {
  7202. $this->_pk=$value;
  7203. }
  7204. protected function query($criteria,$all=false)
  7205. {
  7206. $this->beforeFind();
  7207. $this->applyScopes($criteria);
  7208. if(empty($criteria->with))
  7209. {
  7210. if(!$all)
  7211. $criteria->limit=1;
  7212. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  7213. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  7214. }
  7215. else
  7216. {
  7217. $finder=new CActiveFinder($this,$criteria->with);
  7218. return $finder->query($criteria,$all);
  7219. }
  7220. }
  7221. public function applyScopes(&$criteria)
  7222. {
  7223. if(!empty($criteria->scopes))
  7224. {
  7225. $scs=$this->scopes();
  7226. $c=$this->getDbCriteria();
  7227. foreach((array)$criteria->scopes as $k=>$v)
  7228. {
  7229. if(is_integer($k))
  7230. {
  7231. if(is_string($v))
  7232. {
  7233. if(isset($scs[$v]))
  7234. {
  7235. $c->mergeWith($scs[$v],true);
  7236. continue;
  7237. }
  7238. $scope=$v;
  7239. $params=array();
  7240. }
  7241. else if(is_array($v))
  7242. {
  7243. $scope=key($v);
  7244. $params=current($v);
  7245. }
  7246. }
  7247. else if(is_string($k))
  7248. {
  7249. $scope=$k;
  7250. $params=$v;
  7251. }
  7252. call_user_func_array(array($this,$scope),(array)$params);
  7253. }
  7254. }
  7255. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  7256. {
  7257. $c->mergeWith($criteria);
  7258. $criteria=$c;
  7259. $this->_c=null;
  7260. }
  7261. }
  7262. public function getTableAlias($quote=false, $checkScopes=true)
  7263. {
  7264. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  7265. $alias=$criteria->alias;
  7266. else
  7267. $alias=$this->_alias;
  7268. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  7269. }
  7270. public function setTableAlias($alias)
  7271. {
  7272. $this->_alias=$alias;
  7273. }
  7274. public function find($condition='',$params=array())
  7275. {
  7276. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7277. return $this->query($criteria);
  7278. }
  7279. public function findAll($condition='',$params=array())
  7280. {
  7281. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7282. return $this->query($criteria,true);
  7283. }
  7284. public function findByPk($pk,$condition='',$params=array())
  7285. {
  7286. $prefix=$this->getTableAlias(true).'.';
  7287. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7288. return $this->query($criteria);
  7289. }
  7290. public function findAllByPk($pk,$condition='',$params=array())
  7291. {
  7292. $prefix=$this->getTableAlias(true).'.';
  7293. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7294. return $this->query($criteria,true);
  7295. }
  7296. public function findByAttributes($attributes,$condition='',$params=array())
  7297. {
  7298. $prefix=$this->getTableAlias(true).'.';
  7299. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7300. return $this->query($criteria);
  7301. }
  7302. public function findAllByAttributes($attributes,$condition='',$params=array())
  7303. {
  7304. $prefix=$this->getTableAlias(true).'.';
  7305. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7306. return $this->query($criteria,true);
  7307. }
  7308. public function findBySql($sql,$params=array())
  7309. {
  7310. $this->beforeFind();
  7311. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7312. {
  7313. $this->_c=null;
  7314. $finder=new CActiveFinder($this,$criteria->with);
  7315. return $finder->findBySql($sql,$params);
  7316. }
  7317. else
  7318. {
  7319. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7320. return $this->populateRecord($command->queryRow());
  7321. }
  7322. }
  7323. public function findAllBySql($sql,$params=array())
  7324. {
  7325. $this->beforeFind();
  7326. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7327. {
  7328. $this->_c=null;
  7329. $finder=new CActiveFinder($this,$criteria->with);
  7330. return $finder->findAllBySql($sql,$params);
  7331. }
  7332. else
  7333. {
  7334. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7335. return $this->populateRecords($command->queryAll());
  7336. }
  7337. }
  7338. public function count($condition='',$params=array())
  7339. {
  7340. $builder=$this->getCommandBuilder();
  7341. $criteria=$builder->createCriteria($condition,$params);
  7342. $this->applyScopes($criteria);
  7343. if(empty($criteria->with))
  7344. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7345. else
  7346. {
  7347. $finder=new CActiveFinder($this,$criteria->with);
  7348. return $finder->count($criteria);
  7349. }
  7350. }
  7351. public function countByAttributes($attributes,$condition='',$params=array())
  7352. {
  7353. $prefix=$this->getTableAlias(true).'.';
  7354. $builder=$this->getCommandBuilder();
  7355. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7356. $this->applyScopes($criteria);
  7357. if(empty($criteria->with))
  7358. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7359. else
  7360. {
  7361. $finder=new CActiveFinder($this,$criteria->with);
  7362. return $finder->count($criteria);
  7363. }
  7364. }
  7365. public function countBySql($sql,$params=array())
  7366. {
  7367. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  7368. }
  7369. public function exists($condition='',$params=array())
  7370. {
  7371. $builder=$this->getCommandBuilder();
  7372. $criteria=$builder->createCriteria($condition,$params);
  7373. $table=$this->getTableSchema();
  7374. $criteria->select='1';
  7375. $criteria->limit=1;
  7376. $this->applyScopes($criteria);
  7377. if(empty($criteria->with))
  7378. return $builder->createFindCommand($table,$criteria)->queryRow()!==false;
  7379. else
  7380. {
  7381. $criteria->select='*';
  7382. $finder=new CActiveFinder($this,$criteria->with);
  7383. return $finder->count($criteria)>0;
  7384. }
  7385. }
  7386. public function with()
  7387. {
  7388. if(func_num_args()>0)
  7389. {
  7390. $with=func_get_args();
  7391. if(is_array($with[0])) // the parameter is given as an array
  7392. $with=$with[0];
  7393. if(!empty($with))
  7394. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  7395. }
  7396. return $this;
  7397. }
  7398. public function together()
  7399. {
  7400. $this->getDbCriteria()->together=true;
  7401. return $this;
  7402. }
  7403. public function updateByPk($pk,$attributes,$condition='',$params=array())
  7404. {
  7405. $builder=$this->getCommandBuilder();
  7406. $table=$this->getTableSchema();
  7407. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  7408. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  7409. return $command->execute();
  7410. }
  7411. public function updateAll($attributes,$condition='',$params=array())
  7412. {
  7413. $builder=$this->getCommandBuilder();
  7414. $criteria=$builder->createCriteria($condition,$params);
  7415. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  7416. return $command->execute();
  7417. }
  7418. public function updateCounters($counters,$condition='',$params=array())
  7419. {
  7420. $builder=$this->getCommandBuilder();
  7421. $criteria=$builder->createCriteria($condition,$params);
  7422. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7423. return $command->execute();
  7424. }
  7425. public function deleteByPk($pk,$condition='',$params=array())
  7426. {
  7427. $builder=$this->getCommandBuilder();
  7428. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  7429. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7430. return $command->execute();
  7431. }
  7432. public function deleteAll($condition='',$params=array())
  7433. {
  7434. $builder=$this->getCommandBuilder();
  7435. $criteria=$builder->createCriteria($condition,$params);
  7436. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7437. return $command->execute();
  7438. }
  7439. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  7440. {
  7441. $builder=$this->getCommandBuilder();
  7442. $table=$this->getTableSchema();
  7443. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  7444. $command=$builder->createDeleteCommand($table,$criteria);
  7445. return $command->execute();
  7446. }
  7447. public function populateRecord($attributes,$callAfterFind=true)
  7448. {
  7449. if($attributes!==false)
  7450. {
  7451. $record=$this->instantiate($attributes);
  7452. $record->setScenario('update');
  7453. $record->init();
  7454. $md=$record->getMetaData();
  7455. foreach($attributes as $name=>$value)
  7456. {
  7457. if(property_exists($record,$name))
  7458. $record->$name=$value;
  7459. else if(isset($md->columns[$name]))
  7460. $record->_attributes[$name]=$value;
  7461. }
  7462. $record->_pk=$record->getPrimaryKey();
  7463. $record->attachBehaviors($record->behaviors());
  7464. if($callAfterFind)
  7465. $record->afterFind();
  7466. return $record;
  7467. }
  7468. else
  7469. return null;
  7470. }
  7471. public function populateRecords($data,$callAfterFind=true,$index=null)
  7472. {
  7473. $records=array();
  7474. foreach($data as $attributes)
  7475. {
  7476. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  7477. {
  7478. if($index===null)
  7479. $records[]=$record;
  7480. else
  7481. $records[$record->$index]=$record;
  7482. }
  7483. }
  7484. return $records;
  7485. }
  7486. protected function instantiate($attributes)
  7487. {
  7488. $class=get_class($this);
  7489. $model=new $class(null);
  7490. return $model;
  7491. }
  7492. public function offsetExists($offset)
  7493. {
  7494. return $this->__isset($offset);
  7495. }
  7496. }
  7497. class CBaseActiveRelation extends CComponent
  7498. {
  7499. public $name;
  7500. public $className;
  7501. public $foreignKey;
  7502. public $select='*';
  7503. public $condition='';
  7504. public $params=array();
  7505. public $group='';
  7506. public $join='';
  7507. public $having='';
  7508. public $order='';
  7509. public function __construct($name,$className,$foreignKey,$options=array())
  7510. {
  7511. $this->name=$name;
  7512. $this->className=$className;
  7513. $this->foreignKey=$foreignKey;
  7514. foreach($options as $name=>$value)
  7515. $this->$name=$value;
  7516. }
  7517. public function mergeWith($criteria,$fromScope=false)
  7518. {
  7519. if($criteria instanceof CDbCriteria)
  7520. $criteria=$criteria->toArray();
  7521. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  7522. {
  7523. if($this->select==='*')
  7524. $this->select=$criteria['select'];
  7525. else if($criteria['select']!=='*')
  7526. {
  7527. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  7528. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  7529. $this->select=array_merge($select1,array_diff($select2,$select1));
  7530. }
  7531. }
  7532. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  7533. {
  7534. if($this->condition==='')
  7535. $this->condition=$criteria['condition'];
  7536. else if($criteria['condition']!=='')
  7537. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  7538. }
  7539. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  7540. $this->params=array_merge($this->params,$criteria['params']);
  7541. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  7542. {
  7543. if($this->order==='')
  7544. $this->order=$criteria['order'];
  7545. else if($criteria['order']!=='')
  7546. $this->order=$criteria['order'].', '.$this->order;
  7547. }
  7548. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  7549. {
  7550. if($this->group==='')
  7551. $this->group=$criteria['group'];
  7552. else if($criteria['group']!=='')
  7553. $this->group.=', '.$criteria['group'];
  7554. }
  7555. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  7556. {
  7557. if($this->join==='')
  7558. $this->join=$criteria['join'];
  7559. else if($criteria['join']!=='')
  7560. $this->join.=' '.$criteria['join'];
  7561. }
  7562. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  7563. {
  7564. if($this->having==='')
  7565. $this->having=$criteria['having'];
  7566. else if($criteria['having']!=='')
  7567. $this->having="({$this->having}) AND ({$criteria['having']})";
  7568. }
  7569. }
  7570. }
  7571. class CStatRelation extends CBaseActiveRelation
  7572. {
  7573. public $select='COUNT(*)';
  7574. public $defaultValue=0;
  7575. public function mergeWith($criteria,$fromScope=false)
  7576. {
  7577. if($criteria instanceof CDbCriteria)
  7578. $criteria=$criteria->toArray();
  7579. parent::mergeWith($criteria,$fromScope);
  7580. if(isset($criteria['defaultValue']))
  7581. $this->defaultValue=$criteria['defaultValue'];
  7582. }
  7583. }
  7584. class CActiveRelation extends CBaseActiveRelation
  7585. {
  7586. public $joinType='LEFT OUTER JOIN';
  7587. public $on='';
  7588. public $alias;
  7589. public $with=array();
  7590. public $together;
  7591. public $scopes;
  7592. public function mergeWith($criteria,$fromScope=false)
  7593. {
  7594. if($criteria instanceof CDbCriteria)
  7595. $criteria=$criteria->toArray();
  7596. if($fromScope)
  7597. {
  7598. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  7599. {
  7600. if($this->on==='')
  7601. $this->on=$criteria['condition'];
  7602. else if($criteria['condition']!=='')
  7603. $this->on="({$this->on}) AND ({$criteria['condition']})";
  7604. }
  7605. unset($criteria['condition']);
  7606. }
  7607. parent::mergeWith($criteria);
  7608. if(isset($criteria['joinType']))
  7609. $this->joinType=$criteria['joinType'];
  7610. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  7611. {
  7612. if($this->on==='')
  7613. $this->on=$criteria['on'];
  7614. else if($criteria['on']!=='')
  7615. $this->on="({$this->on}) AND ({$criteria['on']})";
  7616. }
  7617. if(isset($criteria['with']))
  7618. $this->with=$criteria['with'];
  7619. if(isset($criteria['alias']))
  7620. $this->alias=$criteria['alias'];
  7621. if(isset($criteria['together']))
  7622. $this->together=$criteria['together'];
  7623. }
  7624. }
  7625. class CBelongsToRelation extends CActiveRelation
  7626. {
  7627. }
  7628. class CHasOneRelation extends CActiveRelation
  7629. {
  7630. public $through;
  7631. }
  7632. class CHasManyRelation extends CActiveRelation
  7633. {
  7634. public $limit=-1;
  7635. public $offset=-1;
  7636. public $index;
  7637. public $through;
  7638. public function mergeWith($criteria,$fromScope=false)
  7639. {
  7640. if($criteria instanceof CDbCriteria)
  7641. $criteria=$criteria->toArray();
  7642. parent::mergeWith($criteria,$fromScope);
  7643. if(isset($criteria['limit']) && $criteria['limit']>0)
  7644. $this->limit=$criteria['limit'];
  7645. if(isset($criteria['offset']) && $criteria['offset']>=0)
  7646. $this->offset=$criteria['offset'];
  7647. if(isset($criteria['index']))
  7648. $this->index=$criteria['index'];
  7649. }
  7650. }
  7651. class CManyManyRelation extends CHasManyRelation
  7652. {
  7653. }
  7654. class CActiveRecordMetaData
  7655. {
  7656. public $tableSchema;
  7657. public $columns;
  7658. public $relations=array();
  7659. public $attributeDefaults=array();
  7660. private $_model;
  7661. public function __construct($model)
  7662. {
  7663. $this->_model=$model;
  7664. $tableName=$model->tableName();
  7665. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  7666. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  7667. array('{class}'=>get_class($model),'{table}'=>$tableName)));
  7668. if($table->primaryKey===null)
  7669. {
  7670. $table->primaryKey=$model->primaryKey();
  7671. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  7672. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  7673. else if(is_array($table->primaryKey))
  7674. {
  7675. foreach($table->primaryKey as $name)
  7676. {
  7677. if(isset($table->columns[$name]))
  7678. $table->columns[$name]->isPrimaryKey=true;
  7679. }
  7680. }
  7681. }
  7682. $this->tableSchema=$table;
  7683. $this->columns=$table->columns;
  7684. foreach($table->columns as $name=>$column)
  7685. {
  7686. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  7687. $this->attributeDefaults[$name]=$column->defaultValue;
  7688. }
  7689. foreach($model->relations() as $name=>$config)
  7690. {
  7691. $this->addRelation($name,$config);
  7692. }
  7693. }
  7694. public function addRelation($name,$config)
  7695. {
  7696. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  7697. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  7698. else
  7699. 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)));
  7700. }
  7701. public function hasRelation($name)
  7702. {
  7703. return isset($this->relations[$name]);
  7704. }
  7705. public function removeRelation($name)
  7706. {
  7707. unset($this->relations[$name]);
  7708. }
  7709. }
  7710. class CDbConnection extends CApplicationComponent
  7711. {
  7712. public $connectionString;
  7713. public $username='';
  7714. public $password='';
  7715. public $schemaCachingDuration=0;
  7716. public $schemaCachingExclude=array();
  7717. public $schemaCacheID='cache';
  7718. public $queryCachingDuration=0;
  7719. public $queryCachingDependency;
  7720. public $queryCachingCount=0;
  7721. public $queryCacheID='cache';
  7722. public $autoConnect=true;
  7723. public $charset;
  7724. public $emulatePrepare;
  7725. public $enableParamLogging=false;
  7726. public $enableProfiling=false;
  7727. public $tablePrefix;
  7728. public $initSQLs;
  7729. public $driverMap=array(
  7730. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  7731. 'mysqli'=>'CMysqlSchema', // MySQL
  7732. 'mysql'=>'CMysqlSchema', // MySQL
  7733. 'sqlite'=>'CSqliteSchema', // sqlite 3
  7734. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  7735. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  7736. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  7737. 'sqlsrv'=>'CMssqlSchema', // Mssql
  7738. 'oci'=>'COciSchema', // Oracle driver
  7739. );
  7740. public $pdoClass = 'PDO';
  7741. private $_attributes=array();
  7742. private $_active=false;
  7743. private $_pdo;
  7744. private $_transaction;
  7745. private $_schema;
  7746. public function __construct($dsn='',$username='',$password='')
  7747. {
  7748. $this->connectionString=$dsn;
  7749. $this->username=$username;
  7750. $this->password=$password;
  7751. }
  7752. public function __sleep()
  7753. {
  7754. $this->close();
  7755. return array_keys(get_object_vars($this));
  7756. }
  7757. public static function getAvailableDrivers()
  7758. {
  7759. return PDO::getAvailableDrivers();
  7760. }
  7761. public function init()
  7762. {
  7763. parent::init();
  7764. if($this->autoConnect)
  7765. $this->setActive(true);
  7766. }
  7767. public function getActive()
  7768. {
  7769. return $this->_active;
  7770. }
  7771. public function setActive($value)
  7772. {
  7773. if($value!=$this->_active)
  7774. {
  7775. if($value)
  7776. $this->open();
  7777. else
  7778. $this->close();
  7779. }
  7780. }
  7781. public function cache($duration, $dependency=null, $queryCount=1)
  7782. {
  7783. $this->queryCachingDuration=$duration;
  7784. $this->queryCachingDependency=$dependency;
  7785. $this->queryCachingCount=$queryCount;
  7786. return $this;
  7787. }
  7788. protected function open()
  7789. {
  7790. if($this->_pdo===null)
  7791. {
  7792. if(empty($this->connectionString))
  7793. throw new CDbException(Yii::t('yii','CDbConnection.connectionString cannot be empty.'));
  7794. try
  7795. {
  7796. $this->_pdo=$this->createPdoInstance();
  7797. $this->initConnection($this->_pdo);
  7798. $this->_active=true;
  7799. }
  7800. catch(PDOException $e)
  7801. {
  7802. if(YII_DEBUG)
  7803. {
  7804. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection: {error}',
  7805. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$e->errorInfo);
  7806. }
  7807. else
  7808. {
  7809. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  7810. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'),(int)$e->getCode(),$e->errorInfo);
  7811. }
  7812. }
  7813. }
  7814. }
  7815. protected function close()
  7816. {
  7817. $this->_pdo=null;
  7818. $this->_active=false;
  7819. $this->_schema=null;
  7820. }
  7821. protected function createPdoInstance()
  7822. {
  7823. $pdoClass=$this->pdoClass;
  7824. if(($pos=strpos($this->connectionString,':'))!==false)
  7825. {
  7826. $driver=strtolower(substr($this->connectionString,0,$pos));
  7827. if($driver==='mssql' || $driver==='dblib' || $driver==='sqlsrv')
  7828. $pdoClass='CMssqlPdoAdapter';
  7829. }
  7830. return new $pdoClass($this->connectionString,$this->username,
  7831. $this->password,$this->_attributes);
  7832. }
  7833. protected function initConnection($pdo)
  7834. {
  7835. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  7836. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  7837. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  7838. if($this->charset!==null)
  7839. {
  7840. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  7841. if(in_array($driver,array('pgsql','mysql','mysqli')))
  7842. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  7843. }
  7844. if($this->initSQLs!==null)
  7845. {
  7846. foreach($this->initSQLs as $sql)
  7847. $pdo->exec($sql);
  7848. }
  7849. }
  7850. public function getPdoInstance()
  7851. {
  7852. return $this->_pdo;
  7853. }
  7854. public function createCommand($query=null)
  7855. {
  7856. $this->setActive(true);
  7857. return new CDbCommand($this,$query);
  7858. }
  7859. public function getCurrentTransaction()
  7860. {
  7861. if($this->_transaction!==null)
  7862. {
  7863. if($this->_transaction->getActive())
  7864. return $this->_transaction;
  7865. }
  7866. return null;
  7867. }
  7868. public function beginTransaction()
  7869. {
  7870. $this->setActive(true);
  7871. $this->_pdo->beginTransaction();
  7872. return $this->_transaction=new CDbTransaction($this);
  7873. }
  7874. public function getSchema()
  7875. {
  7876. if($this->_schema!==null)
  7877. return $this->_schema;
  7878. else
  7879. {
  7880. $driver=$this->getDriverName();
  7881. if(isset($this->driverMap[$driver]))
  7882. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  7883. else
  7884. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  7885. array('{driver}'=>$driver)));
  7886. }
  7887. }
  7888. public function getCommandBuilder()
  7889. {
  7890. return $this->getSchema()->getCommandBuilder();
  7891. }
  7892. public function getLastInsertID($sequenceName='')
  7893. {
  7894. $this->setActive(true);
  7895. return $this->_pdo->lastInsertId($sequenceName);
  7896. }
  7897. public function quoteValue($str)
  7898. {
  7899. if(is_int($str) || is_float($str))
  7900. return $str;
  7901. $this->setActive(true);
  7902. if(($value=$this->_pdo->quote($str))!==false)
  7903. return $value;
  7904. else // the driver doesn't support quote (e.g. oci)
  7905. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  7906. }
  7907. public function quoteTableName($name)
  7908. {
  7909. return $this->getSchema()->quoteTableName($name);
  7910. }
  7911. public function quoteColumnName($name)
  7912. {
  7913. return $this->getSchema()->quoteColumnName($name);
  7914. }
  7915. public function getPdoType($type)
  7916. {
  7917. static $map=array
  7918. (
  7919. 'boolean'=>PDO::PARAM_BOOL,
  7920. 'integer'=>PDO::PARAM_INT,
  7921. 'string'=>PDO::PARAM_STR,
  7922. 'NULL'=>PDO::PARAM_NULL,
  7923. );
  7924. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  7925. }
  7926. public function getColumnCase()
  7927. {
  7928. return $this->getAttribute(PDO::ATTR_CASE);
  7929. }
  7930. public function setColumnCase($value)
  7931. {
  7932. $this->setAttribute(PDO::ATTR_CASE,$value);
  7933. }
  7934. public function getNullConversion()
  7935. {
  7936. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  7937. }
  7938. public function setNullConversion($value)
  7939. {
  7940. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  7941. }
  7942. public function getAutoCommit()
  7943. {
  7944. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  7945. }
  7946. public function setAutoCommit($value)
  7947. {
  7948. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  7949. }
  7950. public function getPersistent()
  7951. {
  7952. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  7953. }
  7954. public function setPersistent($value)
  7955. {
  7956. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  7957. }
  7958. public function getDriverName()
  7959. {
  7960. if(($pos=strpos($this->connectionString, ':'))!==false)
  7961. return strtolower(substr($this->connectionString, 0, $pos));
  7962. // return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  7963. }
  7964. public function getClientVersion()
  7965. {
  7966. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  7967. }
  7968. public function getConnectionStatus()
  7969. {
  7970. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  7971. }
  7972. public function getPrefetch()
  7973. {
  7974. return $this->getAttribute(PDO::ATTR_PREFETCH);
  7975. }
  7976. public function getServerInfo()
  7977. {
  7978. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  7979. }
  7980. public function getServerVersion()
  7981. {
  7982. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  7983. }
  7984. public function getTimeout()
  7985. {
  7986. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  7987. }
  7988. public function getAttribute($name)
  7989. {
  7990. $this->setActive(true);
  7991. return $this->_pdo->getAttribute($name);
  7992. }
  7993. public function setAttribute($name,$value)
  7994. {
  7995. if($this->_pdo instanceof PDO)
  7996. $this->_pdo->setAttribute($name,$value);
  7997. else
  7998. $this->_attributes[$name]=$value;
  7999. }
  8000. public function getAttributes()
  8001. {
  8002. return $this->_attributes;
  8003. }
  8004. public function setAttributes($values)
  8005. {
  8006. foreach($values as $name=>$value)
  8007. $this->_attributes[$name]=$value;
  8008. }
  8009. public function getStats()
  8010. {
  8011. $logger=Yii::getLogger();
  8012. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  8013. $count=count($timings);
  8014. $time=array_sum($timings);
  8015. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  8016. $count+=count($timings);
  8017. $time+=array_sum($timings);
  8018. return array($count,$time);
  8019. }
  8020. }
  8021. abstract class CDbSchema extends CComponent
  8022. {
  8023. public $columnTypes=array();
  8024. private $_tableNames=array();
  8025. private $_tables=array();
  8026. private $_connection;
  8027. private $_builder;
  8028. private $_cacheExclude=array();
  8029. abstract protected function loadTable($name);
  8030. public function __construct($conn)
  8031. {
  8032. $this->_connection=$conn;
  8033. foreach($conn->schemaCachingExclude as $name)
  8034. $this->_cacheExclude[$name]=true;
  8035. }
  8036. public function getDbConnection()
  8037. {
  8038. return $this->_connection;
  8039. }
  8040. public function getTable($name,$refresh=false)
  8041. {
  8042. if($refresh===false && isset($this->_tables[$name]))
  8043. return $this->_tables[$name];
  8044. else
  8045. {
  8046. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  8047. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  8048. else
  8049. $realName=$name;
  8050. // temporarily disable query caching
  8051. if($this->_connection->queryCachingDuration>0)
  8052. {
  8053. $qcDuration=$this->_connection->queryCachingDuration;
  8054. $this->_connection->queryCachingDuration=0;
  8055. }
  8056. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8057. {
  8058. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8059. $table=$cache->get($key);
  8060. if($refresh===true || $table===false)
  8061. {
  8062. $table=$this->loadTable($realName);
  8063. if($table!==null)
  8064. $cache->set($key,$table,$duration);
  8065. }
  8066. $this->_tables[$name]=$table;
  8067. }
  8068. else
  8069. $this->_tables[$name]=$table=$this->loadTable($realName);
  8070. if(isset($qcDuration)) // re-enable query caching
  8071. $this->_connection->queryCachingDuration=$qcDuration;
  8072. return $table;
  8073. }
  8074. }
  8075. public function getTables($schema='')
  8076. {
  8077. $tables=array();
  8078. foreach($this->getTableNames($schema) as $name)
  8079. {
  8080. if(($table=$this->getTable($name))!==null)
  8081. $tables[$name]=$table;
  8082. }
  8083. return $tables;
  8084. }
  8085. public function getTableNames($schema='')
  8086. {
  8087. if(!isset($this->_tableNames[$schema]))
  8088. $this->_tableNames[$schema]=$this->findTableNames($schema);
  8089. return $this->_tableNames[$schema];
  8090. }
  8091. public function getCommandBuilder()
  8092. {
  8093. if($this->_builder!==null)
  8094. return $this->_builder;
  8095. else
  8096. return $this->_builder=$this->createCommandBuilder();
  8097. }
  8098. public function refresh()
  8099. {
  8100. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8101. {
  8102. foreach(array_keys($this->_tables) as $name)
  8103. {
  8104. if(!isset($this->_cacheExclude[$name]))
  8105. {
  8106. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8107. $cache->delete($key);
  8108. }
  8109. }
  8110. }
  8111. $this->_tables=array();
  8112. $this->_tableNames=array();
  8113. $this->_builder=null;
  8114. }
  8115. public function quoteTableName($name)
  8116. {
  8117. if(strpos($name,'.')===false)
  8118. return $this->quoteSimpleTableName($name);
  8119. $parts=explode('.',$name);
  8120. foreach($parts as $i=>$part)
  8121. $parts[$i]=$this->quoteSimpleTableName($part);
  8122. return implode('.',$parts);
  8123. }
  8124. public function quoteSimpleTableName($name)
  8125. {
  8126. return "'".$name."'";
  8127. }
  8128. public function quoteColumnName($name)
  8129. {
  8130. if(($pos=strrpos($name,'.'))!==false)
  8131. {
  8132. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  8133. $name=substr($name,$pos+1);
  8134. }
  8135. else
  8136. $prefix='';
  8137. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  8138. }
  8139. public function quoteSimpleColumnName($name)
  8140. {
  8141. return '"'.$name.'"';
  8142. }
  8143. public function compareTableNames($name1,$name2)
  8144. {
  8145. $name1=str_replace(array('"','`',"'"),'',$name1);
  8146. $name2=str_replace(array('"','`',"'"),'',$name2);
  8147. if(($pos=strrpos($name1,'.'))!==false)
  8148. $name1=substr($name1,$pos+1);
  8149. if(($pos=strrpos($name2,'.'))!==false)
  8150. $name2=substr($name2,$pos+1);
  8151. if($this->_connection->tablePrefix!==null)
  8152. {
  8153. if(strpos($name1,'{')!==false)
  8154. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  8155. if(strpos($name2,'{')!==false)
  8156. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  8157. }
  8158. return $name1===$name2;
  8159. }
  8160. public function resetSequence($table,$value=null)
  8161. {
  8162. }
  8163. public function checkIntegrity($check=true,$schema='')
  8164. {
  8165. }
  8166. protected function createCommandBuilder()
  8167. {
  8168. return new CDbCommandBuilder($this);
  8169. }
  8170. protected function findTableNames($schema='')
  8171. {
  8172. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  8173. array('{class}'=>get_class($this))));
  8174. }
  8175. public function getColumnType($type)
  8176. {
  8177. if(isset($this->columnTypes[$type]))
  8178. return $this->columnTypes[$type];
  8179. else if(($pos=strpos($type,' '))!==false)
  8180. {
  8181. $t=substr($type,0,$pos);
  8182. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  8183. }
  8184. else
  8185. return $type;
  8186. }
  8187. public function createTable($table, $columns, $options=null)
  8188. {
  8189. $cols=array();
  8190. foreach($columns as $name=>$type)
  8191. {
  8192. if(is_string($name))
  8193. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  8194. else
  8195. $cols[]="\t".$type;
  8196. }
  8197. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  8198. return $options===null ? $sql : $sql.' '.$options;
  8199. }
  8200. public function renameTable($table, $newName)
  8201. {
  8202. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  8203. }
  8204. public function dropTable($table)
  8205. {
  8206. return "DROP TABLE ".$this->quoteTableName($table);
  8207. }
  8208. public function truncateTable($table)
  8209. {
  8210. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  8211. }
  8212. public function addColumn($table, $column, $type)
  8213. {
  8214. return 'ALTER TABLE ' . $this->quoteTableName($table)
  8215. . ' ADD ' . $this->quoteColumnName($column) . ' '
  8216. . $this->getColumnType($type);
  8217. }
  8218. public function dropColumn($table, $column)
  8219. {
  8220. return "ALTER TABLE ".$this->quoteTableName($table)
  8221. ." DROP COLUMN ".$this->quoteColumnName($column);
  8222. }
  8223. public function renameColumn($table, $name, $newName)
  8224. {
  8225. return "ALTER TABLE ".$this->quoteTableName($table)
  8226. . " RENAME COLUMN ".$this->quoteColumnName($name)
  8227. . " TO ".$this->quoteColumnName($newName);
  8228. }
  8229. public function alterColumn($table, $column, $type)
  8230. {
  8231. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  8232. . $this->quoteColumnName($column) . ' '
  8233. . $this->quoteColumnName($column) . ' '
  8234. . $this->getColumnType($type);
  8235. }
  8236. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8237. {
  8238. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  8239. foreach($columns as $i=>$col)
  8240. $columns[$i]=$this->quoteColumnName($col);
  8241. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  8242. foreach($refColumns as $i=>$col)
  8243. $refColumns[$i]=$this->quoteColumnName($col);
  8244. $sql='ALTER TABLE '.$this->quoteTableName($table)
  8245. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  8246. .' FOREIGN KEY ('.implode(', ', $columns).')'
  8247. .' REFERENCES '.$this->quoteTableName($refTable)
  8248. .' ('.implode(', ', $refColumns).')';
  8249. if($delete!==null)
  8250. $sql.=' ON DELETE '.$delete;
  8251. if($update!==null)
  8252. $sql.=' ON UPDATE '.$update;
  8253. return $sql;
  8254. }
  8255. public function dropForeignKey($name, $table)
  8256. {
  8257. return 'ALTER TABLE '.$this->quoteTableName($table)
  8258. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  8259. }
  8260. public function createIndex($name, $table, $column, $unique=false)
  8261. {
  8262. $cols=array();
  8263. $columns=preg_split('/\s*,\s*/',$column,-1,PREG_SPLIT_NO_EMPTY);
  8264. foreach($columns as $col)
  8265. {
  8266. if(strpos($col,'(')!==false)
  8267. $cols[]=$col;
  8268. else
  8269. $cols[]=$this->quoteColumnName($col);
  8270. }
  8271. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  8272. . $this->quoteTableName($name).' ON '
  8273. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  8274. }
  8275. public function dropIndex($name, $table)
  8276. {
  8277. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  8278. }
  8279. }
  8280. class CSqliteSchema extends CDbSchema
  8281. {
  8282. public $columnTypes=array(
  8283. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  8284. 'string' => 'varchar(255)',
  8285. 'text' => 'text',
  8286. 'integer' => 'integer',
  8287. 'float' => 'float',
  8288. 'decimal' => 'decimal',
  8289. 'datetime' => 'datetime',
  8290. 'timestamp' => 'timestamp',
  8291. 'time' => 'time',
  8292. 'date' => 'date',
  8293. 'binary' => 'blob',
  8294. 'boolean' => 'tinyint(1)',
  8295. 'money' => 'decimal(19,4)',
  8296. );
  8297. public function resetSequence($table,$value=null)
  8298. {
  8299. if($table->sequenceName!==null)
  8300. {
  8301. if($value===null)
  8302. $value=$this->getDbConnection()->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")->queryScalar();
  8303. else
  8304. $value=(int)$value-1;
  8305. try
  8306. {
  8307. // it's possible sqlite_sequence does not exist
  8308. $this->getDbConnection()->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")->execute();
  8309. }
  8310. catch(Exception $e)
  8311. {
  8312. }
  8313. }
  8314. }
  8315. public function checkIntegrity($check=true,$schema='')
  8316. {
  8317. // SQLite doesn't enforce integrity
  8318. return;
  8319. }
  8320. protected function findTableNames($schema='')
  8321. {
  8322. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  8323. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  8324. }
  8325. protected function createCommandBuilder()
  8326. {
  8327. return new CSqliteCommandBuilder($this);
  8328. }
  8329. protected function loadTable($name)
  8330. {
  8331. $table=new CDbTableSchema;
  8332. $table->name=$name;
  8333. $table->rawName=$this->quoteTableName($name);
  8334. if($this->findColumns($table))
  8335. {
  8336. $this->findConstraints($table);
  8337. return $table;
  8338. }
  8339. else
  8340. return null;
  8341. }
  8342. protected function findColumns($table)
  8343. {
  8344. $sql="PRAGMA table_info({$table->rawName})";
  8345. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  8346. if(empty($columns))
  8347. return false;
  8348. foreach($columns as $column)
  8349. {
  8350. $c=$this->createColumn($column);
  8351. $table->columns[$c->name]=$c;
  8352. if($c->isPrimaryKey)
  8353. {
  8354. if($table->primaryKey===null)
  8355. $table->primaryKey=$c->name;
  8356. else if(is_string($table->primaryKey))
  8357. $table->primaryKey=array($table->primaryKey,$c->name);
  8358. else
  8359. $table->primaryKey[]=$c->name;
  8360. }
  8361. }
  8362. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  8363. {
  8364. $table->sequenceName='';
  8365. $table->columns[$table->primaryKey]->autoIncrement=true;
  8366. }
  8367. return true;
  8368. }
  8369. protected function findConstraints($table)
  8370. {
  8371. $foreignKeys=array();
  8372. $sql="PRAGMA foreign_key_list({$table->rawName})";
  8373. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  8374. foreach($keys as $key)
  8375. {
  8376. $column=$table->columns[$key['from']];
  8377. $column->isForeignKey=true;
  8378. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  8379. }
  8380. $table->foreignKeys=$foreignKeys;
  8381. }
  8382. protected function createColumn($column)
  8383. {
  8384. $c=new CSqliteColumnSchema;
  8385. $c->name=$column['name'];
  8386. $c->rawName=$this->quoteColumnName($c->name);
  8387. $c->allowNull=!$column['notnull'];
  8388. $c->isPrimaryKey=$column['pk']!=0;
  8389. $c->isForeignKey=false;
  8390. $c->init(strtolower($column['type']),$column['dflt_value']);
  8391. return $c;
  8392. }
  8393. public function truncateTable($table)
  8394. {
  8395. return "DELETE FROM ".$this->quoteTableName($table);
  8396. }
  8397. public function dropColumn($table, $column)
  8398. {
  8399. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  8400. }
  8401. public function renameColumn($table, $name, $newName)
  8402. {
  8403. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  8404. }
  8405. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8406. {
  8407. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  8408. }
  8409. public function dropForeignKey($name, $table)
  8410. {
  8411. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  8412. }
  8413. public function alterColumn($table, $column, $type)
  8414. {
  8415. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  8416. }
  8417. public function dropIndex($name, $table)
  8418. {
  8419. return 'DROP INDEX '.$this->quoteTableName($name);
  8420. }
  8421. }
  8422. class CDbTableSchema extends CComponent
  8423. {
  8424. public $name;
  8425. public $rawName;
  8426. public $primaryKey;
  8427. public $sequenceName;
  8428. public $foreignKeys=array();
  8429. public $columns=array();
  8430. public function getColumn($name)
  8431. {
  8432. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  8433. }
  8434. public function getColumnNames()
  8435. {
  8436. return array_keys($this->columns);
  8437. }
  8438. }
  8439. class CDbCommand extends CComponent
  8440. {
  8441. public $params=array();
  8442. private $_connection;
  8443. private $_text;
  8444. private $_statement;
  8445. private $_paramLog=array();
  8446. private $_query;
  8447. private $_fetchMode = array(PDO::FETCH_ASSOC);
  8448. public function __construct(CDbConnection $connection,$query=null)
  8449. {
  8450. $this->_connection=$connection;
  8451. if(is_array($query))
  8452. {
  8453. foreach($query as $name=>$value)
  8454. $this->$name=$value;
  8455. }
  8456. else
  8457. $this->setText($query);
  8458. }
  8459. public function __sleep()
  8460. {
  8461. $this->_statement=null;
  8462. return array_keys(get_object_vars($this));
  8463. }
  8464. public function setFetchMode($mode)
  8465. {
  8466. $params=func_get_args();
  8467. $this->_fetchMode = $params;
  8468. return $this;
  8469. }
  8470. public function reset()
  8471. {
  8472. $this->_text=null;
  8473. $this->_query=null;
  8474. $this->_statement=null;
  8475. $this->_paramLog=array();
  8476. $this->params=array();
  8477. return $this;
  8478. }
  8479. public function getText()
  8480. {
  8481. if($this->_text=='' && !empty($this->_query))
  8482. $this->setText($this->buildQuery($this->_query));
  8483. return $this->_text;
  8484. }
  8485. public function setText($value)
  8486. {
  8487. if($this->_connection->tablePrefix!==null && $value!='')
  8488. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  8489. else
  8490. $this->_text=$value;
  8491. $this->cancel();
  8492. return $this;
  8493. }
  8494. public function getConnection()
  8495. {
  8496. return $this->_connection;
  8497. }
  8498. public function getPdoStatement()
  8499. {
  8500. return $this->_statement;
  8501. }
  8502. public function prepare()
  8503. {
  8504. if($this->_statement==null)
  8505. {
  8506. try
  8507. {
  8508. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  8509. $this->_paramLog=array();
  8510. }
  8511. catch(Exception $e)
  8512. {
  8513. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8514. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8515. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  8516. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  8517. }
  8518. }
  8519. }
  8520. public function cancel()
  8521. {
  8522. $this->_statement=null;
  8523. }
  8524. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  8525. {
  8526. $this->prepare();
  8527. if($dataType===null)
  8528. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  8529. else if($length===null)
  8530. $this->_statement->bindParam($name,$value,$dataType);
  8531. else if($driverOptions===null)
  8532. $this->_statement->bindParam($name,$value,$dataType,$length);
  8533. else
  8534. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  8535. $this->_paramLog[$name]=&$value;
  8536. return $this;
  8537. }
  8538. public function bindValue($name, $value, $dataType=null)
  8539. {
  8540. $this->prepare();
  8541. if($dataType===null)
  8542. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8543. else
  8544. $this->_statement->bindValue($name,$value,$dataType);
  8545. $this->_paramLog[$name]=$value;
  8546. return $this;
  8547. }
  8548. public function bindValues($values)
  8549. {
  8550. $this->prepare();
  8551. foreach($values as $name=>$value)
  8552. {
  8553. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8554. $this->_paramLog[$name]=$value;
  8555. }
  8556. return $this;
  8557. }
  8558. public function execute($params=array())
  8559. {
  8560. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8561. {
  8562. $p=array();
  8563. foreach($pars as $name=>$value)
  8564. $p[$name]=$name.'='.var_export($value,true);
  8565. $par='. Bound with ' .implode(', ',$p);
  8566. }
  8567. else
  8568. $par='';
  8569. try
  8570. {
  8571. if($this->_connection->enableProfiling)
  8572. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8573. $this->prepare();
  8574. if($params===array())
  8575. $this->_statement->execute();
  8576. else
  8577. $this->_statement->execute($params);
  8578. $n=$this->_statement->rowCount();
  8579. if($this->_connection->enableProfiling)
  8580. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8581. return $n;
  8582. }
  8583. catch(Exception $e)
  8584. {
  8585. if($this->_connection->enableProfiling)
  8586. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8587. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8588. $message = $e->getMessage();
  8589. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  8590. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8591. if(YII_DEBUG)
  8592. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  8593. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8594. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8595. }
  8596. }
  8597. public function query($params=array())
  8598. {
  8599. return $this->queryInternal('',0,$params);
  8600. }
  8601. public function queryAll($fetchAssociative=true,$params=array())
  8602. {
  8603. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8604. }
  8605. public function queryRow($fetchAssociative=true,$params=array())
  8606. {
  8607. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8608. }
  8609. public function queryScalar($params=array())
  8610. {
  8611. $result=$this->queryInternal('fetchColumn',0,$params);
  8612. if(is_resource($result) && get_resource_type($result)==='stream')
  8613. return stream_get_contents($result);
  8614. else
  8615. return $result;
  8616. }
  8617. public function queryColumn($params=array())
  8618. {
  8619. return $this->queryInternal('fetchAll',PDO::FETCH_COLUMN,$params);
  8620. }
  8621. private function queryInternal($method,$mode,$params=array())
  8622. {
  8623. $params=array_merge($this->params,$params);
  8624. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8625. {
  8626. $p=array();
  8627. foreach($pars as $name=>$value)
  8628. $p[$name]=$name.'='.var_export($value,true);
  8629. $par='. Bound with '.implode(', ',$p);
  8630. }
  8631. else
  8632. $par='';
  8633. if($this->_connection->queryCachingCount>0 && $method!==''
  8634. && $this->_connection->queryCachingDuration>0
  8635. && $this->_connection->queryCacheID!==false
  8636. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  8637. {
  8638. $this->_connection->queryCachingCount--;
  8639. $cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
  8640. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  8641. if(($result=$cache->get($cacheKey))!==false)
  8642. {
  8643. return $result;
  8644. }
  8645. }
  8646. try
  8647. {
  8648. if($this->_connection->enableProfiling)
  8649. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8650. $this->prepare();
  8651. if($params===array())
  8652. $this->_statement->execute();
  8653. else
  8654. $this->_statement->execute($params);
  8655. if($method==='')
  8656. $result=new CDbDataReader($this);
  8657. else
  8658. {
  8659. $mode=(array)$mode;
  8660. $result=call_user_func_array(array($this->_statement, $method), $mode);
  8661. $this->_statement->closeCursor();
  8662. }
  8663. if($this->_connection->enableProfiling)
  8664. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8665. if(isset($cache,$cacheKey))
  8666. $cache->set($cacheKey, $result, $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  8667. return $result;
  8668. }
  8669. catch(Exception $e)
  8670. {
  8671. if($this->_connection->enableProfiling)
  8672. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8673. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8674. $message = $e->getMessage();
  8675. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  8676. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8677. if(YII_DEBUG)
  8678. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  8679. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8680. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8681. }
  8682. }
  8683. public function buildQuery($query)
  8684. {
  8685. $sql=isset($query['distinct']) && $query['distinct'] ? 'SELECT DISTINCT' : 'SELECT';
  8686. $sql.=' '.(isset($query['select']) ? $query['select'] : '*');
  8687. if(isset($query['from']))
  8688. $sql.="\nFROM ".$query['from'];
  8689. else
  8690. throw new CDbException(Yii::t('yii','The DB query must contain the "from" portion.'));
  8691. if(isset($query['join']))
  8692. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  8693. if(isset($query['where']))
  8694. $sql.="\nWHERE ".$query['where'];
  8695. if(isset($query['group']))
  8696. $sql.="\nGROUP BY ".$query['group'];
  8697. if(isset($query['having']))
  8698. $sql.="\nHAVING ".$query['having'];
  8699. if(isset($query['order']))
  8700. $sql.="\nORDER BY ".$query['order'];
  8701. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  8702. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  8703. if($limit>=0 || $offset>0)
  8704. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  8705. if(isset($query['union']))
  8706. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  8707. return $sql;
  8708. }
  8709. public function select($columns='*', $option='')
  8710. {
  8711. if(is_string($columns) && strpos($columns,'(')!==false)
  8712. $this->_query['select']=$columns;
  8713. else
  8714. {
  8715. if(!is_array($columns))
  8716. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8717. foreach($columns as $i=>$column)
  8718. {
  8719. if(is_object($column))
  8720. $columns[$i]=(string)$column;
  8721. else if(strpos($column,'(')===false)
  8722. {
  8723. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  8724. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  8725. else
  8726. $columns[$i]=$this->_connection->quoteColumnName($column);
  8727. }
  8728. }
  8729. $this->_query['select']=implode(', ',$columns);
  8730. }
  8731. if($option!='')
  8732. $this->_query['select']=$option.' '.$this->_query['select'];
  8733. return $this;
  8734. }
  8735. public function getSelect()
  8736. {
  8737. return isset($this->_query['select']) ? $this->_query['select'] : '';
  8738. }
  8739. public function setSelect($value)
  8740. {
  8741. $this->select($value);
  8742. }
  8743. public function selectDistinct($columns='*')
  8744. {
  8745. $this->_query['distinct']=true;
  8746. return $this->select($columns);
  8747. }
  8748. public function getDistinct()
  8749. {
  8750. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  8751. }
  8752. public function setDistinct($value)
  8753. {
  8754. $this->_query['distinct']=$value;
  8755. }
  8756. public function from($tables)
  8757. {
  8758. if(is_string($tables) && strpos($tables,'(')!==false)
  8759. $this->_query['from']=$tables;
  8760. else
  8761. {
  8762. if(!is_array($tables))
  8763. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  8764. foreach($tables as $i=>$table)
  8765. {
  8766. if(strpos($table,'(')===false)
  8767. {
  8768. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  8769. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  8770. else
  8771. $tables[$i]=$this->_connection->quoteTableName($table);
  8772. }
  8773. }
  8774. $this->_query['from']=implode(', ',$tables);
  8775. }
  8776. return $this;
  8777. }
  8778. public function getFrom()
  8779. {
  8780. return isset($this->_query['from']) ? $this->_query['from'] : '';
  8781. }
  8782. public function setFrom($value)
  8783. {
  8784. $this->from($value);
  8785. }
  8786. public function where($conditions, $params=array())
  8787. {
  8788. $this->_query['where']=$this->processConditions($conditions);
  8789. foreach($params as $name=>$value)
  8790. $this->params[$name]=$value;
  8791. return $this;
  8792. }
  8793. public function getWhere()
  8794. {
  8795. return isset($this->_query['where']) ? $this->_query['where'] : '';
  8796. }
  8797. public function setWhere($value)
  8798. {
  8799. $this->where($value);
  8800. }
  8801. public function join($table, $conditions, $params=array())
  8802. {
  8803. return $this->joinInternal('join', $table, $conditions, $params);
  8804. }
  8805. public function getJoin()
  8806. {
  8807. return isset($this->_query['join']) ? $this->_query['join'] : '';
  8808. }
  8809. public function setJoin($value)
  8810. {
  8811. $this->_query['join']=$value;
  8812. }
  8813. public function leftJoin($table, $conditions, $params=array())
  8814. {
  8815. return $this->joinInternal('left join', $table, $conditions, $params);
  8816. }
  8817. public function rightJoin($table, $conditions, $params=array())
  8818. {
  8819. return $this->joinInternal('right join', $table, $conditions, $params);
  8820. }
  8821. public function crossJoin($table)
  8822. {
  8823. return $this->joinInternal('cross join', $table);
  8824. }
  8825. public function naturalJoin($table)
  8826. {
  8827. return $this->joinInternal('natural join', $table);
  8828. }
  8829. public function group($columns)
  8830. {
  8831. if(is_string($columns) && strpos($columns,'(')!==false)
  8832. $this->_query['group']=$columns;
  8833. else
  8834. {
  8835. if(!is_array($columns))
  8836. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8837. foreach($columns as $i=>$column)
  8838. {
  8839. if(is_object($column))
  8840. $columns[$i]=(string)$column;
  8841. else if(strpos($column,'(')===false)
  8842. $columns[$i]=$this->_connection->quoteColumnName($column);
  8843. }
  8844. $this->_query['group']=implode(', ',$columns);
  8845. }
  8846. return $this;
  8847. }
  8848. public function getGroup()
  8849. {
  8850. return isset($this->_query['group']) ? $this->_query['group'] : '';
  8851. }
  8852. public function setGroup($value)
  8853. {
  8854. $this->group($value);
  8855. }
  8856. public function having($conditions, $params=array())
  8857. {
  8858. $this->_query['having']=$this->processConditions($conditions);
  8859. foreach($params as $name=>$value)
  8860. $this->params[$name]=$value;
  8861. return $this;
  8862. }
  8863. public function getHaving()
  8864. {
  8865. return isset($this->_query['having']) ? $this->_query['having'] : '';
  8866. }
  8867. public function setHaving($value)
  8868. {
  8869. $this->having($value);
  8870. }
  8871. public function order($columns)
  8872. {
  8873. if(is_string($columns) && strpos($columns,'(')!==false)
  8874. $this->_query['order']=$columns;
  8875. else
  8876. {
  8877. if(!is_array($columns))
  8878. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8879. foreach($columns as $i=>$column)
  8880. {
  8881. if(is_object($column))
  8882. $columns[$i]=(string)$column;
  8883. else if(strpos($column,'(')===false)
  8884. {
  8885. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  8886. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  8887. else
  8888. $columns[$i]=$this->_connection->quoteColumnName($column);
  8889. }
  8890. }
  8891. $this->_query['order']=implode(', ',$columns);
  8892. }
  8893. return $this;
  8894. }
  8895. public function getOrder()
  8896. {
  8897. return isset($this->_query['order']) ? $this->_query['order'] : '';
  8898. }
  8899. public function setOrder($value)
  8900. {
  8901. $this->order($value);
  8902. }
  8903. public function limit($limit, $offset=null)
  8904. {
  8905. $this->_query['limit']=(int)$limit;
  8906. if($offset!==null)
  8907. $this->offset($offset);
  8908. return $this;
  8909. }
  8910. public function getLimit()
  8911. {
  8912. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  8913. }
  8914. public function setLimit($value)
  8915. {
  8916. $this->limit($value);
  8917. }
  8918. public function offset($offset)
  8919. {
  8920. $this->_query['offset']=(int)$offset;
  8921. return $this;
  8922. }
  8923. public function getOffset()
  8924. {
  8925. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  8926. }
  8927. public function setOffset($value)
  8928. {
  8929. $this->offset($value);
  8930. }
  8931. public function union($sql)
  8932. {
  8933. if(isset($this->_query['union']) && is_string($this->_query['union']))
  8934. $this->_query['union']=array($this->_query['union']);
  8935. $this->_query['union'][]=$sql;
  8936. return $this;
  8937. }
  8938. public function getUnion()
  8939. {
  8940. return isset($this->_query['union']) ? $this->_query['union'] : '';
  8941. }
  8942. public function setUnion($value)
  8943. {
  8944. $this->_query['union']=$value;
  8945. }
  8946. public function insert($table, $columns)
  8947. {
  8948. $params=array();
  8949. $names=array();
  8950. $placeholders=array();
  8951. foreach($columns as $name=>$value)
  8952. {
  8953. $names[]=$this->_connection->quoteColumnName($name);
  8954. if($value instanceof CDbExpression)
  8955. {
  8956. $placeholders[] = $value->expression;
  8957. foreach($value->params as $n => $v)
  8958. $params[$n] = $v;
  8959. }
  8960. else
  8961. {
  8962. $placeholders[] = ':' . $name;
  8963. $params[':' . $name] = $value;
  8964. }
  8965. }
  8966. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  8967. . ' (' . implode(', ',$names) . ') VALUES ('
  8968. . implode(', ', $placeholders) . ')';
  8969. return $this->setText($sql)->execute($params);
  8970. }
  8971. public function update($table, $columns, $conditions='', $params=array())
  8972. {
  8973. $lines=array();
  8974. foreach($columns as $name=>$value)
  8975. {
  8976. if($value instanceof CDbExpression)
  8977. {
  8978. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  8979. foreach($value->params as $n => $v)
  8980. $params[$n] = $v;
  8981. }
  8982. else
  8983. {
  8984. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  8985. $params[':' . $name]=$value;
  8986. }
  8987. }
  8988. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  8989. if(($where=$this->processConditions($conditions))!='')
  8990. $sql.=' WHERE '.$where;
  8991. return $this->setText($sql)->execute($params);
  8992. }
  8993. public function delete($table, $conditions='', $params=array())
  8994. {
  8995. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  8996. if(($where=$this->processConditions($conditions))!='')
  8997. $sql.=' WHERE '.$where;
  8998. return $this->setText($sql)->execute($params);
  8999. }
  9000. public function createTable($table, $columns, $options=null)
  9001. {
  9002. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  9003. }
  9004. public function renameTable($table, $newName)
  9005. {
  9006. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  9007. }
  9008. public function dropTable($table)
  9009. {
  9010. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  9011. }
  9012. public function truncateTable($table)
  9013. {
  9014. $schema=$this->getConnection()->getSchema();
  9015. $n=$this->setText($schema->truncateTable($table))->execute();
  9016. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  9017. $schema->resetSequence($schema->getTable($table));
  9018. return $n;
  9019. }
  9020. public function addColumn($table, $column, $type)
  9021. {
  9022. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  9023. }
  9024. public function dropColumn($table, $column)
  9025. {
  9026. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  9027. }
  9028. public function renameColumn($table, $name, $newName)
  9029. {
  9030. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  9031. }
  9032. public function alterColumn($table, $column, $type)
  9033. {
  9034. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  9035. }
  9036. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9037. {
  9038. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  9039. }
  9040. public function dropForeignKey($name, $table)
  9041. {
  9042. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  9043. }
  9044. public function createIndex($name, $table, $column, $unique=false)
  9045. {
  9046. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $column, $unique))->execute();
  9047. }
  9048. public function dropIndex($name, $table)
  9049. {
  9050. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  9051. }
  9052. private function processConditions($conditions)
  9053. {
  9054. if(!is_array($conditions))
  9055. return $conditions;
  9056. else if($conditions===array())
  9057. return '';
  9058. $n=count($conditions);
  9059. $operator=strtoupper($conditions[0]);
  9060. if($operator==='OR' || $operator==='AND')
  9061. {
  9062. $parts=array();
  9063. for($i=1;$i<$n;++$i)
  9064. {
  9065. $condition=$this->processConditions($conditions[$i]);
  9066. if($condition!=='')
  9067. $parts[]='('.$condition.')';
  9068. }
  9069. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  9070. }
  9071. if(!isset($conditions[1],$conditions[2]))
  9072. return '';
  9073. $column=$conditions[1];
  9074. if(strpos($column,'(')===false)
  9075. $column=$this->_connection->quoteColumnName($column);
  9076. $values=$conditions[2];
  9077. if(!is_array($values))
  9078. $values=array($values);
  9079. if($operator==='IN' || $operator==='NOT IN')
  9080. {
  9081. if($values===array())
  9082. return $operator==='IN' ? '0=1' : '';
  9083. foreach($values as $i=>$value)
  9084. {
  9085. if(is_string($value))
  9086. $values[$i]=$this->_connection->quoteValue($value);
  9087. else
  9088. $values[$i]=(string)$value;
  9089. }
  9090. return $column.' '.$operator.' ('.implode(', ',$values).')';
  9091. }
  9092. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  9093. {
  9094. if($values===array())
  9095. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  9096. if($operator==='LIKE' || $operator==='NOT LIKE')
  9097. $andor=' AND ';
  9098. else
  9099. {
  9100. $andor=' OR ';
  9101. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  9102. }
  9103. $expressions=array();
  9104. foreach($values as $value)
  9105. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  9106. return implode($andor,$expressions);
  9107. }
  9108. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  9109. }
  9110. private function joinInternal($type, $table, $conditions='', $params=array())
  9111. {
  9112. if(strpos($table,'(')===false)
  9113. {
  9114. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9115. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9116. else
  9117. $table=$this->_connection->quoteTableName($table);
  9118. }
  9119. $conditions=$this->processConditions($conditions);
  9120. if($conditions!='')
  9121. $conditions=' ON '.$conditions;
  9122. if(isset($this->_query['join']) && is_string($this->_query['join']))
  9123. $this->_query['join']=array($this->_query['join']);
  9124. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  9125. foreach($params as $name=>$value)
  9126. $this->params[$name]=$value;
  9127. return $this;
  9128. }
  9129. }
  9130. class CDbColumnSchema extends CComponent
  9131. {
  9132. public $name;
  9133. public $rawName;
  9134. public $allowNull;
  9135. public $dbType;
  9136. public $type;
  9137. public $defaultValue;
  9138. public $size;
  9139. public $precision;
  9140. public $scale;
  9141. public $isPrimaryKey;
  9142. public $isForeignKey;
  9143. public $autoIncrement=false;
  9144. public function init($dbType, $defaultValue)
  9145. {
  9146. $this->dbType=$dbType;
  9147. $this->extractType($dbType);
  9148. $this->extractLimit($dbType);
  9149. if($defaultValue!==null)
  9150. $this->extractDefault($defaultValue);
  9151. }
  9152. protected function extractType($dbType)
  9153. {
  9154. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  9155. $this->type='integer';
  9156. else if(stripos($dbType,'bool')!==false)
  9157. $this->type='boolean';
  9158. else if(preg_match('/(real|floa|doub)/i',$dbType))
  9159. $this->type='double';
  9160. else
  9161. $this->type='string';
  9162. }
  9163. protected function extractLimit($dbType)
  9164. {
  9165. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  9166. {
  9167. $values=explode(',',$matches[1]);
  9168. $this->size=$this->precision=(int)$values[0];
  9169. if(isset($values[1]))
  9170. $this->scale=(int)$values[1];
  9171. }
  9172. }
  9173. protected function extractDefault($defaultValue)
  9174. {
  9175. $this->defaultValue=$this->typecast($defaultValue);
  9176. }
  9177. public function typecast($value)
  9178. {
  9179. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  9180. return $value;
  9181. if($value==='' && $this->allowNull)
  9182. return $this->type==='string' ? '' : null;
  9183. switch($this->type)
  9184. {
  9185. case 'string': return (string)$value;
  9186. case 'integer': return (integer)$value;
  9187. case 'boolean': return (boolean)$value;
  9188. case 'double':
  9189. default: return $value;
  9190. }
  9191. }
  9192. }
  9193. class CSqliteColumnSchema extends CDbColumnSchema
  9194. {
  9195. protected function extractDefault($defaultValue)
  9196. {
  9197. if($this->type==='string') // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  9198. $this->defaultValue=trim($defaultValue,"'\"");
  9199. else
  9200. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  9201. }
  9202. }
  9203. abstract class CValidator extends CComponent
  9204. {
  9205. public static $builtInValidators=array(
  9206. 'required'=>'CRequiredValidator',
  9207. 'filter'=>'CFilterValidator',
  9208. 'match'=>'CRegularExpressionValidator',
  9209. 'email'=>'CEmailValidator',
  9210. 'url'=>'CUrlValidator',
  9211. 'unique'=>'CUniqueValidator',
  9212. 'compare'=>'CCompareValidator',
  9213. 'length'=>'CStringValidator',
  9214. 'in'=>'CRangeValidator',
  9215. 'numerical'=>'CNumberValidator',
  9216. 'captcha'=>'CCaptchaValidator',
  9217. 'type'=>'CTypeValidator',
  9218. 'file'=>'CFileValidator',
  9219. 'default'=>'CDefaultValueValidator',
  9220. 'exist'=>'CExistValidator',
  9221. 'boolean'=>'CBooleanValidator',
  9222. 'safe'=>'CSafeValidator',
  9223. 'unsafe'=>'CUnsafeValidator',
  9224. 'date'=>'CDateValidator',
  9225. );
  9226. public $attributes;
  9227. public $message;
  9228. public $skipOnError=false;
  9229. public $on;
  9230. public $safe=true;
  9231. public $enableClientValidation=true;
  9232. abstract protected function validateAttribute($object,$attribute);
  9233. public static function createValidator($name,$object,$attributes,$params=array())
  9234. {
  9235. if(is_string($attributes))
  9236. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  9237. if(isset($params['on']))
  9238. {
  9239. if(is_array($params['on']))
  9240. $on=$params['on'];
  9241. else
  9242. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  9243. }
  9244. else
  9245. $on=array();
  9246. if(method_exists($object,$name))
  9247. {
  9248. $validator=new CInlineValidator;
  9249. $validator->attributes=$attributes;
  9250. $validator->method=$name;
  9251. if(isset($params['clientValidate']))
  9252. {
  9253. $validator->clientValidate=$params['clientValidate'];
  9254. unset($params['clientValidate']);
  9255. }
  9256. $validator->params=$params;
  9257. if(isset($params['skipOnError']))
  9258. $validator->skipOnError=$params['skipOnError'];
  9259. }
  9260. else
  9261. {
  9262. $params['attributes']=$attributes;
  9263. if(isset(self::$builtInValidators[$name]))
  9264. $className=Yii::import(self::$builtInValidators[$name],true);
  9265. else
  9266. $className=Yii::import($name,true);
  9267. $validator=new $className;
  9268. foreach($params as $name=>$value)
  9269. $validator->$name=$value;
  9270. }
  9271. $validator->on=empty($on) ? array() : array_combine($on,$on);
  9272. return $validator;
  9273. }
  9274. public function validate($object,$attributes=null)
  9275. {
  9276. if(is_array($attributes))
  9277. $attributes=array_intersect($this->attributes,$attributes);
  9278. else
  9279. $attributes=$this->attributes;
  9280. foreach($attributes as $attribute)
  9281. {
  9282. if(!$this->skipOnError || !$object->hasErrors($attribute))
  9283. $this->validateAttribute($object,$attribute);
  9284. }
  9285. }
  9286. public function clientValidateAttribute($object,$attribute)
  9287. {
  9288. }
  9289. public function applyTo($scenario)
  9290. {
  9291. return empty($this->on) || isset($this->on[$scenario]);
  9292. }
  9293. protected function addError($object,$attribute,$message,$params=array())
  9294. {
  9295. $params['{attribute}']=$object->getAttributeLabel($attribute);
  9296. $object->addError($attribute,strtr($message,$params));
  9297. }
  9298. protected function isEmpty($value,$trim=false)
  9299. {
  9300. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  9301. }
  9302. }
  9303. class CStringValidator extends CValidator
  9304. {
  9305. public $max;
  9306. public $min;
  9307. public $is;
  9308. public $tooShort;
  9309. public $tooLong;
  9310. public $allowEmpty=true;
  9311. public $encoding;
  9312. protected function validateAttribute($object,$attribute)
  9313. {
  9314. $value=$object->$attribute;
  9315. if($this->allowEmpty && $this->isEmpty($value))
  9316. return;
  9317. if(function_exists('mb_strlen') && $this->encoding!==false)
  9318. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  9319. else
  9320. $length=strlen($value);
  9321. if($this->min!==null && $length<$this->min)
  9322. {
  9323. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9324. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9325. }
  9326. if($this->max!==null && $length>$this->max)
  9327. {
  9328. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9329. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9330. }
  9331. if($this->is!==null && $length!==$this->is)
  9332. {
  9333. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9334. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  9335. }
  9336. }
  9337. public function clientValidateAttribute($object,$attribute)
  9338. {
  9339. $label=$object->getAttributeLabel($attribute);
  9340. if(($message=$this->message)===null)
  9341. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9342. $message=strtr($message, array(
  9343. '{attribute}'=>$label,
  9344. '{length}'=>$this->is,
  9345. ));
  9346. if(($tooShort=$this->tooShort)===null)
  9347. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9348. $tooShort=strtr($tooShort, array(
  9349. '{attribute}'=>$label,
  9350. '{min}'=>$this->min,
  9351. ));
  9352. if(($tooLong=$this->tooLong)===null)
  9353. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9354. $tooLong=strtr($tooLong, array(
  9355. '{attribute}'=>$label,
  9356. '{max}'=>$this->max,
  9357. ));
  9358. $js='';
  9359. if($this->min!==null)
  9360. {
  9361. $js.="
  9362. if(value.length<{$this->min}) {
  9363. messages.push(".CJSON::encode($tooShort).");
  9364. }
  9365. ";
  9366. }
  9367. if($this->max!==null)
  9368. {
  9369. $js.="
  9370. if(value.length>{$this->max}) {
  9371. messages.push(".CJSON::encode($tooLong).");
  9372. }
  9373. ";
  9374. }
  9375. if($this->is!==null)
  9376. {
  9377. $js.="
  9378. if(value.length!={$this->is}) {
  9379. messages.push(".CJSON::encode($message).");
  9380. }
  9381. ";
  9382. }
  9383. if($this->allowEmpty)
  9384. {
  9385. $js="
  9386. if($.trim(value)!='') {
  9387. $js
  9388. }
  9389. ";
  9390. }
  9391. return $js;
  9392. }
  9393. }
  9394. class CRequiredValidator extends CValidator
  9395. {
  9396. public $requiredValue;
  9397. public $strict=false;
  9398. protected function validateAttribute($object,$attribute)
  9399. {
  9400. $value=$object->$attribute;
  9401. if($this->requiredValue!==null)
  9402. {
  9403. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  9404. {
  9405. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  9406. array('{value}'=>$this->requiredValue));
  9407. $this->addError($object,$attribute,$message);
  9408. }
  9409. }
  9410. else if($this->isEmpty($value,true))
  9411. {
  9412. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  9413. $this->addError($object,$attribute,$message);
  9414. }
  9415. }
  9416. public function clientValidateAttribute($object,$attribute)
  9417. {
  9418. $message=$this->message;
  9419. if($this->requiredValue!==null)
  9420. {
  9421. if($message===null)
  9422. $message=Yii::t('yii','{attribute} must be {value}.');
  9423. $message=strtr($message, array(
  9424. '{value}'=>$this->requiredValue,
  9425. '{attribute}'=>$object->getAttributeLabel($attribute),
  9426. ));
  9427. return "
  9428. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  9429. messages.push(".CJSON::encode($message).");
  9430. }
  9431. ";
  9432. }
  9433. else
  9434. {
  9435. if($message===null)
  9436. $message=Yii::t('yii','{attribute} cannot be blank.');
  9437. $message=strtr($message, array(
  9438. '{attribute}'=>$object->getAttributeLabel($attribute),
  9439. ));
  9440. return "
  9441. if($.trim(value)=='') {
  9442. messages.push(".CJSON::encode($message).");
  9443. }
  9444. ";
  9445. }
  9446. }
  9447. }
  9448. class CNumberValidator extends CValidator
  9449. {
  9450. public $integerOnly=false;
  9451. public $allowEmpty=true;
  9452. public $max;
  9453. public $min;
  9454. public $tooBig;
  9455. public $tooSmall;
  9456. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  9457. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  9458. protected function validateAttribute($object,$attribute)
  9459. {
  9460. $value=$object->$attribute;
  9461. if($this->allowEmpty && $this->isEmpty($value))
  9462. return;
  9463. if($this->integerOnly)
  9464. {
  9465. if(!preg_match($this->integerPattern,"$value"))
  9466. {
  9467. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  9468. $this->addError($object,$attribute,$message);
  9469. }
  9470. }
  9471. else
  9472. {
  9473. if(!preg_match($this->numberPattern,"$value"))
  9474. {
  9475. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  9476. $this->addError($object,$attribute,$message);
  9477. }
  9478. }
  9479. if($this->min!==null && $value<$this->min)
  9480. {
  9481. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9482. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9483. }
  9484. if($this->max!==null && $value>$this->max)
  9485. {
  9486. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9487. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9488. }
  9489. }
  9490. public function clientValidateAttribute($object,$attribute)
  9491. {
  9492. $label=$object->getAttributeLabel($attribute);
  9493. if(($message=$this->message)===null)
  9494. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  9495. $message=strtr($message, array(
  9496. '{attribute}'=>$label,
  9497. ));
  9498. if(($tooBig=$this->tooBig)===null)
  9499. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9500. $tooBig=strtr($tooBig, array(
  9501. '{attribute}'=>$label,
  9502. '{max}'=>$this->max,
  9503. ));
  9504. if(($tooSmall=$this->tooSmall)===null)
  9505. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9506. $tooSmall=strtr($tooSmall, array(
  9507. '{attribute}'=>$label,
  9508. '{min}'=>$this->min,
  9509. ));
  9510. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  9511. $js="
  9512. if(!value.match($pattern)) {
  9513. messages.push(".CJSON::encode($message).");
  9514. }
  9515. ";
  9516. if($this->min!==null)
  9517. {
  9518. $js.="
  9519. if(value<{$this->min}) {
  9520. messages.push(".CJSON::encode($tooSmall).");
  9521. }
  9522. ";
  9523. }
  9524. if($this->max!==null)
  9525. {
  9526. $js.="
  9527. if(value>{$this->max}) {
  9528. messages.push(".CJSON::encode($tooBig).");
  9529. }
  9530. ";
  9531. }
  9532. if($this->allowEmpty)
  9533. {
  9534. $js="
  9535. if($.trim(value)!='') {
  9536. $js
  9537. }
  9538. ";
  9539. }
  9540. return $js;
  9541. }
  9542. }
  9543. class CListIterator implements Iterator
  9544. {
  9545. private $_d;
  9546. private $_i;
  9547. private $_c;
  9548. public function __construct(&$data)
  9549. {
  9550. $this->_d=&$data;
  9551. $this->_i=0;
  9552. $this->_c=count($this->_d);
  9553. }
  9554. public function rewind()
  9555. {
  9556. $this->_i=0;
  9557. }
  9558. public function key()
  9559. {
  9560. return $this->_i;
  9561. }
  9562. public function current()
  9563. {
  9564. return $this->_d[$this->_i];
  9565. }
  9566. public function next()
  9567. {
  9568. $this->_i++;
  9569. }
  9570. public function valid()
  9571. {
  9572. return $this->_i<$this->_c;
  9573. }
  9574. }
  9575. interface IApplicationComponent
  9576. {
  9577. public function init();
  9578. public function getIsInitialized();
  9579. }
  9580. interface ICache
  9581. {
  9582. public function get($id);
  9583. public function mget($ids);
  9584. public function set($id,$value,$expire=0,$dependency=null);
  9585. public function add($id,$value,$expire=0,$dependency=null);
  9586. public function delete($id);
  9587. public function flush();
  9588. }
  9589. interface ICacheDependency
  9590. {
  9591. public function evaluateDependency();
  9592. public function getHasChanged();
  9593. }
  9594. interface IStatePersister
  9595. {
  9596. public function load();
  9597. public function save($state);
  9598. }
  9599. interface IFilter
  9600. {
  9601. public function filter($filterChain);
  9602. }
  9603. interface IAction
  9604. {
  9605. public function getId();
  9606. public function getController();
  9607. }
  9608. interface IWebServiceProvider
  9609. {
  9610. public function beforeWebMethod($service);
  9611. public function afterWebMethod($service);
  9612. }
  9613. interface IViewRenderer
  9614. {
  9615. public function renderFile($context,$file,$data,$return);
  9616. }
  9617. interface IUserIdentity
  9618. {
  9619. public function authenticate();
  9620. public function getIsAuthenticated();
  9621. public function getId();
  9622. public function getName();
  9623. public function getPersistentStates();
  9624. }
  9625. interface IWebUser
  9626. {
  9627. public function getId();
  9628. public function getName();
  9629. public function getIsGuest();
  9630. public function checkAccess($operation,$params=array());
  9631. }
  9632. interface IAuthManager
  9633. {
  9634. public function checkAccess($itemName,$userId,$params=array());
  9635. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  9636. public function removeAuthItem($name);
  9637. public function getAuthItems($type=null,$userId=null);
  9638. public function getAuthItem($name);
  9639. public function saveAuthItem($item,$oldName=null);
  9640. public function addItemChild($itemName,$childName);
  9641. public function removeItemChild($itemName,$childName);
  9642. public function hasItemChild($itemName,$childName);
  9643. public function getItemChildren($itemName);
  9644. public function assign($itemName,$userId,$bizRule=null,$data=null);
  9645. public function revoke($itemName,$userId);
  9646. public function isAssigned($itemName,$userId);
  9647. public function getAuthAssignment($itemName,$userId);
  9648. public function getAuthAssignments($userId);
  9649. public function saveAuthAssignment($assignment);
  9650. public function clearAll();
  9651. public function clearAuthAssignments();
  9652. public function save();
  9653. public function executeBizRule($bizRule,$params,$data);
  9654. }
  9655. interface IBehavior
  9656. {
  9657. public function attach($component);
  9658. public function detach($component);
  9659. public function getEnabled();
  9660. public function setEnabled($value);
  9661. }
  9662. interface IWidgetFactory
  9663. {
  9664. public function createWidget($owner,$className,$properties=array());
  9665. }
  9666. interface IDataProvider
  9667. {
  9668. public function getId();
  9669. public function getItemCount($refresh=false);
  9670. public function getTotalItemCount($refresh=false);
  9671. public function getData($refresh=false);
  9672. public function getKeys($refresh=false);
  9673. public function getSort();
  9674. public function getPagination();
  9675. }
  9676. ?>