PageRenderTime 116ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 1ms

/yii-1.1.10.r3566/framework/yiilite.php

https://bitbucket.org/zadoev/yii-skeleton
PHP | 9680 lines | 9625 code | 2 blank | 53 comment | 815 complexity | 304ce166e05e4d980ea7815ba6f9a8e9 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-2-Clause, BSD-3-Clause
  1. <?php
  2. /**
  3. * Yii bootstrap file.
  4. *
  5. * This file is automatically generated using 'build lite' command.
  6. * It is the result of merging commonly used Yii class files with
  7. * comments and trace statements removed away.
  8. *
  9. * By using this file instead of yii.php, an Yii application may
  10. * improve performance due to the reduction of PHP parsing time.
  11. * The performance improvement is especially obvious when PHP APC extension
  12. * is enabled.
  13. *
  14. * DO NOT modify this file manually.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @link http://www.yiiframework.com/
  18. * @copyright Copyright &copy; 2008-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. public static function app()
  56. {
  57. return self::$_app;
  58. }
  59. public static function setApplication($app)
  60. {
  61. if(self::$_app===null || $app===null)
  62. self::$_app=$app;
  63. else
  64. throw new CException(Yii::t('yii','Yii application can only be created once.'));
  65. }
  66. public static function getFrameworkPath()
  67. {
  68. return YII_PATH;
  69. }
  70. public static function createComponent($config)
  71. {
  72. if(is_string($config))
  73. {
  74. $type=$config;
  75. $config=array();
  76. }
  77. else if(isset($config['class']))
  78. {
  79. $type=$config['class'];
  80. unset($config['class']);
  81. }
  82. else
  83. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  84. if(!class_exists($type,false))
  85. $type=Yii::import($type,true);
  86. if(($n=func_num_args())>1)
  87. {
  88. $args=func_get_args();
  89. if($n===2)
  90. $object=new $type($args[1]);
  91. else if($n===3)
  92. $object=new $type($args[1],$args[2]);
  93. else if($n===4)
  94. $object=new $type($args[1],$args[2],$args[3]);
  95. else
  96. {
  97. unset($args[0]);
  98. $class=new ReflectionClass($type);
  99. // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
  100. // $object=$class->newInstanceArgs($args);
  101. $object=call_user_func_array(array($class,'newInstance'),$args);
  102. }
  103. }
  104. else
  105. $object=new $type;
  106. foreach($config as $key=>$value)
  107. $object->$key=$value;
  108. return $object;
  109. }
  110. public static function import($alias,$forceInclude=false)
  111. {
  112. if(isset(self::$_imports[$alias])) // previously imported
  113. return self::$_imports[$alias];
  114. if(class_exists($alias,false) || interface_exists($alias,false))
  115. return self::$_imports[$alias]=$alias;
  116. if(($pos=strrpos($alias,'\\'))!==false) // a class name in PHP 5.3 namespace format
  117. {
  118. $namespace=str_replace('\\','.',ltrim(substr($alias,0,$pos),'\\'));
  119. if(($path=self::getPathOfAlias($namespace))!==false)
  120. {
  121. $classFile=$path.DIRECTORY_SEPARATOR.substr($alias,$pos+1).'.php';
  122. if($forceInclude)
  123. {
  124. if(is_file($classFile))
  125. require($classFile);
  126. else
  127. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file.',array('{alias}'=>$alias)));
  128. self::$_imports[$alias]=$alias;
  129. }
  130. else
  131. self::$classMap[$alias]=$classFile;
  132. return $alias;
  133. }
  134. else
  135. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory.',
  136. array('{alias}'=>$namespace)));
  137. }
  138. if(($pos=strrpos($alias,'.'))===false) // a simple class name
  139. {
  140. if($forceInclude && self::autoload($alias))
  141. self::$_imports[$alias]=$alias;
  142. return $alias;
  143. }
  144. $className=(string)substr($alias,$pos+1);
  145. $isClass=$className!=='*';
  146. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  147. return self::$_imports[$alias]=$className;
  148. if(($path=self::getPathOfAlias($alias))!==false)
  149. {
  150. if($isClass)
  151. {
  152. if($forceInclude)
  153. {
  154. if(is_file($path.'.php'))
  155. require($path.'.php');
  156. else
  157. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file.',array('{alias}'=>$alias)));
  158. self::$_imports[$alias]=$className;
  159. }
  160. else
  161. self::$classMap[$className]=$path.'.php';
  162. return $className;
  163. }
  164. else // a directory
  165. {
  166. if(self::$_includePaths===null)
  167. {
  168. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  169. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  170. unset(self::$_includePaths[$pos]);
  171. }
  172. array_unshift(self::$_includePaths,$path);
  173. if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  174. self::$enableIncludePath=false;
  175. return self::$_imports[$alias]=$path;
  176. }
  177. }
  178. else
  179. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  180. array('{alias}'=>$alias)));
  181. }
  182. public static function getPathOfAlias($alias)
  183. {
  184. if(isset(self::$_aliases[$alias]))
  185. return self::$_aliases[$alias];
  186. else if(($pos=strpos($alias,'.'))!==false)
  187. {
  188. $rootAlias=substr($alias,0,$pos);
  189. if(isset(self::$_aliases[$rootAlias]))
  190. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  191. else if(self::$_app instanceof CWebApplication)
  192. {
  193. if(self::$_app->findModule($rootAlias)!==null)
  194. return self::getPathOfAlias($alias);
  195. }
  196. }
  197. return false;
  198. }
  199. public static function setPathOfAlias($alias,$path)
  200. {
  201. if(empty($path))
  202. unset(self::$_aliases[$alias]);
  203. else
  204. self::$_aliases[$alias]=rtrim($path,'\\/');
  205. }
  206. public static function autoload($className)
  207. {
  208. // use include so that the error PHP file may appear
  209. if(isset(self::$classMap[$className]))
  210. include(self::$classMap[$className]);
  211. else if(isset(self::$_coreClasses[$className]))
  212. include(YII_PATH.self::$_coreClasses[$className]);
  213. else
  214. {
  215. // include class file relying on include_path
  216. if(strpos($className,'\\')===false) // class without namespace
  217. {
  218. if(self::$enableIncludePath===false)
  219. {
  220. foreach(self::$_includePaths as $path)
  221. {
  222. $classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
  223. if(is_file($classFile))
  224. {
  225. include($classFile);
  226. break;
  227. }
  228. }
  229. }
  230. else
  231. include($className.'.php');
  232. }
  233. else // class name with namespace in PHP 5.3
  234. {
  235. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  236. if(($path=self::getPathOfAlias($namespace))!==false)
  237. include($path.'.php');
  238. else
  239. return false;
  240. }
  241. return class_exists($className,false) || interface_exists($className,false);
  242. }
  243. return true;
  244. }
  245. public static function trace($msg,$category='application')
  246. {
  247. if(YII_DEBUG)
  248. self::log($msg,CLogger::LEVEL_TRACE,$category);
  249. }
  250. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  251. {
  252. if(self::$_logger===null)
  253. self::$_logger=new CLogger;
  254. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  255. {
  256. $traces=debug_backtrace();
  257. $count=0;
  258. foreach($traces as $trace)
  259. {
  260. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  261. {
  262. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  263. if(++$count>=YII_TRACE_LEVEL)
  264. break;
  265. }
  266. }
  267. }
  268. self::$_logger->log($msg,$level,$category);
  269. }
  270. public static function beginProfile($token,$category='application')
  271. {
  272. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  273. }
  274. public static function endProfile($token,$category='application')
  275. {
  276. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  277. }
  278. public static function getLogger()
  279. {
  280. if(self::$_logger!==null)
  281. return self::$_logger;
  282. else
  283. return self::$_logger=new CLogger;
  284. }
  285. public static function setLogger($logger)
  286. {
  287. self::$_logger=$logger;
  288. }
  289. public static function powered()
  290. {
  291. return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
  292. }
  293. public static function t($category,$message,$params=array(),$source=null,$language=null)
  294. {
  295. if(self::$_app!==null)
  296. {
  297. if($source===null)
  298. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  299. if(($source=self::$_app->getComponent($source))!==null)
  300. $message=$source->translate($category,$message,$language);
  301. }
  302. if($params===array())
  303. return $message;
  304. if(!is_array($params))
  305. $params=array($params);
  306. if(isset($params[0])) // number choice
  307. {
  308. if(strpos($message,'|')!==false)
  309. {
  310. if(strpos($message,'#')===false)
  311. {
  312. $chunks=explode('|',$message);
  313. $expressions=self::$_app->getLocale($language)->getPluralRules();
  314. if($n=min(count($chunks),count($expressions)))
  315. {
  316. for($i=0;$i<$n;$i++)
  317. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  318. $message=implode('|',$chunks);
  319. }
  320. }
  321. $message=CChoiceFormat::format($message,$params[0]);
  322. }
  323. if(!isset($params['{n}']))
  324. $params['{n}']=$params[0];
  325. unset($params[0]);
  326. }
  327. return $params!==array() ? strtr($message,$params) : $message;
  328. }
  329. public static function registerAutoloader($callback, $append=false)
  330. {
  331. if($append)
  332. {
  333. self::$enableIncludePath=false;
  334. spl_autoload_register($callback);
  335. }
  336. else
  337. {
  338. spl_autoload_unregister(array('YiiBase','autoload'));
  339. spl_autoload_register($callback);
  340. spl_autoload_register(array('YiiBase','autoload'));
  341. }
  342. }
  343. private static $_coreClasses=array(
  344. 'CApplication' => '/base/CApplication.php',
  345. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  346. 'CBehavior' => '/base/CBehavior.php',
  347. 'CComponent' => '/base/CComponent.php',
  348. 'CErrorEvent' => '/base/CErrorEvent.php',
  349. 'CErrorHandler' => '/base/CErrorHandler.php',
  350. 'CException' => '/base/CException.php',
  351. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  352. 'CHttpException' => '/base/CHttpException.php',
  353. 'CModel' => '/base/CModel.php',
  354. 'CModelBehavior' => '/base/CModelBehavior.php',
  355. 'CModelEvent' => '/base/CModelEvent.php',
  356. 'CModule' => '/base/CModule.php',
  357. 'CSecurityManager' => '/base/CSecurityManager.php',
  358. 'CStatePersister' => '/base/CStatePersister.php',
  359. 'CApcCache' => '/caching/CApcCache.php',
  360. 'CCache' => '/caching/CCache.php',
  361. 'CDbCache' => '/caching/CDbCache.php',
  362. 'CDummyCache' => '/caching/CDummyCache.php',
  363. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  364. 'CFileCache' => '/caching/CFileCache.php',
  365. 'CMemCache' => '/caching/CMemCache.php',
  366. 'CWinCache' => '/caching/CWinCache.php',
  367. 'CXCache' => '/caching/CXCache.php',
  368. 'CZendDataCache' => '/caching/CZendDataCache.php',
  369. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  370. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  371. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  372. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  373. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  374. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  375. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  376. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  377. 'CConfiguration' => '/collections/CConfiguration.php',
  378. 'CList' => '/collections/CList.php',
  379. 'CListIterator' => '/collections/CListIterator.php',
  380. 'CMap' => '/collections/CMap.php',
  381. 'CMapIterator' => '/collections/CMapIterator.php',
  382. 'CQueue' => '/collections/CQueue.php',
  383. 'CQueueIterator' => '/collections/CQueueIterator.php',
  384. 'CStack' => '/collections/CStack.php',
  385. 'CStackIterator' => '/collections/CStackIterator.php',
  386. 'CTypedList' => '/collections/CTypedList.php',
  387. 'CTypedMap' => '/collections/CTypedMap.php',
  388. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  389. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  390. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  391. 'CHelpCommand' => '/console/CHelpCommand.php',
  392. 'CDbCommand' => '/db/CDbCommand.php',
  393. 'CDbConnection' => '/db/CDbConnection.php',
  394. 'CDbDataReader' => '/db/CDbDataReader.php',
  395. 'CDbException' => '/db/CDbException.php',
  396. 'CDbMigration' => '/db/CDbMigration.php',
  397. 'CDbTransaction' => '/db/CDbTransaction.php',
  398. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  399. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  400. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  401. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  402. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  403. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  404. 'CDbExpression' => '/db/schema/CDbExpression.php',
  405. 'CDbSchema' => '/db/schema/CDbSchema.php',
  406. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  407. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  408. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  409. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  410. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  411. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  412. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  413. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  414. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  415. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  416. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  417. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  418. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  419. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  420. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  421. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  422. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  423. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  424. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  425. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  426. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  427. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  428. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  429. 'CLocale' => '/i18n/CLocale.php',
  430. 'CMessageSource' => '/i18n/CMessageSource.php',
  431. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  432. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  433. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  434. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  435. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  436. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  437. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  438. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  439. 'CLogFilter' => '/logging/CLogFilter.php',
  440. 'CLogRoute' => '/logging/CLogRoute.php',
  441. 'CLogRouter' => '/logging/CLogRouter.php',
  442. 'CLogger' => '/logging/CLogger.php',
  443. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  444. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  445. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  446. 'CFileHelper' => '/utils/CFileHelper.php',
  447. 'CFormatter' => '/utils/CFormatter.php',
  448. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  449. 'CPropertyValue' => '/utils/CPropertyValue.php',
  450. 'CTimestamp' => '/utils/CTimestamp.php',
  451. 'CVarDumper' => '/utils/CVarDumper.php',
  452. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  453. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  454. 'CCompareValidator' => '/validators/CCompareValidator.php',
  455. 'CDateValidator' => '/validators/CDateValidator.php',
  456. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  457. 'CEmailValidator' => '/validators/CEmailValidator.php',
  458. 'CExistValidator' => '/validators/CExistValidator.php',
  459. 'CFileValidator' => '/validators/CFileValidator.php',
  460. 'CFilterValidator' => '/validators/CFilterValidator.php',
  461. 'CInlineValidator' => '/validators/CInlineValidator.php',
  462. 'CNumberValidator' => '/validators/CNumberValidator.php',
  463. 'CRangeValidator' => '/validators/CRangeValidator.php',
  464. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  465. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  466. 'CSafeValidator' => '/validators/CSafeValidator.php',
  467. 'CStringValidator' => '/validators/CStringValidator.php',
  468. 'CTypeValidator' => '/validators/CTypeValidator.php',
  469. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  470. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  471. 'CUrlValidator' => '/validators/CUrlValidator.php',
  472. 'CValidator' => '/validators/CValidator.php',
  473. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  474. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  475. 'CAssetManager' => '/web/CAssetManager.php',
  476. 'CBaseController' => '/web/CBaseController.php',
  477. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  478. 'CClientScript' => '/web/CClientScript.php',
  479. 'CController' => '/web/CController.php',
  480. 'CDataProvider' => '/web/CDataProvider.php',
  481. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  482. 'CExtController' => '/web/CExtController.php',
  483. 'CFormModel' => '/web/CFormModel.php',
  484. 'CHttpCookie' => '/web/CHttpCookie.php',
  485. 'CHttpRequest' => '/web/CHttpRequest.php',
  486. 'CHttpSession' => '/web/CHttpSession.php',
  487. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  488. 'COutputEvent' => '/web/COutputEvent.php',
  489. 'CPagination' => '/web/CPagination.php',
  490. 'CSort' => '/web/CSort.php',
  491. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  492. 'CTheme' => '/web/CTheme.php',
  493. 'CThemeManager' => '/web/CThemeManager.php',
  494. 'CUploadedFile' => '/web/CUploadedFile.php',
  495. 'CUrlManager' => '/web/CUrlManager.php',
  496. 'CWebApplication' => '/web/CWebApplication.php',
  497. 'CWebModule' => '/web/CWebModule.php',
  498. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  499. 'CAction' => '/web/actions/CAction.php',
  500. 'CInlineAction' => '/web/actions/CInlineAction.php',
  501. 'CViewAction' => '/web/actions/CViewAction.php',
  502. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  503. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  504. 'CAuthItem' => '/web/auth/CAuthItem.php',
  505. 'CAuthManager' => '/web/auth/CAuthManager.php',
  506. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  507. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  508. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  509. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  510. 'CWebUser' => '/web/auth/CWebUser.php',
  511. 'CFilter' => '/web/filters/CFilter.php',
  512. 'CFilterChain' => '/web/filters/CFilterChain.php',
  513. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  514. 'CForm' => '/web/form/CForm.php',
  515. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  516. 'CFormElement' => '/web/form/CFormElement.php',
  517. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  518. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  519. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  520. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  521. 'CHtml' => '/web/helpers/CHtml.php',
  522. 'CJSON' => '/web/helpers/CJSON.php',
  523. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  524. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  525. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  526. 'CWebService' => '/web/services/CWebService.php',
  527. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  528. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  529. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  530. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  531. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  532. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  533. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  534. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  535. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  536. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  537. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  538. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  539. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  540. 'COutputCache' => '/web/widgets/COutputCache.php',
  541. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  542. 'CStarRating' => '/web/widgets/CStarRating.php',
  543. 'CTabView' => '/web/widgets/CTabView.php',
  544. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  545. 'CTreeView' => '/web/widgets/CTreeView.php',
  546. 'CWidget' => '/web/widgets/CWidget.php',
  547. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  548. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  549. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  550. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  551. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  552. );
  553. }
  554. spl_autoload_register(array('YiiBase','autoload'));
  555. class Yii extends YiiBase
  556. {
  557. }
  558. class CComponent
  559. {
  560. private $_e;
  561. private $_m;
  562. public function __get($name)
  563. {
  564. $getter='get'.$name;
  565. if(method_exists($this,$getter))
  566. return $this->$getter();
  567. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  568. {
  569. // duplicating getEventHandlers() here for performance
  570. $name=strtolower($name);
  571. if(!isset($this->_e[$name]))
  572. $this->_e[$name]=new CList;
  573. return $this->_e[$name];
  574. }
  575. else if(isset($this->_m[$name]))
  576. return $this->_m[$name];
  577. else if(is_array($this->_m))
  578. {
  579. foreach($this->_m as $object)
  580. {
  581. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  582. return $object->$name;
  583. }
  584. }
  585. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  586. array('{class}'=>get_class($this), '{property}'=>$name)));
  587. }
  588. public function __set($name,$value)
  589. {
  590. $setter='set'.$name;
  591. if(method_exists($this,$setter))
  592. return $this->$setter($value);
  593. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  594. {
  595. // duplicating getEventHandlers() here for performance
  596. $name=strtolower($name);
  597. if(!isset($this->_e[$name]))
  598. $this->_e[$name]=new CList;
  599. return $this->_e[$name]->add($value);
  600. }
  601. else if(is_array($this->_m))
  602. {
  603. foreach($this->_m as $object)
  604. {
  605. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  606. return $object->$name=$value;
  607. }
  608. }
  609. if(method_exists($this,'get'.$name))
  610. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  611. array('{class}'=>get_class($this), '{property}'=>$name)));
  612. else
  613. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  614. array('{class}'=>get_class($this), '{property}'=>$name)));
  615. }
  616. public function __isset($name)
  617. {
  618. $getter='get'.$name;
  619. if(method_exists($this,$getter))
  620. return $this->$getter()!==null;
  621. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  622. {
  623. $name=strtolower($name);
  624. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  625. }
  626. else if(is_array($this->_m))
  627. {
  628. if(isset($this->_m[$name]))
  629. return true;
  630. foreach($this->_m as $object)
  631. {
  632. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  633. return $object->$name!==null;
  634. }
  635. }
  636. return false;
  637. }
  638. public function __unset($name)
  639. {
  640. $setter='set'.$name;
  641. if(method_exists($this,$setter))
  642. $this->$setter(null);
  643. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  644. unset($this->_e[strtolower($name)]);
  645. else if(is_array($this->_m))
  646. {
  647. if(isset($this->_m[$name]))
  648. $this->detachBehavior($name);
  649. else
  650. {
  651. foreach($this->_m as $object)
  652. {
  653. if($object->getEnabled())
  654. {
  655. if(property_exists($object,$name))
  656. return $object->$name=null;
  657. else if($object->canSetProperty($name))
  658. return $object->$setter(null);
  659. }
  660. }
  661. }
  662. }
  663. else if(method_exists($this,'get'.$name))
  664. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  665. array('{class}'=>get_class($this), '{property}'=>$name)));
  666. }
  667. public function __call($name,$parameters)
  668. {
  669. if($this->_m!==null)
  670. {
  671. foreach($this->_m as $object)
  672. {
  673. if($object->getEnabled() && method_exists($object,$name))
  674. return call_user_func_array(array($object,$name),$parameters);
  675. }
  676. }
  677. if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)
  678. return call_user_func_array($this->$name, $parameters);
  679. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  680. array('{class}'=>get_class($this), '{name}'=>$name)));
  681. }
  682. public function asa($behavior)
  683. {
  684. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  685. }
  686. public function attachBehaviors($behaviors)
  687. {
  688. foreach($behaviors as $name=>$behavior)
  689. $this->attachBehavior($name,$behavior);
  690. }
  691. public function detachBehaviors()
  692. {
  693. if($this->_m!==null)
  694. {
  695. foreach($this->_m as $name=>$behavior)
  696. $this->detachBehavior($name);
  697. $this->_m=null;
  698. }
  699. }
  700. public function attachBehavior($name,$behavior)
  701. {
  702. if(!($behavior instanceof IBehavior))
  703. $behavior=Yii::createComponent($behavior);
  704. $behavior->setEnabled(true);
  705. $behavior->attach($this);
  706. return $this->_m[$name]=$behavior;
  707. }
  708. public function detachBehavior($name)
  709. {
  710. if(isset($this->_m[$name]))
  711. {
  712. $this->_m[$name]->detach($this);
  713. $behavior=$this->_m[$name];
  714. unset($this->_m[$name]);
  715. return $behavior;
  716. }
  717. }
  718. public function enableBehaviors()
  719. {
  720. if($this->_m!==null)
  721. {
  722. foreach($this->_m as $behavior)
  723. $behavior->setEnabled(true);
  724. }
  725. }
  726. public function disableBehaviors()
  727. {
  728. if($this->_m!==null)
  729. {
  730. foreach($this->_m as $behavior)
  731. $behavior->setEnabled(false);
  732. }
  733. }
  734. public function enableBehavior($name)
  735. {
  736. if(isset($this->_m[$name]))
  737. $this->_m[$name]->setEnabled(true);
  738. }
  739. public function disableBehavior($name)
  740. {
  741. if(isset($this->_m[$name]))
  742. $this->_m[$name]->setEnabled(false);
  743. }
  744. public function hasProperty($name)
  745. {
  746. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  747. }
  748. public function canGetProperty($name)
  749. {
  750. return method_exists($this,'get'.$name);
  751. }
  752. public function canSetProperty($name)
  753. {
  754. return method_exists($this,'set'.$name);
  755. }
  756. public function hasEvent($name)
  757. {
  758. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  759. }
  760. public function hasEventHandler($name)
  761. {
  762. $name=strtolower($name);
  763. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  764. }
  765. public function getEventHandlers($name)
  766. {
  767. if($this->hasEvent($name))
  768. {
  769. $name=strtolower($name);
  770. if(!isset($this->_e[$name]))
  771. $this->_e[$name]=new CList;
  772. return $this->_e[$name];
  773. }
  774. else
  775. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  776. array('{class}'=>get_class($this), '{event}'=>$name)));
  777. }
  778. public function attachEventHandler($name,$handler)
  779. {
  780. $this->getEventHandlers($name)->add($handler);
  781. }
  782. public function detachEventHandler($name,$handler)
  783. {
  784. if($this->hasEventHandler($name))
  785. return $this->getEventHandlers($name)->remove($handler)!==false;
  786. else
  787. return false;
  788. }
  789. public function raiseEvent($name,$event)
  790. {
  791. $name=strtolower($name);
  792. if(isset($this->_e[$name]))
  793. {
  794. foreach($this->_e[$name] as $handler)
  795. {
  796. if(is_string($handler))
  797. call_user_func($handler,$event);
  798. else if(is_callable($handler,true))
  799. {
  800. if(is_array($handler))
  801. {
  802. // an array: 0 - object, 1 - method name
  803. list($object,$method)=$handler;
  804. if(is_string($object)) // static method call
  805. call_user_func($handler,$event);
  806. else if(method_exists($object,$method))
  807. $object->$method($event);
  808. else
  809. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  810. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  811. }
  812. else // PHP 5.3: anonymous function
  813. call_user_func($handler,$event);
  814. }
  815. else
  816. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  817. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  818. // stop further handling if param.handled is set true
  819. if(($event instanceof CEvent) && $event->handled)
  820. return;
  821. }
  822. }
  823. else if(YII_DEBUG && !$this->hasEvent($name))
  824. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  825. array('{class}'=>get_class($this), '{event}'=>$name)));
  826. }
  827. public function evaluateExpression($_expression_,$_data_=array())
  828. {
  829. if(is_string($_expression_))
  830. {
  831. extract($_data_);
  832. return eval('return '.$_expression_.';');
  833. }
  834. else
  835. {
  836. $_data_[]=$this;
  837. return call_user_func_array($_expression_, $_data_);
  838. }
  839. }
  840. }
  841. class CEvent extends CComponent
  842. {
  843. public $sender;
  844. public $handled=false;
  845. public $params;
  846. public function __construct($sender=null,$params=null)
  847. {
  848. $this->sender=$sender;
  849. $this->params=$params;
  850. }
  851. }
  852. class CEnumerable
  853. {
  854. }
  855. abstract class CModule extends CComponent
  856. {
  857. public $preload=array();
  858. public $behaviors=array();
  859. private $_id;
  860. private $_parentModule;
  861. private $_basePath;
  862. private $_modulePath;
  863. private $_params;
  864. private $_modules=array();
  865. private $_moduleConfig=array();
  866. private $_components=array();
  867. private $_componentConfig=array();
  868. public function __construct($id,$parent,$config=null)
  869. {
  870. $this->_id=$id;
  871. $this->_parentModule=$parent;
  872. // set basePath at early as possible to avoid trouble
  873. if(is_string($config))
  874. $config=require($config);
  875. if(isset($config['basePath']))
  876. {
  877. $this->setBasePath($config['basePath']);
  878. unset($config['basePath']);
  879. }
  880. Yii::setPathOfAlias($id,$this->getBasePath());
  881. $this->preinit();
  882. $this->configure($config);
  883. $this->attachBehaviors($this->behaviors);
  884. $this->preloadComponents();
  885. $this->init();
  886. }
  887. public function __get($name)
  888. {
  889. if($this->hasComponent($name))
  890. return $this->getComponent($name);
  891. else
  892. return parent::__get($name);
  893. }
  894. public function __isset($name)
  895. {
  896. if($this->hasComponent($name))
  897. return $this->getComponent($name)!==null;
  898. else
  899. return parent::__isset($name);
  900. }
  901. public function getId()
  902. {
  903. return $this->_id;
  904. }
  905. public function setId($id)
  906. {
  907. $this->_id=$id;
  908. }
  909. public function getBasePath()
  910. {
  911. if($this->_basePath===null)
  912. {
  913. $class=new ReflectionClass(get_class($this));
  914. $this->_basePath=dirname($class->getFileName());
  915. }
  916. return $this->_basePath;
  917. }
  918. public function setBasePath($path)
  919. {
  920. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  921. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  922. array('{path}'=>$path)));
  923. }
  924. public function getParams()
  925. {
  926. if($this->_params!==null)
  927. return $this->_params;
  928. else
  929. {
  930. $this->_params=new CAttributeCollection;
  931. $this->_params->caseSensitive=true;
  932. return $this->_params;
  933. }
  934. }
  935. public function setParams($value)
  936. {
  937. $params=$this->getParams();
  938. foreach($value as $k=>$v)
  939. $params->add($k,$v);
  940. }
  941. public function getModulePath()
  942. {
  943. if($this->_modulePath!==null)
  944. return $this->_modulePath;
  945. else
  946. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  947. }
  948. public function setModulePath($value)
  949. {
  950. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  951. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  952. array('{path}'=>$value)));
  953. }
  954. public function setImport($aliases)
  955. {
  956. foreach($aliases as $alias)
  957. Yii::import($alias);
  958. }
  959. public function setAliases($mappings)
  960. {
  961. foreach($mappings as $name=>$alias)
  962. {
  963. if(($path=Yii::getPathOfAlias($alias))!==false)
  964. Yii::setPathOfAlias($name,$path);
  965. else
  966. Yii::setPathOfAlias($name,$alias);
  967. }
  968. }
  969. public function getParentModule()
  970. {
  971. return $this->_parentModule;
  972. }
  973. public function getModule($id)
  974. {
  975. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  976. return $this->_modules[$id];
  977. else if(isset($this->_moduleConfig[$id]))
  978. {
  979. $config=$this->_moduleConfig[$id];
  980. if(!isset($config['enabled']) || $config['enabled'])
  981. {
  982. $class=$config['class'];
  983. unset($config['class'], $config['enabled']);
  984. if($this===Yii::app())
  985. $module=Yii::createComponent($class,$id,null,$config);
  986. else
  987. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  988. return $this->_modules[$id]=$module;
  989. }
  990. }
  991. }
  992. public function hasModule($id)
  993. {
  994. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  995. }
  996. public function getModules()
  997. {
  998. return $this->_moduleConfig;
  999. }
  1000. public function setModules($modules)
  1001. {
  1002. foreach($modules as $id=>$module)
  1003. {
  1004. if(is_int($id))
  1005. {
  1006. $id=$module;
  1007. $module=array();
  1008. }
  1009. if(!isset($module['class']))
  1010. {
  1011. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1012. $module['class']=$id.'.'.ucfirst($id).'Module';
  1013. }
  1014. if(isset($this->_moduleConfig[$id]))
  1015. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1016. else
  1017. $this->_moduleConfig[$id]=$module;
  1018. }
  1019. }
  1020. public function hasComponent($id)
  1021. {
  1022. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1023. }
  1024. public function getComponent($id,$createIfNull=true)
  1025. {
  1026. if(isset($this->_components[$id]))
  1027. return $this->_components[$id];
  1028. else if(isset($this->_componentConfig[$id]) && $createIfNull)
  1029. {
  1030. $config=$this->_componentConfig[$id];
  1031. if(!isset($config['enabled']) || $config['enabled'])
  1032. {
  1033. unset($config['enabled']);
  1034. $component=Yii::createComponent($config);
  1035. $component->init();
  1036. return $this->_components[$id]=$component;
  1037. }
  1038. }
  1039. }
  1040. public function setComponent($id,$component)
  1041. {
  1042. if($component===null)
  1043. unset($this->_components[$id]);
  1044. else
  1045. {
  1046. $this->_components[$id]=$component;
  1047. if(!$component->getIsInitialized())
  1048. $component->init();
  1049. }
  1050. }
  1051. public function getComponents($loadedOnly=true)
  1052. {
  1053. if($loadedOnly)
  1054. return $this->_components;
  1055. else
  1056. return array_merge($this->_componentConfig, $this->_components);
  1057. }
  1058. public function setComponents($components,$merge=true)
  1059. {
  1060. foreach($components as $id=>$component)
  1061. {
  1062. if($component instanceof IApplicationComponent)
  1063. $this->setComponent($id,$component);
  1064. else if(isset($this->_componentConfig[$id]) && $merge)
  1065. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1066. else
  1067. $this->_componentConfig[$id]=$component;
  1068. }
  1069. }
  1070. public function configure($config)
  1071. {
  1072. if(is_array($config))
  1073. {
  1074. foreach($config as $key=>$value)
  1075. $this->$key=$value;
  1076. }
  1077. }
  1078. protected function preloadComponents()
  1079. {
  1080. foreach($this->preload as $id)
  1081. $this->getComponent($id);
  1082. }
  1083. protected function preinit()
  1084. {
  1085. }
  1086. protected function init()
  1087. {
  1088. }
  1089. }
  1090. abstract class CApplication extends CModule
  1091. {
  1092. public $name='My Application';
  1093. public $charset='UTF-8';
  1094. public $sourceLanguage='en_us';
  1095. private $_id;
  1096. private $_basePath;
  1097. private $_runtimePath;
  1098. private $_extensionPath;
  1099. private $_globalState;
  1100. private $_stateChanged;
  1101. private $_ended=false;
  1102. private $_language;
  1103. private $_homeUrl;
  1104. abstract public function processRequest();
  1105. public function __construct($config=null)
  1106. {
  1107. Yii::setApplication($this);
  1108. // set basePath at early as possible to avoid trouble
  1109. if(is_string($config))
  1110. $config=require($config);
  1111. if(isset($config['basePath']))
  1112. {
  1113. $this->setBasePath($config['basePath']);
  1114. unset($config['basePath']);
  1115. }
  1116. else
  1117. $this->setBasePath('protected');
  1118. Yii::setPathOfAlias('application',$this->getBasePath());
  1119. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1120. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1121. $this->preinit();
  1122. $this->initSystemHandlers();
  1123. $this->registerCoreComponents();
  1124. $this->configure($config);
  1125. $this->attachBehaviors($this->behaviors);
  1126. $this->preloadComponents();
  1127. $this->init();
  1128. }
  1129. public function run()
  1130. {
  1131. if($this->hasEventHandler('onBeginRequest'))
  1132. $this->onBeginRequest(new CEvent($this));
  1133. $this->processRequest();
  1134. if($this->hasEventHandler('onEndRequest'))
  1135. $this->onEndRequest(new CEvent($this));
  1136. }
  1137. public function end($status=0, $exit=true)
  1138. {
  1139. if($this->hasEventHandler('onEndRequest'))
  1140. $this->onEndRequest(new CEvent($this));
  1141. if($exit)
  1142. exit($status);
  1143. }
  1144. public function onBeginRequest($event)
  1145. {
  1146. $this->raiseEvent('onBeginRequest',$event);
  1147. }
  1148. public function onEndRequest($event)
  1149. {
  1150. if(!$this->_ended)
  1151. {
  1152. $this->_ended=true;
  1153. $this->raiseEvent('onEndRequest',$event);
  1154. }
  1155. }
  1156. public function getId()
  1157. {
  1158. if($this->_id!==null)
  1159. return $this->_id;
  1160. else
  1161. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1162. }
  1163. public function setId($id)
  1164. {
  1165. $this->_id=$id;
  1166. }
  1167. public function getBasePath()
  1168. {
  1169. return $this->_basePath;
  1170. }
  1171. public function setBasePath($path)
  1172. {
  1173. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1174. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1175. array('{path}'=>$path)));
  1176. }
  1177. public function getRuntimePath()
  1178. {
  1179. if($this->_runtimePath!==null)
  1180. return $this->_runtimePath;
  1181. else
  1182. {
  1183. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1184. return $this->_runtimePath;
  1185. }
  1186. }
  1187. public function setRuntimePath($path)
  1188. {
  1189. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1190. throw new CException(Yii::t('yii','Application runtime path "{path}" is not valid. Please make sure it is a directory writable by the Web server process.',
  1191. array('{path}'=>$path)));
  1192. $this->_runtimePath=$runtimePath;
  1193. }
  1194. public function getExtensionPath()
  1195. {
  1196. return Yii::getPathOfAlias('ext');
  1197. }
  1198. public function setExtensionPath($path)
  1199. {
  1200. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1201. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1202. array('{path}'=>$path)));
  1203. Yii::setPathOfAlias('ext',$extensionPath);
  1204. }
  1205. public function getLanguage()
  1206. {
  1207. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1208. }
  1209. public function setLanguage($language)
  1210. {
  1211. $this->_language=$language;
  1212. }
  1213. public function getTimeZone()
  1214. {
  1215. return date_default_timezone_get();
  1216. }
  1217. public function setTimeZone($value)
  1218. {
  1219. date_default_timezone_set($value);
  1220. }
  1221. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1222. {
  1223. if($srcLanguage===null)
  1224. $srcLanguage=$this->sourceLanguage;
  1225. if($language===null)
  1226. $language=$this->getLanguage();
  1227. if($language===$srcLanguage)
  1228. return $srcFile;
  1229. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1230. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1231. }
  1232. public function getLocale($localeID=null)
  1233. {
  1234. return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID);
  1235. }
  1236. public function getLocaleDataPath()
  1237. {
  1238. return CLocale::$dataPath===null ? Yii::getPathOfAlias('system.i18n.data') : CLocale::$dataPath;
  1239. }
  1240. public function setLocaleDataPath($value)
  1241. {
  1242. CLocale::$dataPath=$value;
  1243. }
  1244. public function getNumberFormatter()
  1245. {
  1246. return $this->getLocale()->getNumberFormatter();
  1247. }
  1248. public function getDateFormatter()
  1249. {
  1250. return $this->getLocale()->getDateFormatter();
  1251. }
  1252. public function getDb()
  1253. {
  1254. return $this->getComponent('db');
  1255. }
  1256. public function getErrorHandler()
  1257. {
  1258. return $this->getComponent('errorHandler');
  1259. }
  1260. public function getSecurityManager()
  1261. {
  1262. return $this->getComponent('securityManager');
  1263. }
  1264. public function getStatePersister()
  1265. {
  1266. return $this->getComponent('statePersister');
  1267. }
  1268. public function getCache()
  1269. {
  1270. return $this->getComponent('cache');
  1271. }
  1272. public function getCoreMessages()
  1273. {
  1274. return $this->getComponent('coreMessages');
  1275. }
  1276. public function getMessages()
  1277. {
  1278. return $this->getComponent('messages');
  1279. }
  1280. public function getRequest()
  1281. {
  1282. return $this->getComponent('request');
  1283. }
  1284. public function getUrlManager()
  1285. {
  1286. return $this->getComponent('urlManager');
  1287. }
  1288. public function getController()
  1289. {
  1290. return null;
  1291. }
  1292. public function createUrl($route,$params=array(),$ampersand='&')
  1293. {
  1294. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1295. }
  1296. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1297. {
  1298. $url=$this->createUrl($route,$params,$ampersand);
  1299. if(strpos($url,'http')===0)
  1300. return $url;
  1301. else
  1302. return $this->getRequest()->getHostInfo($schema).$url;
  1303. }
  1304. public function getBaseUrl($absolute=false)
  1305. {
  1306. return $this->getRequest()->getBaseUrl($absolute);
  1307. }
  1308. public function getHomeUrl()
  1309. {
  1310. if($this->_homeUrl===null)
  1311. {
  1312. if($this->getUrlManager()->showScriptName)
  1313. return $this->getRequest()->getScriptUrl();
  1314. else
  1315. return $this->getRequest()->getBaseUrl().'/';
  1316. }
  1317. else
  1318. return $this->_homeUrl;
  1319. }
  1320. public function setHomeUrl($value)
  1321. {
  1322. $this->_homeUrl=$value;
  1323. }
  1324. public function getGlobalState($key,$defaultValue=null)
  1325. {
  1326. if($this->_globalState===null)
  1327. $this->loadGlobalState();
  1328. if(isset($this->_globalState[$key]))
  1329. return $this->_globalState[$key];
  1330. else
  1331. return $defaultValue;
  1332. }
  1333. public function setGlobalState($key,$value,$defaultValue=null)
  1334. {
  1335. if($this->_globalState===null)
  1336. $this->loadGlobalState();
  1337. $changed=$this->_stateChanged;
  1338. if($value===$defaultValue)
  1339. {
  1340. if(isset($this->_globalState[$key]))
  1341. {
  1342. unset($this->_globalState[$key]);
  1343. $this->_stateChanged=true;
  1344. }
  1345. }
  1346. else if(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1347. {
  1348. $this->_globalState[$key]=$value;
  1349. $this->_stateChanged=true;
  1350. }
  1351. if($this->_stateChanged!==$changed)
  1352. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1353. }
  1354. public function clearGlobalState($key)
  1355. {
  1356. $this->setGlobalState($key,true,true);
  1357. }
  1358. public function loadGlobalState()
  1359. {
  1360. $persister=$this->getStatePersister();
  1361. if(($this->_globalState=$persister->load())===null)
  1362. $this->_globalState=array();
  1363. $this->_stateChanged=false;
  1364. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1365. }
  1366. public function saveGlobalState()
  1367. {
  1368. if($this->_stateChanged)
  1369. {
  1370. $this->_stateChanged=false;
  1371. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1372. $this->getStatePersister()->save($this->_globalState);
  1373. }
  1374. }
  1375. public function handleException($exception)
  1376. {
  1377. // disable error capturing to avoid recursive errors
  1378. restore_error_handler();
  1379. restore_exception_handler();
  1380. $category='exception.'.get_class($exception);
  1381. if($exception instanceof CHttpException)
  1382. $category.='.'.$exception->statusCode;
  1383. // php <5.2 doesn't support string conversion auto-magically
  1384. $message=$exception->__toString();
  1385. if(isset($_SERVER['REQUEST_URI']))
  1386. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  1387. if(isset($_SERVER['HTTP_REFERER']))
  1388. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  1389. $message.="\n---";
  1390. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1391. try
  1392. {
  1393. $event=new CExceptionEvent($this,$exception);
  1394. $this->onException($event);
  1395. if(!$event->handled)
  1396. {
  1397. // try an error handler
  1398. if(($handler=$this->getErrorHandler())!==null)
  1399. $handler->handle($event);
  1400. else
  1401. $this->displayException($exception);
  1402. }
  1403. }
  1404. catch(Exception $e)
  1405. {
  1406. $this->displayException($e);
  1407. }
  1408. try
  1409. {
  1410. $this->end(1);
  1411. }
  1412. catch(Exception $e)
  1413. {
  1414. // use the most primitive way to log error
  1415. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1416. $msg .= $e->getTraceAsString()."\n";
  1417. $msg .= "Previous exception:\n";
  1418. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1419. $msg .= $exception->getTraceAsString()."\n";
  1420. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1421. error_log($msg);
  1422. exit(1);
  1423. }
  1424. }
  1425. public function handleError($code,$message,$file,$line)
  1426. {
  1427. if($code & error_reporting())
  1428. {
  1429. // disable error capturing to avoid recursive errors
  1430. restore_error_handler();
  1431. restore_exception_handler();
  1432. $log="$message ($file:$line)\nStack trace:\n";
  1433. $trace=debug_backtrace();
  1434. // skip the first 3 stacks as they do not tell the error position
  1435. if(count($trace)>3)
  1436. $trace=array_slice($trace,3);
  1437. foreach($trace as $i=>$t)
  1438. {
  1439. if(!isset($t['file']))
  1440. $t['file']='unknown';
  1441. if(!isset($t['line']))
  1442. $t['line']=0;
  1443. if(!isset($t['function']))
  1444. $t['function']='unknown';
  1445. $log.="#$i {$t['file']}({$t['line']}): ";
  1446. if(isset($t['object']) && is_object($t['object']))
  1447. $log.=get_class($t['object']).'->';
  1448. $log.="{$t['function']}()\n";
  1449. }
  1450. if(isset($_SERVER['REQUEST_URI']))
  1451. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1452. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1453. try
  1454. {
  1455. Yii::import('CErrorEvent',true);
  1456. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1457. $this->onError($event);
  1458. if(!$event->handled)
  1459. {
  1460. // try an error handler
  1461. if(($handler=$this->getErrorHandler())!==null)
  1462. $handler->handle($event);
  1463. else
  1464. $this->displayError($code,$message,$file,$line);
  1465. }
  1466. }
  1467. catch(Exception $e)
  1468. {
  1469. $this->displayException($e);
  1470. }
  1471. try
  1472. {
  1473. $this->end(1);
  1474. }
  1475. catch(Exception $e)
  1476. {
  1477. // use the most primitive way to log error
  1478. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1479. $msg .= $e->getTraceAsString()."\n";
  1480. $msg .= "Previous error:\n";
  1481. $msg .= $log."\n";
  1482. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1483. error_log($msg);
  1484. exit(1);
  1485. }
  1486. }
  1487. }
  1488. public function onException($event)
  1489. {
  1490. $this->raiseEvent('onException',$event);
  1491. }
  1492. public function onError($event)
  1493. {
  1494. $this->raiseEvent('onError',$event);
  1495. }
  1496. public function displayError($code,$message,$file,$line)
  1497. {
  1498. if(YII_DEBUG)
  1499. {
  1500. echo "<h1>PHP Error [$code]</h1>\n";
  1501. echo "<p>$message ($file:$line)</p>\n";
  1502. echo '<pre>';
  1503. $trace=debug_backtrace();
  1504. // skip the first 3 stacks as they do not tell the error position
  1505. if(count($trace)>3)
  1506. $trace=array_slice($trace,3);
  1507. foreach($trace as $i=>$t)
  1508. {
  1509. if(!isset($t['file']))
  1510. $t['file']='unknown';
  1511. if(!isset($t['line']))
  1512. $t['line']=0;
  1513. if(!isset($t['function']))
  1514. $t['function']='unknown';
  1515. echo "#$i {$t['file']}({$t['line']}): ";
  1516. if(isset($t['object']) && is_object($t['object']))
  1517. echo get_class($t['object']).'->';
  1518. echo "{$t['function']}()\n";
  1519. }
  1520. echo '</pre>';
  1521. }
  1522. else
  1523. {
  1524. echo "<h1>PHP Error [$code]</h1>\n";
  1525. echo "<p>$message</p>\n";
  1526. }
  1527. }
  1528. public function displayException($exception)
  1529. {
  1530. if(YII_DEBUG)
  1531. {
  1532. echo '<h1>'.get_class($exception)."</h1>\n";
  1533. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1534. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1535. }
  1536. else
  1537. {
  1538. echo '<h1>'.get_class($exception)."</h1>\n";
  1539. echo '<p>'.$exception->getMessage().'</p>';
  1540. }
  1541. }
  1542. protected function initSystemHandlers()
  1543. {
  1544. if(YII_ENABLE_EXCEPTION_HANDLER)
  1545. set_exception_handler(array($this,'handleException'));
  1546. if(YII_ENABLE_ERROR_HANDLER)
  1547. set_error_handler(array($this,'handleError'),error_reporting());
  1548. }
  1549. protected function registerCoreComponents()
  1550. {
  1551. $components=array(
  1552. 'coreMessages'=>array(
  1553. 'class'=>'CPhpMessageSource',
  1554. 'language'=>'en_us',
  1555. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1556. ),
  1557. 'db'=>array(
  1558. 'class'=>'CDbConnection',
  1559. ),
  1560. 'messages'=>array(
  1561. 'class'=>'CPhpMessageSource',
  1562. ),
  1563. 'errorHandler'=>array(
  1564. 'class'=>'CErrorHandler',
  1565. ),
  1566. 'securityManager'=>array(
  1567. 'class'=>'CSecurityManager',
  1568. ),
  1569. 'statePersister'=>array(
  1570. 'class'=>'CStatePersister',
  1571. ),
  1572. 'urlManager'=>array(
  1573. 'class'=>'CUrlManager',
  1574. ),
  1575. 'request'=>array(
  1576. 'class'=>'CHttpRequest',
  1577. ),
  1578. 'format'=>array(
  1579. 'class'=>'CFormatter',
  1580. ),
  1581. );
  1582. $this->setComponents($components);
  1583. }
  1584. }
  1585. class CWebApplication extends CApplication
  1586. {
  1587. public $defaultController='site';
  1588. public $layout='main';
  1589. public $controllerMap=array();
  1590. public $catchAllRequest;
  1591. private $_controllerPath;
  1592. private $_viewPath;
  1593. private $_systemViewPath;
  1594. private $_layoutPath;
  1595. private $_controller;
  1596. private $_theme;
  1597. public function processRequest()
  1598. {
  1599. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1600. {
  1601. $route=$this->catchAllRequest[0];
  1602. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1603. $_GET[$name]=$value;
  1604. }
  1605. else
  1606. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1607. $this->runController($route);
  1608. }
  1609. protected function registerCoreComponents()
  1610. {
  1611. parent::registerCoreComponents();
  1612. $components=array(
  1613. 'session'=>array(
  1614. 'class'=>'CHttpSession',
  1615. ),
  1616. 'assetManager'=>array(
  1617. 'class'=>'CAssetManager',
  1618. ),
  1619. 'user'=>array(
  1620. 'class'=>'CWebUser',
  1621. ),
  1622. 'themeManager'=>array(
  1623. 'class'=>'CThemeManager',
  1624. ),
  1625. 'authManager'=>array(
  1626. 'class'=>'CPhpAuthManager',
  1627. ),
  1628. 'clientScript'=>array(
  1629. 'class'=>'CClientScript',
  1630. ),
  1631. 'widgetFactory'=>array(
  1632. 'class'=>'CWidgetFactory',
  1633. ),
  1634. );
  1635. $this->setComponents($components);
  1636. }
  1637. public function getAuthManager()
  1638. {
  1639. return $this->getComponent('authManager');
  1640. }
  1641. public function getAssetManager()
  1642. {
  1643. return $this->getComponent('assetManager');
  1644. }
  1645. public function getSession()
  1646. {
  1647. return $this->getComponent('session');
  1648. }
  1649. public function getUser()
  1650. {
  1651. return $this->getComponent('user');
  1652. }
  1653. public function getViewRenderer()
  1654. {
  1655. return $this->getComponent('viewRenderer');
  1656. }
  1657. public function getClientScript()
  1658. {
  1659. return $this->getComponent('clientScript');
  1660. }
  1661. public function getWidgetFactory()
  1662. {
  1663. return $this->getComponent('widgetFactory');
  1664. }
  1665. public function getThemeManager()
  1666. {
  1667. return $this->getComponent('themeManager');
  1668. }
  1669. public function getTheme()
  1670. {
  1671. if(is_string($this->_theme))
  1672. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1673. return $this->_theme;
  1674. }
  1675. public function setTheme($value)
  1676. {
  1677. $this->_theme=$value;
  1678. }
  1679. public function runController($route)
  1680. {
  1681. if(($ca=$this->createController($route))!==null)
  1682. {
  1683. list($controller,$actionID)=$ca;
  1684. $oldController=$this->_controller;
  1685. $this->_controller=$controller;
  1686. $controller->init();
  1687. $controller->run($actionID);
  1688. $this->_controller=$oldController;
  1689. }
  1690. else
  1691. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1692. array('{route}'=>$route===''?$this->defaultController:$route)));
  1693. }
  1694. public function createController($route,$owner=null)
  1695. {
  1696. if($owner===null)
  1697. $owner=$this;
  1698. if(($route=trim($route,'/'))==='')
  1699. $route=$owner->defaultController;
  1700. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1701. $route.='/';
  1702. while(($pos=strpos($route,'/'))!==false)
  1703. {
  1704. $id=substr($route,0,$pos);
  1705. if(!preg_match('/^\w+$/',$id))
  1706. return null;
  1707. if(!$caseSensitive)
  1708. $id=strtolower($id);
  1709. $route=(string)substr($route,$pos+1);
  1710. if(!isset($basePath)) // first segment
  1711. {
  1712. if(isset($owner->controllerMap[$id]))
  1713. {
  1714. return array(
  1715. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1716. $this->parseActionParams($route),
  1717. );
  1718. }
  1719. if(($module=$owner->getModule($id))!==null)
  1720. return $this->createController($route,$module);
  1721. $basePath=$owner->getControllerPath();
  1722. $controllerID='';
  1723. }
  1724. else
  1725. $controllerID.='/';
  1726. $className=ucfirst($id).'Controller';
  1727. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1728. if(is_file($classFile))
  1729. {
  1730. if(!class_exists($className,false))
  1731. require($classFile);
  1732. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1733. {
  1734. $id[0]=strtolower($id[0]);
  1735. return array(
  1736. new $className($controllerID.$id,$owner===$this?null:$owner),
  1737. $this->parseActionParams($route),
  1738. );
  1739. }
  1740. return null;
  1741. }
  1742. $controllerID.=$id;
  1743. $basePath.=DIRECTORY_SEPARATOR.$id;
  1744. }
  1745. }
  1746. protected function parseActionParams($pathInfo)
  1747. {
  1748. if(($pos=strpos($pathInfo,'/'))!==false)
  1749. {
  1750. $manager=$this->getUrlManager();
  1751. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1752. $actionID=substr($pathInfo,0,$pos);
  1753. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1754. }
  1755. else
  1756. return $pathInfo;
  1757. }
  1758. public function getController()
  1759. {
  1760. return $this->_controller;
  1761. }
  1762. public function setController($value)
  1763. {
  1764. $this->_controller=$value;
  1765. }
  1766. public function getControllerPath()
  1767. {
  1768. if($this->_controllerPath!==null)
  1769. return $this->_controllerPath;
  1770. else
  1771. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1772. }
  1773. public function setControllerPath($value)
  1774. {
  1775. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1776. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1777. array('{path}'=>$value)));
  1778. }
  1779. public function getViewPath()
  1780. {
  1781. if($this->_viewPath!==null)
  1782. return $this->_viewPath;
  1783. else
  1784. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1785. }
  1786. public function setViewPath($path)
  1787. {
  1788. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1789. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1790. array('{path}'=>$path)));
  1791. }
  1792. public function getSystemViewPath()
  1793. {
  1794. if($this->_systemViewPath!==null)
  1795. return $this->_systemViewPath;
  1796. else
  1797. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1798. }
  1799. public function setSystemViewPath($path)
  1800. {
  1801. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1802. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1803. array('{path}'=>$path)));
  1804. }
  1805. public function getLayoutPath()
  1806. {
  1807. if($this->_layoutPath!==null)
  1808. return $this->_layoutPath;
  1809. else
  1810. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1811. }
  1812. public function setLayoutPath($path)
  1813. {
  1814. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1815. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1816. array('{path}'=>$path)));
  1817. }
  1818. public function beforeControllerAction($controller,$action)
  1819. {
  1820. return true;
  1821. }
  1822. public function afterControllerAction($controller,$action)
  1823. {
  1824. }
  1825. public function findModule($id)
  1826. {
  1827. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1828. {
  1829. do
  1830. {
  1831. if(($m=$module->getModule($id))!==null)
  1832. return $m;
  1833. } while(($module=$module->getParentModule())!==null);
  1834. }
  1835. if(($m=$this->getModule($id))!==null)
  1836. return $m;
  1837. }
  1838. protected function init()
  1839. {
  1840. parent::init();
  1841. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1842. $this->getRequest();
  1843. }
  1844. }
  1845. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1846. {
  1847. private $_d=array();
  1848. private $_r=false;
  1849. public function __construct($data=null,$readOnly=false)
  1850. {
  1851. if($data!==null)
  1852. $this->copyFrom($data);
  1853. $this->setReadOnly($readOnly);
  1854. }
  1855. public function getReadOnly()
  1856. {
  1857. return $this->_r;
  1858. }
  1859. protected function setReadOnly($value)
  1860. {
  1861. $this->_r=$value;
  1862. }
  1863. public function getIterator()
  1864. {
  1865. return new CMapIterator($this->_d);
  1866. }
  1867. public function count()
  1868. {
  1869. return $this->getCount();
  1870. }
  1871. public function getCount()
  1872. {
  1873. return count($this->_d);
  1874. }
  1875. public function getKeys()
  1876. {
  1877. return array_keys($this->_d);
  1878. }
  1879. public function itemAt($key)
  1880. {
  1881. if(isset($this->_d[$key]))
  1882. return $this->_d[$key];
  1883. else
  1884. return null;
  1885. }
  1886. public function add($key,$value)
  1887. {
  1888. if(!$this->_r)
  1889. {
  1890. if($key===null)
  1891. $this->_d[]=$value;
  1892. else
  1893. $this->_d[$key]=$value;
  1894. }
  1895. else
  1896. throw new CException(Yii::t('yii','The map is read only.'));
  1897. }
  1898. public function remove($key)
  1899. {
  1900. if(!$this->_r)
  1901. {
  1902. if(isset($this->_d[$key]))
  1903. {
  1904. $value=$this->_d[$key];
  1905. unset($this->_d[$key]);
  1906. return $value;
  1907. }
  1908. else
  1909. {
  1910. // it is possible the value is null, which is not detected by isset
  1911. unset($this->_d[$key]);
  1912. return null;
  1913. }
  1914. }
  1915. else
  1916. throw new CException(Yii::t('yii','The map is read only.'));
  1917. }
  1918. public function clear()
  1919. {
  1920. foreach(array_keys($this->_d) as $key)
  1921. $this->remove($key);
  1922. }
  1923. public function contains($key)
  1924. {
  1925. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  1926. }
  1927. public function toArray()
  1928. {
  1929. return $this->_d;
  1930. }
  1931. public function copyFrom($data)
  1932. {
  1933. if(is_array($data) || $data instanceof Traversable)
  1934. {
  1935. if($this->getCount()>0)
  1936. $this->clear();
  1937. if($data instanceof CMap)
  1938. $data=$data->_d;
  1939. foreach($data as $key=>$value)
  1940. $this->add($key,$value);
  1941. }
  1942. else if($data!==null)
  1943. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1944. }
  1945. public function mergeWith($data,$recursive=true)
  1946. {
  1947. if(is_array($data) || $data instanceof Traversable)
  1948. {
  1949. if($data instanceof CMap)
  1950. $data=$data->_d;
  1951. if($recursive)
  1952. {
  1953. if($data instanceof Traversable)
  1954. {
  1955. $d=array();
  1956. foreach($data as $key=>$value)
  1957. $d[$key]=$value;
  1958. $this->_d=self::mergeArray($this->_d,$d);
  1959. }
  1960. else
  1961. $this->_d=self::mergeArray($this->_d,$data);
  1962. }
  1963. else
  1964. {
  1965. foreach($data as $key=>$value)
  1966. $this->add($key,$value);
  1967. }
  1968. }
  1969. else if($data!==null)
  1970. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1971. }
  1972. public static function mergeArray($a,$b)
  1973. {
  1974. $args=func_get_args();
  1975. $res=array_shift($args);
  1976. while(!empty($args))
  1977. {
  1978. $next=array_shift($args);
  1979. foreach($next as $k => $v)
  1980. {
  1981. if(is_integer($k))
  1982. isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
  1983. else if(is_array($v) && isset($res[$k]) && is_array($res[$k]))
  1984. $res[$k]=self::mergeArray($res[$k],$v);
  1985. else
  1986. $res[$k]=$v;
  1987. }
  1988. }
  1989. return $res;
  1990. }
  1991. public function offsetExists($offset)
  1992. {
  1993. return $this->contains($offset);
  1994. }
  1995. public function offsetGet($offset)
  1996. {
  1997. return $this->itemAt($offset);
  1998. }
  1999. public function offsetSet($offset,$item)
  2000. {
  2001. $this->add($offset,$item);
  2002. }
  2003. public function offsetUnset($offset)
  2004. {
  2005. $this->remove($offset);
  2006. }
  2007. }
  2008. class CLogger extends CComponent
  2009. {
  2010. const LEVEL_TRACE='trace';
  2011. const LEVEL_WARNING='warning';
  2012. const LEVEL_ERROR='error';
  2013. const LEVEL_INFO='info';
  2014. const LEVEL_PROFILE='profile';
  2015. public $autoFlush=10000;
  2016. public $autoDump=false;
  2017. private $_logs=array();
  2018. private $_logCount=0;
  2019. private $_levels;
  2020. private $_categories;
  2021. private $_timings;
  2022. private $_processing = false;
  2023. public function log($message,$level='info',$category='application')
  2024. {
  2025. $this->_logs[]=array($message,$level,$category,microtime(true));
  2026. $this->_logCount++;
  2027. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
  2028. {
  2029. $this->_processing=true;
  2030. $this->flush($this->autoDump);
  2031. $this->_processing=false;
  2032. }
  2033. }
  2034. public function getLogs($levels='',$categories='')
  2035. {
  2036. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2037. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2038. if(empty($levels) && empty($categories))
  2039. return $this->_logs;
  2040. else if(empty($levels))
  2041. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByCategory'))));
  2042. else if(empty($categories))
  2043. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  2044. else
  2045. {
  2046. $ret=array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  2047. return array_values(array_filter(array_filter($ret,array($this,'filterByCategory'))));
  2048. }
  2049. }
  2050. private function filterByCategory($value)
  2051. {
  2052. foreach($this->_categories as $category)
  2053. {
  2054. $cat=strtolower($value[2]);
  2055. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2056. return $value;
  2057. }
  2058. return false;
  2059. }
  2060. private function filterByLevel($value)
  2061. {
  2062. return in_array(strtolower($value[1]),$this->_levels)?$value:false;
  2063. }
  2064. public function getExecutionTime()
  2065. {
  2066. return microtime(true)-YII_BEGIN_TIME;
  2067. }
  2068. public function getMemoryUsage()
  2069. {
  2070. if(function_exists('memory_get_usage'))
  2071. return memory_get_usage();
  2072. else
  2073. {
  2074. $output=array();
  2075. if(strncmp(PHP_OS,'WIN',3)===0)
  2076. {
  2077. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2078. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2079. }
  2080. else
  2081. {
  2082. $pid=getmypid();
  2083. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2084. $output=explode(" ",$output[0]);
  2085. return isset($output[1]) ? $output[1]*1024 : 0;
  2086. }
  2087. }
  2088. }
  2089. public function getProfilingResults($token=null,$category=null,$refresh=false)
  2090. {
  2091. if($this->_timings===null || $refresh)
  2092. $this->calculateTimings();
  2093. if($token===null && $category===null)
  2094. return $this->_timings;
  2095. $results=array();
  2096. foreach($this->_timings as $timing)
  2097. {
  2098. if(($category===null || $timing[1]===$category) && ($token===null || $timing[0]===$token))
  2099. $results[]=$timing[2];
  2100. }
  2101. return $results;
  2102. }
  2103. private function calculateTimings()
  2104. {
  2105. $this->_timings=array();
  2106. $stack=array();
  2107. foreach($this->_logs as $log)
  2108. {
  2109. if($log[1]!==CLogger::LEVEL_PROFILE)
  2110. continue;
  2111. list($message,$level,$category,$timestamp)=$log;
  2112. if(!strncasecmp($message,'begin:',6))
  2113. {
  2114. $log[0]=substr($message,6);
  2115. $stack[]=$log;
  2116. }
  2117. else if(!strncasecmp($message,'end:',4))
  2118. {
  2119. $token=substr($message,4);
  2120. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2121. {
  2122. $delta=$log[3]-$last[3];
  2123. $this->_timings[]=array($message,$category,$delta);
  2124. }
  2125. else
  2126. throw new CException(Yii::t('yii','CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.',
  2127. array('{token}'=>$token)));
  2128. }
  2129. }
  2130. $now=microtime(true);
  2131. while(($last=array_pop($stack))!==null)
  2132. {
  2133. $delta=$now-$last[3];
  2134. $this->_timings[]=array($last[0],$last[2],$delta);
  2135. }
  2136. }
  2137. public function flush($dumpLogs=false)
  2138. {
  2139. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2140. $this->_logs=array();
  2141. $this->_logCount=0;
  2142. }
  2143. public function onFlush($event)
  2144. {
  2145. $this->raiseEvent('onFlush', $event);
  2146. }
  2147. }
  2148. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2149. {
  2150. public $behaviors=array();
  2151. private $_initialized=false;
  2152. public function init()
  2153. {
  2154. $this->attachBehaviors($this->behaviors);
  2155. $this->_initialized=true;
  2156. }
  2157. public function getIsInitialized()
  2158. {
  2159. return $this->_initialized;
  2160. }
  2161. }
  2162. class CHttpRequest extends CApplicationComponent
  2163. {
  2164. public $enableCookieValidation=false;
  2165. public $enableCsrfValidation=false;
  2166. public $csrfTokenName='YII_CSRF_TOKEN';
  2167. public $csrfCookie;
  2168. private $_requestUri;
  2169. private $_pathInfo;
  2170. private $_scriptFile;
  2171. private $_scriptUrl;
  2172. private $_hostInfo;
  2173. private $_baseUrl;
  2174. private $_cookies;
  2175. private $_preferredLanguage;
  2176. private $_csrfToken;
  2177. private $_deleteParams;
  2178. private $_putParams;
  2179. public function init()
  2180. {
  2181. parent::init();
  2182. $this->normalizeRequest();
  2183. }
  2184. protected function normalizeRequest()
  2185. {
  2186. // normalize request
  2187. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2188. {
  2189. if(isset($_GET))
  2190. $_GET=$this->stripSlashes($_GET);
  2191. if(isset($_POST))
  2192. $_POST=$this->stripSlashes($_POST);
  2193. if(isset($_REQUEST))
  2194. $_REQUEST=$this->stripSlashes($_REQUEST);
  2195. if(isset($_COOKIE))
  2196. $_COOKIE=$this->stripSlashes($_COOKIE);
  2197. }
  2198. if($this->enableCsrfValidation)
  2199. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2200. }
  2201. public function stripSlashes(&$data)
  2202. {
  2203. return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
  2204. }
  2205. public function getParam($name,$defaultValue=null)
  2206. {
  2207. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2208. }
  2209. public function getQuery($name,$defaultValue=null)
  2210. {
  2211. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2212. }
  2213. public function getPost($name,$defaultValue=null)
  2214. {
  2215. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2216. }
  2217. public function getDelete($name,$defaultValue=null)
  2218. {
  2219. if($this->_deleteParams===null)
  2220. $this->_deleteParams=$this->getIsDeleteRequest() ? $this->getRestParams() : array();
  2221. return isset($this->_deleteParams[$name]) ? $this->_deleteParams[$name] : $defaultValue;
  2222. }
  2223. public function getPut($name,$defaultValue=null)
  2224. {
  2225. if($this->_putParams===null)
  2226. $this->_putParams=$this->getIsPutRequest() ? $this->getRestParams() : array();
  2227. return isset($this->_putParams[$name]) ? $this->_putParams[$name] : $defaultValue;
  2228. }
  2229. protected function getRestParams()
  2230. {
  2231. $result=array();
  2232. if(function_exists('mb_parse_str'))
  2233. mb_parse_str(file_get_contents('php://input'), $result);
  2234. else
  2235. parse_str(file_get_contents('php://input'), $result);
  2236. return $result;
  2237. }
  2238. public function getUrl()
  2239. {
  2240. return $this->getRequestUri();
  2241. }
  2242. public function getHostInfo($schema='')
  2243. {
  2244. if($this->_hostInfo===null)
  2245. {
  2246. if($secure=$this->getIsSecureConnection())
  2247. $http='https';
  2248. else
  2249. $http='http';
  2250. if(isset($_SERVER['HTTP_HOST']))
  2251. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2252. else
  2253. {
  2254. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2255. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2256. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2257. $this->_hostInfo.=':'.$port;
  2258. }
  2259. }
  2260. if($schema!=='')
  2261. {
  2262. $secure=$this->getIsSecureConnection();
  2263. if($secure && $schema==='https' || !$secure && $schema==='http')
  2264. return $this->_hostInfo;
  2265. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2266. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2267. $port=':'.$port;
  2268. else
  2269. $port='';
  2270. $pos=strpos($this->_hostInfo,':');
  2271. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2272. }
  2273. else
  2274. return $this->_hostInfo;
  2275. }
  2276. public function setHostInfo($value)
  2277. {
  2278. $this->_hostInfo=rtrim($value,'/');
  2279. }
  2280. public function getBaseUrl($absolute=false)
  2281. {
  2282. if($this->_baseUrl===null)
  2283. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2284. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2285. }
  2286. public function setBaseUrl($value)
  2287. {
  2288. $this->_baseUrl=$value;
  2289. }
  2290. public function getScriptUrl()
  2291. {
  2292. if($this->_scriptUrl===null)
  2293. {
  2294. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2295. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2296. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2297. else if(basename($_SERVER['PHP_SELF'])===$scriptName)
  2298. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2299. else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2300. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2301. else if(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2302. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2303. else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2304. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2305. else
  2306. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2307. }
  2308. return $this->_scriptUrl;
  2309. }
  2310. public function setScriptUrl($value)
  2311. {
  2312. $this->_scriptUrl='/'.trim($value,'/');
  2313. }
  2314. public function getPathInfo()
  2315. {
  2316. if($this->_pathInfo===null)
  2317. {
  2318. $pathInfo=$this->getRequestUri();
  2319. if(($pos=strpos($pathInfo,'?'))!==false)
  2320. $pathInfo=substr($pathInfo,0,$pos);
  2321. $pathInfo=$this->decodePathInfo($pathInfo);
  2322. $scriptUrl=$this->getScriptUrl();
  2323. $baseUrl=$this->getBaseUrl();
  2324. if(strpos($pathInfo,$scriptUrl)===0)
  2325. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2326. else if($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2327. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2328. else if(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2329. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2330. else
  2331. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2332. $this->_pathInfo=trim($pathInfo,'/');
  2333. }
  2334. return $this->_pathInfo;
  2335. }
  2336. protected function decodePathInfo($pathInfo)
  2337. {
  2338. $pathInfo = urldecode($pathInfo);
  2339. // is it UTF-8?
  2340. // http://w3.org/International/questions/qa-forms-utf-8.html
  2341. if(preg_match('%^(?:
  2342. [\x09\x0A\x0D\x20-\x7E] # ASCII
  2343. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  2344. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  2345. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  2346. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  2347. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  2348. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  2349. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  2350. )*$%xs', $pathInfo))
  2351. {
  2352. return $pathInfo;
  2353. }
  2354. else
  2355. {
  2356. return utf8_encode($pathInfo);
  2357. }
  2358. }
  2359. public function getRequestUri()
  2360. {
  2361. if($this->_requestUri===null)
  2362. {
  2363. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2364. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2365. else if(isset($_SERVER['REQUEST_URI']))
  2366. {
  2367. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2368. if(!empty($_SERVER['HTTP_HOST']))
  2369. {
  2370. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2371. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2372. }
  2373. else
  2374. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2375. }
  2376. else if(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2377. {
  2378. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2379. if(!empty($_SERVER['QUERY_STRING']))
  2380. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2381. }
  2382. else
  2383. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2384. }
  2385. return $this->_requestUri;
  2386. }
  2387. public function getQueryString()
  2388. {
  2389. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2390. }
  2391. public function getIsSecureConnection()
  2392. {
  2393. return isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'],'on');
  2394. }
  2395. public function getRequestType()
  2396. {
  2397. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2398. }
  2399. public function getIsPostRequest()
  2400. {
  2401. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2402. }
  2403. public function getIsDeleteRequest()
  2404. {
  2405. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE');
  2406. }
  2407. public function getIsPutRequest()
  2408. {
  2409. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT');
  2410. }
  2411. public function getIsAjaxRequest()
  2412. {
  2413. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2414. }
  2415. public function getServerName()
  2416. {
  2417. return $_SERVER['SERVER_NAME'];
  2418. }
  2419. public function getServerPort()
  2420. {
  2421. return $_SERVER['SERVER_PORT'];
  2422. }
  2423. public function getUrlReferrer()
  2424. {
  2425. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2426. }
  2427. public function getUserAgent()
  2428. {
  2429. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2430. }
  2431. public function getUserHostAddress()
  2432. {
  2433. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2434. }
  2435. public function getUserHost()
  2436. {
  2437. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2438. }
  2439. public function getScriptFile()
  2440. {
  2441. if($this->_scriptFile!==null)
  2442. return $this->_scriptFile;
  2443. else
  2444. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2445. }
  2446. public function getBrowser($userAgent=null)
  2447. {
  2448. return get_browser($userAgent,true);
  2449. }
  2450. public function getAcceptTypes()
  2451. {
  2452. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2453. }
  2454. private $_port;
  2455. public function getPort()
  2456. {
  2457. if($this->_port===null)
  2458. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2459. return $this->_port;
  2460. }
  2461. public function setPort($value)
  2462. {
  2463. $this->_port=(int)$value;
  2464. $this->_hostInfo=null;
  2465. }
  2466. private $_securePort;
  2467. public function getSecurePort()
  2468. {
  2469. if($this->_securePort===null)
  2470. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2471. return $this->_securePort;
  2472. }
  2473. public function setSecurePort($value)
  2474. {
  2475. $this->_securePort=(int)$value;
  2476. $this->_hostInfo=null;
  2477. }
  2478. public function getCookies()
  2479. {
  2480. if($this->_cookies!==null)
  2481. return $this->_cookies;
  2482. else
  2483. return $this->_cookies=new CCookieCollection($this);
  2484. }
  2485. public function redirect($url,$terminate=true,$statusCode=302)
  2486. {
  2487. if(strpos($url,'/')===0)
  2488. $url=$this->getHostInfo().$url;
  2489. header('Location: '.$url, true, $statusCode);
  2490. if($terminate)
  2491. Yii::app()->end();
  2492. }
  2493. public function getPreferredLanguage()
  2494. {
  2495. if($this->_preferredLanguage===null)
  2496. {
  2497. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && ($n=preg_match_all('/([\w\-_]+)\s*(;\s*q\s*=\s*(\d*\.\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))>0)
  2498. {
  2499. $languages=array();
  2500. for($i=0;$i<$n;++$i)
  2501. $languages[$matches[1][$i]]=empty($matches[3][$i]) ? 1.0 : floatval($matches[3][$i]);
  2502. arsort($languages);
  2503. foreach($languages as $language=>$pref)
  2504. return $this->_preferredLanguage=CLocale::getCanonicalID($language);
  2505. }
  2506. return $this->_preferredLanguage=false;
  2507. }
  2508. return $this->_preferredLanguage;
  2509. }
  2510. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2511. {
  2512. if($mimeType===null)
  2513. {
  2514. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2515. $mimeType='text/plain';
  2516. }
  2517. header('Pragma: public');
  2518. header('Expires: 0');
  2519. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2520. header("Content-type: $mimeType");
  2521. if(ob_get_length()===false)
  2522. header('Content-Length: '.(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content)));
  2523. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2524. header('Content-Transfer-Encoding: binary');
  2525. if($terminate)
  2526. {
  2527. // clean up the application first because the file downloading could take long time
  2528. // which may cause timeout of some resources (such as DB connection)
  2529. Yii::app()->end(0,false);
  2530. echo $content;
  2531. exit(0);
  2532. }
  2533. else
  2534. echo $content;
  2535. }
  2536. public function xSendFile($filePath, $options=array())
  2537. {
  2538. if(!isset($options['forceDownload']) || $options['forceDownload'])
  2539. $disposition='attachment';
  2540. else
  2541. $disposition='inline';
  2542. if(!isset($options['saveName']))
  2543. $options['saveName']=basename($filePath);
  2544. if(!isset($options['mimeType']))
  2545. {
  2546. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2547. $options['mimeType']='text/plain';
  2548. }
  2549. if(!isset($options['xHeader']))
  2550. $options['xHeader']='X-Sendfile';
  2551. if($options['mimeType'] !== null)
  2552. header('Content-type: '.$options['mimeType']);
  2553. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  2554. if(isset($options['addHeaders']))
  2555. {
  2556. foreach($options['addHeaders'] as $header=>$value)
  2557. header($header.': '.$value);
  2558. }
  2559. header(trim($options['xHeader']).': '.$filePath);
  2560. if(!isset($options['terminate']) || $options['terminate'])
  2561. Yii::app()->end();
  2562. }
  2563. public function getCsrfToken()
  2564. {
  2565. if($this->_csrfToken===null)
  2566. {
  2567. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2568. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2569. {
  2570. $cookie=$this->createCsrfCookie();
  2571. $this->_csrfToken=$cookie->value;
  2572. $this->getCookies()->add($cookie->name,$cookie);
  2573. }
  2574. }
  2575. return $this->_csrfToken;
  2576. }
  2577. protected function createCsrfCookie()
  2578. {
  2579. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2580. if(is_array($this->csrfCookie))
  2581. {
  2582. foreach($this->csrfCookie as $name=>$value)
  2583. $cookie->$name=$value;
  2584. }
  2585. return $cookie;
  2586. }
  2587. public function validateCsrfToken($event)
  2588. {
  2589. if($this->getIsPostRequest())
  2590. {
  2591. // only validate POST requests
  2592. $cookies=$this->getCookies();
  2593. if($cookies->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName]))
  2594. {
  2595. $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value;
  2596. $tokenFromPost=$_POST[$this->csrfTokenName];
  2597. $valid=$tokenFromCookie===$tokenFromPost;
  2598. }
  2599. else
  2600. $valid=false;
  2601. if(!$valid)
  2602. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2603. }
  2604. }
  2605. }
  2606. class CCookieCollection extends CMap
  2607. {
  2608. private $_request;
  2609. private $_initialized=false;
  2610. public function __construct(CHttpRequest $request)
  2611. {
  2612. $this->_request=$request;
  2613. $this->copyfrom($this->getCookies());
  2614. $this->_initialized=true;
  2615. }
  2616. public function getRequest()
  2617. {
  2618. return $this->_request;
  2619. }
  2620. protected function getCookies()
  2621. {
  2622. $cookies=array();
  2623. if($this->_request->enableCookieValidation)
  2624. {
  2625. $sm=Yii::app()->getSecurityManager();
  2626. foreach($_COOKIE as $name=>$value)
  2627. {
  2628. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  2629. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  2630. }
  2631. }
  2632. else
  2633. {
  2634. foreach($_COOKIE as $name=>$value)
  2635. $cookies[$name]=new CHttpCookie($name,$value);
  2636. }
  2637. return $cookies;
  2638. }
  2639. public function add($name,$cookie)
  2640. {
  2641. if($cookie instanceof CHttpCookie)
  2642. {
  2643. $this->remove($name);
  2644. parent::add($name,$cookie);
  2645. if($this->_initialized)
  2646. $this->addCookie($cookie);
  2647. }
  2648. else
  2649. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  2650. }
  2651. public function remove($name)
  2652. {
  2653. if(($cookie=parent::remove($name))!==null)
  2654. {
  2655. if($this->_initialized)
  2656. $this->removeCookie($cookie);
  2657. }
  2658. return $cookie;
  2659. }
  2660. protected function addCookie($cookie)
  2661. {
  2662. $value=$cookie->value;
  2663. if($this->_request->enableCookieValidation)
  2664. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  2665. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2666. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2667. else
  2668. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  2669. }
  2670. protected function removeCookie($cookie)
  2671. {
  2672. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2673. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2674. else
  2675. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure);
  2676. }
  2677. }
  2678. class CUrlManager extends CApplicationComponent
  2679. {
  2680. const CACHE_KEY='Yii.CUrlManager.rules';
  2681. const GET_FORMAT='get';
  2682. const PATH_FORMAT='path';
  2683. public $rules=array();
  2684. public $urlSuffix='';
  2685. public $showScriptName=true;
  2686. public $appendParams=true;
  2687. public $routeVar='r';
  2688. public $caseSensitive=true;
  2689. public $matchValue=false;
  2690. public $cacheID='cache';
  2691. public $useStrictParsing=false;
  2692. public $urlRuleClass='CUrlRule';
  2693. private $_urlFormat=self::GET_FORMAT;
  2694. private $_rules=array();
  2695. private $_baseUrl;
  2696. public function init()
  2697. {
  2698. parent::init();
  2699. $this->processRules();
  2700. }
  2701. protected function processRules()
  2702. {
  2703. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  2704. return;
  2705. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  2706. {
  2707. $hash=md5(serialize($this->rules));
  2708. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  2709. {
  2710. $this->_rules=$data[0];
  2711. return;
  2712. }
  2713. }
  2714. foreach($this->rules as $pattern=>$route)
  2715. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2716. if(isset($cache))
  2717. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  2718. }
  2719. public function addRules($rules, $append=true)
  2720. {
  2721. if ($append)
  2722. {
  2723. foreach($rules as $pattern=>$route)
  2724. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2725. }
  2726. else
  2727. {
  2728. foreach($rules as $pattern=>$route)
  2729. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  2730. }
  2731. }
  2732. protected function createUrlRule($route,$pattern)
  2733. {
  2734. if(is_array($route) && isset($route['class']))
  2735. return $route;
  2736. else
  2737. return new $this->urlRuleClass($route,$pattern);
  2738. }
  2739. public function createUrl($route,$params=array(),$ampersand='&')
  2740. {
  2741. unset($params[$this->routeVar]);
  2742. foreach($params as $i=>$param)
  2743. if($param===null)
  2744. $params[$i]='';
  2745. if(isset($params['#']))
  2746. {
  2747. $anchor='#'.$params['#'];
  2748. unset($params['#']);
  2749. }
  2750. else
  2751. $anchor='';
  2752. $route=trim($route,'/');
  2753. foreach($this->_rules as $i=>$rule)
  2754. {
  2755. if(is_array($rule))
  2756. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2757. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  2758. {
  2759. if($rule->hasHostInfo)
  2760. return $url==='' ? '/'.$anchor : $url.$anchor;
  2761. else
  2762. return $this->getBaseUrl().'/'.$url.$anchor;
  2763. }
  2764. }
  2765. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  2766. }
  2767. protected function createUrlDefault($route,$params,$ampersand)
  2768. {
  2769. if($this->getUrlFormat()===self::PATH_FORMAT)
  2770. {
  2771. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  2772. if($this->appendParams)
  2773. {
  2774. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  2775. return $route==='' ? $url : $url.$this->urlSuffix;
  2776. }
  2777. else
  2778. {
  2779. if($route!=='')
  2780. $url.=$this->urlSuffix;
  2781. $query=$this->createPathInfo($params,'=',$ampersand);
  2782. return $query==='' ? $url : $url.'?'.$query;
  2783. }
  2784. }
  2785. else
  2786. {
  2787. $url=$this->getBaseUrl();
  2788. if(!$this->showScriptName)
  2789. $url.='/';
  2790. if($route!=='')
  2791. {
  2792. $url.='?'.$this->routeVar.'='.$route;
  2793. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2794. $url.=$ampersand.$query;
  2795. }
  2796. else if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2797. $url.='?'.$query;
  2798. return $url;
  2799. }
  2800. }
  2801. public function parseUrl($request)
  2802. {
  2803. if($this->getUrlFormat()===self::PATH_FORMAT)
  2804. {
  2805. $rawPathInfo=$request->getPathInfo();
  2806. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  2807. foreach($this->_rules as $i=>$rule)
  2808. {
  2809. if(is_array($rule))
  2810. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2811. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  2812. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  2813. }
  2814. if($this->useStrictParsing)
  2815. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  2816. array('{route}'=>$pathInfo)));
  2817. else
  2818. return $pathInfo;
  2819. }
  2820. else if(isset($_GET[$this->routeVar]))
  2821. return $_GET[$this->routeVar];
  2822. else if(isset($_POST[$this->routeVar]))
  2823. return $_POST[$this->routeVar];
  2824. else
  2825. return '';
  2826. }
  2827. public function parsePathInfo($pathInfo)
  2828. {
  2829. if($pathInfo==='')
  2830. return;
  2831. $segs=explode('/',$pathInfo.'/');
  2832. $n=count($segs);
  2833. for($i=0;$i<$n-1;$i+=2)
  2834. {
  2835. $key=$segs[$i];
  2836. if($key==='') continue;
  2837. $value=$segs[$i+1];
  2838. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  2839. {
  2840. $name=substr($key,0,$pos);
  2841. for($j=$m-1;$j>=0;--$j)
  2842. {
  2843. if($matches[1][$j]==='')
  2844. $value=array($value);
  2845. else
  2846. $value=array($matches[1][$j]=>$value);
  2847. }
  2848. if(isset($_GET[$name]) && is_array($_GET[$name]))
  2849. $value=CMap::mergeArray($_GET[$name],$value);
  2850. $_REQUEST[$name]=$_GET[$name]=$value;
  2851. }
  2852. else
  2853. $_REQUEST[$key]=$_GET[$key]=$value;
  2854. }
  2855. }
  2856. public function createPathInfo($params,$equal,$ampersand, $key=null)
  2857. {
  2858. $pairs = array();
  2859. foreach($params as $k => $v)
  2860. {
  2861. if ($key!==null)
  2862. $k = $key.'['.$k.']';
  2863. if (is_array($v))
  2864. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  2865. else
  2866. $pairs[]=urlencode($k).$equal.urlencode($v);
  2867. }
  2868. return implode($ampersand,$pairs);
  2869. }
  2870. public function removeUrlSuffix($pathInfo,$urlSuffix)
  2871. {
  2872. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  2873. return substr($pathInfo,0,-strlen($urlSuffix));
  2874. else
  2875. return $pathInfo;
  2876. }
  2877. public function getBaseUrl()
  2878. {
  2879. if($this->_baseUrl!==null)
  2880. return $this->_baseUrl;
  2881. else
  2882. {
  2883. if($this->showScriptName)
  2884. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  2885. else
  2886. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  2887. return $this->_baseUrl;
  2888. }
  2889. }
  2890. public function setBaseUrl($value)
  2891. {
  2892. $this->_baseUrl=$value;
  2893. }
  2894. public function getUrlFormat()
  2895. {
  2896. return $this->_urlFormat;
  2897. }
  2898. public function setUrlFormat($value)
  2899. {
  2900. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  2901. $this->_urlFormat=$value;
  2902. else
  2903. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  2904. }
  2905. }
  2906. abstract class CBaseUrlRule extends CComponent
  2907. {
  2908. public $hasHostInfo=false;
  2909. abstract public function createUrl($manager,$route,$params,$ampersand);
  2910. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  2911. }
  2912. class CUrlRule extends CBaseUrlRule
  2913. {
  2914. public $urlSuffix;
  2915. public $caseSensitive;
  2916. public $defaultParams=array();
  2917. public $matchValue;
  2918. public $verb;
  2919. public $parsingOnly=false;
  2920. public $route;
  2921. public $references=array();
  2922. public $routePattern;
  2923. public $pattern;
  2924. public $template;
  2925. public $params=array();
  2926. public $append;
  2927. public $hasHostInfo;
  2928. public function __construct($route,$pattern)
  2929. {
  2930. if(is_array($route))
  2931. {
  2932. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  2933. {
  2934. if(isset($route[$name]))
  2935. $this->$name=$route[$name];
  2936. }
  2937. if(isset($route['pattern']))
  2938. $pattern=$route['pattern'];
  2939. $route=$route[0];
  2940. }
  2941. $this->route=trim($route,'/');
  2942. $tr2['/']=$tr['/']='\\/';
  2943. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  2944. {
  2945. foreach($matches2[1] as $name)
  2946. $this->references[$name]="<$name>";
  2947. }
  2948. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  2949. if($this->verb!==null)
  2950. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  2951. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  2952. {
  2953. $tokens=array_combine($matches[1],$matches[2]);
  2954. foreach($tokens as $name=>$value)
  2955. {
  2956. if($value==='')
  2957. $value='[^\/]+';
  2958. $tr["<$name>"]="(?P<$name>$value)";
  2959. if(isset($this->references[$name]))
  2960. $tr2["<$name>"]=$tr["<$name>"];
  2961. else
  2962. $this->params[$name]=$value;
  2963. }
  2964. }
  2965. $p=rtrim($pattern,'*');
  2966. $this->append=$p!==$pattern;
  2967. $p=trim($p,'/');
  2968. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  2969. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  2970. if($this->append)
  2971. $this->pattern.='/u';
  2972. else
  2973. $this->pattern.='$/u';
  2974. if($this->references!==array())
  2975. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  2976. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  2977. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  2978. array('{route}'=>$route,'{pattern}'=>$pattern)));
  2979. }
  2980. public function createUrl($manager,$route,$params,$ampersand)
  2981. {
  2982. if($this->parsingOnly)
  2983. return false;
  2984. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  2985. $case='';
  2986. else
  2987. $case='i';
  2988. $tr=array();
  2989. if($route!==$this->route)
  2990. {
  2991. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  2992. {
  2993. foreach($this->references as $key=>$name)
  2994. $tr[$name]=$matches[$key];
  2995. }
  2996. else
  2997. return false;
  2998. }
  2999. foreach($this->defaultParams as $key=>$value)
  3000. {
  3001. if(isset($params[$key]))
  3002. {
  3003. if($params[$key]==$value)
  3004. unset($params[$key]);
  3005. else
  3006. return false;
  3007. }
  3008. }
  3009. foreach($this->params as $key=>$value)
  3010. if(!isset($params[$key]))
  3011. return false;
  3012. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  3013. {
  3014. foreach($this->params as $key=>$value)
  3015. {
  3016. if(!preg_match('/'.$value.'/'.$case,$params[$key]))
  3017. return false;
  3018. }
  3019. }
  3020. foreach($this->params as $key=>$value)
  3021. {
  3022. $tr["<$key>"]=urlencode($params[$key]);
  3023. unset($params[$key]);
  3024. }
  3025. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3026. $url=strtr($this->template,$tr);
  3027. if($this->hasHostInfo)
  3028. {
  3029. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  3030. if(stripos($url,$hostInfo)===0)
  3031. $url=substr($url,strlen($hostInfo));
  3032. }
  3033. if(empty($params))
  3034. return $url!=='' ? $url.$suffix : $url;
  3035. if($this->append)
  3036. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  3037. else
  3038. {
  3039. if($url!=='')
  3040. $url.=$suffix;
  3041. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  3042. }
  3043. return $url;
  3044. }
  3045. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  3046. {
  3047. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  3048. return false;
  3049. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3050. $case='';
  3051. else
  3052. $case='i';
  3053. if($this->urlSuffix!==null)
  3054. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3055. // URL suffix required, but not found in the requested URL
  3056. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3057. {
  3058. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3059. if($urlSuffix!='' && $urlSuffix!=='/')
  3060. return false;
  3061. }
  3062. if($this->hasHostInfo)
  3063. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3064. $pathInfo.='/';
  3065. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3066. {
  3067. foreach($this->defaultParams as $name=>$value)
  3068. {
  3069. if(!isset($_GET[$name]))
  3070. $_REQUEST[$name]=$_GET[$name]=$value;
  3071. }
  3072. $tr=array();
  3073. foreach($matches as $key=>$value)
  3074. {
  3075. if(isset($this->references[$key]))
  3076. $tr[$this->references[$key]]=$value;
  3077. else if(isset($this->params[$key]))
  3078. $_REQUEST[$key]=$_GET[$key]=$value;
  3079. }
  3080. if($pathInfo!==$matches[0]) // there're additional GET params
  3081. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3082. if($this->routePattern!==null)
  3083. return strtr($this->route,$tr);
  3084. else
  3085. return $this->route;
  3086. }
  3087. else
  3088. return false;
  3089. }
  3090. }
  3091. abstract class CBaseController extends CComponent
  3092. {
  3093. private $_widgetStack=array();
  3094. abstract public function getViewFile($viewName);
  3095. public function renderFile($viewFile,$data=null,$return=false)
  3096. {
  3097. $widgetCount=count($this->_widgetStack);
  3098. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3099. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3100. else
  3101. $content=$this->renderInternal($viewFile,$data,$return);
  3102. if(count($this->_widgetStack)===$widgetCount)
  3103. return $content;
  3104. else
  3105. {
  3106. $widget=end($this->_widgetStack);
  3107. 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.',
  3108. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3109. }
  3110. }
  3111. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3112. {
  3113. // we use special variable names here to avoid conflict when extracting data
  3114. if(is_array($_data_))
  3115. extract($_data_,EXTR_PREFIX_SAME,'data');
  3116. else
  3117. $data=$_data_;
  3118. if($_return_)
  3119. {
  3120. ob_start();
  3121. ob_implicit_flush(false);
  3122. require($_viewFile_);
  3123. return ob_get_clean();
  3124. }
  3125. else
  3126. require($_viewFile_);
  3127. }
  3128. public function createWidget($className,$properties=array())
  3129. {
  3130. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3131. $widget->init();
  3132. return $widget;
  3133. }
  3134. public function widget($className,$properties=array(),$captureOutput=false)
  3135. {
  3136. if($captureOutput)
  3137. {
  3138. ob_start();
  3139. ob_implicit_flush(false);
  3140. $widget=$this->createWidget($className,$properties);
  3141. $widget->run();
  3142. return ob_get_clean();
  3143. }
  3144. else
  3145. {
  3146. $widget=$this->createWidget($className,$properties);
  3147. $widget->run();
  3148. return $widget;
  3149. }
  3150. }
  3151. public function beginWidget($className,$properties=array())
  3152. {
  3153. $widget=$this->createWidget($className,$properties);
  3154. $this->_widgetStack[]=$widget;
  3155. return $widget;
  3156. }
  3157. public function endWidget($id='')
  3158. {
  3159. if(($widget=array_pop($this->_widgetStack))!==null)
  3160. {
  3161. $widget->run();
  3162. return $widget;
  3163. }
  3164. else
  3165. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3166. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3167. }
  3168. public function beginClip($id,$properties=array())
  3169. {
  3170. $properties['id']=$id;
  3171. $this->beginWidget('CClipWidget',$properties);
  3172. }
  3173. public function endClip()
  3174. {
  3175. $this->endWidget('CClipWidget');
  3176. }
  3177. public function beginCache($id,$properties=array())
  3178. {
  3179. $properties['id']=$id;
  3180. $cache=$this->beginWidget('COutputCache',$properties);
  3181. if($cache->getIsContentCached())
  3182. {
  3183. $this->endCache();
  3184. return false;
  3185. }
  3186. else
  3187. return true;
  3188. }
  3189. public function endCache()
  3190. {
  3191. $this->endWidget('COutputCache');
  3192. }
  3193. public function beginContent($view=null,$data=array())
  3194. {
  3195. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3196. }
  3197. public function endContent()
  3198. {
  3199. $this->endWidget('CContentDecorator');
  3200. }
  3201. }
  3202. class CController extends CBaseController
  3203. {
  3204. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3205. public $layout;
  3206. public $defaultAction='index';
  3207. private $_id;
  3208. private $_action;
  3209. private $_pageTitle;
  3210. private $_cachingStack;
  3211. private $_clips;
  3212. private $_dynamicOutput;
  3213. private $_pageStates;
  3214. private $_module;
  3215. public function __construct($id,$module=null)
  3216. {
  3217. $this->_id=$id;
  3218. $this->_module=$module;
  3219. $this->attachBehaviors($this->behaviors());
  3220. }
  3221. public function init()
  3222. {
  3223. }
  3224. public function filters()
  3225. {
  3226. return array();
  3227. }
  3228. public function actions()
  3229. {
  3230. return array();
  3231. }
  3232. public function behaviors()
  3233. {
  3234. return array();
  3235. }
  3236. public function accessRules()
  3237. {
  3238. return array();
  3239. }
  3240. public function run($actionID)
  3241. {
  3242. if(($action=$this->createAction($actionID))!==null)
  3243. {
  3244. if(($parent=$this->getModule())===null)
  3245. $parent=Yii::app();
  3246. if($parent->beforeControllerAction($this,$action))
  3247. {
  3248. $this->runActionWithFilters($action,$this->filters());
  3249. $parent->afterControllerAction($this,$action);
  3250. }
  3251. }
  3252. else
  3253. $this->missingAction($actionID);
  3254. }
  3255. public function runActionWithFilters($action,$filters)
  3256. {
  3257. if(empty($filters))
  3258. $this->runAction($action);
  3259. else
  3260. {
  3261. $priorAction=$this->_action;
  3262. $this->_action=$action;
  3263. CFilterChain::create($this,$action,$filters)->run();
  3264. $this->_action=$priorAction;
  3265. }
  3266. }
  3267. public function runAction($action)
  3268. {
  3269. $priorAction=$this->_action;
  3270. $this->_action=$action;
  3271. if($this->beforeAction($action))
  3272. {
  3273. if($action->runWithParams($this->getActionParams())===false)
  3274. $this->invalidActionParams($action);
  3275. else
  3276. $this->afterAction($action);
  3277. }
  3278. $this->_action=$priorAction;
  3279. }
  3280. public function getActionParams()
  3281. {
  3282. return $_GET;
  3283. }
  3284. public function invalidActionParams($action)
  3285. {
  3286. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3287. }
  3288. public function processOutput($output)
  3289. {
  3290. Yii::app()->getClientScript()->render($output);
  3291. // if using page caching, we should delay dynamic output replacement
  3292. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3293. {
  3294. $output=$this->processDynamicOutput($output);
  3295. $this->_dynamicOutput=null;
  3296. }
  3297. if($this->_pageStates===null)
  3298. $this->_pageStates=$this->loadPageStates();
  3299. if(!empty($this->_pageStates))
  3300. $this->savePageStates($this->_pageStates,$output);
  3301. return $output;
  3302. }
  3303. public function processDynamicOutput($output)
  3304. {
  3305. if($this->_dynamicOutput)
  3306. {
  3307. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3308. }
  3309. return $output;
  3310. }
  3311. protected function replaceDynamicOutput($matches)
  3312. {
  3313. $content=$matches[0];
  3314. if(isset($this->_dynamicOutput[$matches[1]]))
  3315. {
  3316. $content=$this->_dynamicOutput[$matches[1]];
  3317. $this->_dynamicOutput[$matches[1]]=null;
  3318. }
  3319. return $content;
  3320. }
  3321. public function createAction($actionID)
  3322. {
  3323. if($actionID==='')
  3324. $actionID=$this->defaultAction;
  3325. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3326. return new CInlineAction($this,$actionID);
  3327. else
  3328. {
  3329. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3330. if($action!==null && !method_exists($action,'run'))
  3331. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3332. return $action;
  3333. }
  3334. }
  3335. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3336. {
  3337. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3338. {
  3339. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3340. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3341. }
  3342. else if($pos===false)
  3343. return null;
  3344. // the action is defined in a provider
  3345. $prefix=substr($actionID,0,$pos+1);
  3346. if(!isset($actionMap[$prefix]))
  3347. return null;
  3348. $actionID=(string)substr($actionID,$pos+1);
  3349. $provider=$actionMap[$prefix];
  3350. if(is_string($provider))
  3351. $providerType=$provider;
  3352. else if(is_array($provider) && isset($provider['class']))
  3353. {
  3354. $providerType=$provider['class'];
  3355. if(isset($provider[$actionID]))
  3356. {
  3357. if(is_string($provider[$actionID]))
  3358. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3359. else
  3360. $config=array_merge($provider[$actionID],$config);
  3361. }
  3362. }
  3363. else
  3364. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3365. $class=Yii::import($providerType,true);
  3366. $map=call_user_func(array($class,'actions'));
  3367. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3368. }
  3369. public function missingAction($actionID)
  3370. {
  3371. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3372. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3373. }
  3374. public function getAction()
  3375. {
  3376. return $this->_action;
  3377. }
  3378. public function setAction($value)
  3379. {
  3380. $this->_action=$value;
  3381. }
  3382. public function getId()
  3383. {
  3384. return $this->_id;
  3385. }
  3386. public function getUniqueId()
  3387. {
  3388. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3389. }
  3390. public function getRoute()
  3391. {
  3392. if(($action=$this->getAction())!==null)
  3393. return $this->getUniqueId().'/'.$action->getId();
  3394. else
  3395. return $this->getUniqueId();
  3396. }
  3397. public function getModule()
  3398. {
  3399. return $this->_module;
  3400. }
  3401. public function getViewPath()
  3402. {
  3403. if(($module=$this->getModule())===null)
  3404. $module=Yii::app();
  3405. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3406. }
  3407. public function getViewFile($viewName)
  3408. {
  3409. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3410. return $viewFile;
  3411. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3412. if(($module=$this->getModule())!==null)
  3413. $moduleViewPath=$module->getViewPath();
  3414. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3415. }
  3416. public function getLayoutFile($layoutName)
  3417. {
  3418. if($layoutName===false)
  3419. return false;
  3420. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3421. return $layoutFile;
  3422. if(empty($layoutName))
  3423. {
  3424. $module=$this->getModule();
  3425. while($module!==null)
  3426. {
  3427. if($module->layout===false)
  3428. return false;
  3429. if(!empty($module->layout))
  3430. break;
  3431. $module=$module->getParentModule();
  3432. }
  3433. if($module===null)
  3434. $module=Yii::app();
  3435. $layoutName=$module->layout;
  3436. }
  3437. else if(($module=$this->getModule())===null)
  3438. $module=Yii::app();
  3439. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3440. }
  3441. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3442. {
  3443. if(empty($viewName))
  3444. return false;
  3445. if($moduleViewPath===null)
  3446. $moduleViewPath=$basePath;
  3447. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3448. $extension=$renderer->fileExtension;
  3449. else
  3450. $extension='.php';
  3451. if($viewName[0]==='/')
  3452. {
  3453. if(strncmp($viewName,'//',2)===0)
  3454. $viewFile=$basePath.$viewName;
  3455. else
  3456. $viewFile=$moduleViewPath.$viewName;
  3457. }
  3458. else if(strpos($viewName,'.'))
  3459. $viewFile=Yii::getPathOfAlias($viewName);
  3460. else
  3461. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3462. if(is_file($viewFile.$extension))
  3463. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3464. else if($extension!=='.php' && is_file($viewFile.'.php'))
  3465. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3466. else
  3467. return false;
  3468. }
  3469. public function getClips()
  3470. {
  3471. if($this->_clips!==null)
  3472. return $this->_clips;
  3473. else
  3474. return $this->_clips=new CMap;
  3475. }
  3476. public function forward($route,$exit=true)
  3477. {
  3478. if(strpos($route,'/')===false)
  3479. $this->run($route);
  3480. else
  3481. {
  3482. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3483. $route=$module->getId().'/'.$route;
  3484. Yii::app()->runController($route);
  3485. }
  3486. if($exit)
  3487. Yii::app()->end();
  3488. }
  3489. public function render($view,$data=null,$return=false)
  3490. {
  3491. if($this->beforeRender($view))
  3492. {
  3493. $output=$this->renderPartial($view,$data,true);
  3494. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3495. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3496. $this->afterRender($view,$output);
  3497. $output=$this->processOutput($output);
  3498. if($return)
  3499. return $output;
  3500. else
  3501. echo $output;
  3502. }
  3503. }
  3504. protected function beforeRender($view)
  3505. {
  3506. return true;
  3507. }
  3508. protected function afterRender($view, &$output)
  3509. {
  3510. }
  3511. public function renderText($text,$return=false)
  3512. {
  3513. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3514. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3515. $text=$this->processOutput($text);
  3516. if($return)
  3517. return $text;
  3518. else
  3519. echo $text;
  3520. }
  3521. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3522. {
  3523. if(($viewFile=$this->getViewFile($view))!==false)
  3524. {
  3525. $output=$this->renderFile($viewFile,$data,true);
  3526. if($processOutput)
  3527. $output=$this->processOutput($output);
  3528. if($return)
  3529. return $output;
  3530. else
  3531. echo $output;
  3532. }
  3533. else
  3534. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3535. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3536. }
  3537. public function renderClip($name,$params=array(),$return=false)
  3538. {
  3539. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  3540. if($return)
  3541. return $text;
  3542. else
  3543. echo $text;
  3544. }
  3545. public function renderDynamic($callback)
  3546. {
  3547. $n=count($this->_dynamicOutput);
  3548. echo "<###dynamic-$n###>";
  3549. $params=func_get_args();
  3550. array_shift($params);
  3551. $this->renderDynamicInternal($callback,$params);
  3552. }
  3553. public function renderDynamicInternal($callback,$params)
  3554. {
  3555. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3556. if(is_string($callback) && method_exists($this,$callback))
  3557. $callback=array($this,$callback);
  3558. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3559. }
  3560. public function createUrl($route,$params=array(),$ampersand='&')
  3561. {
  3562. if($route==='')
  3563. $route=$this->getId().'/'.$this->getAction()->getId();
  3564. else if(strpos($route,'/')===false)
  3565. $route=$this->getId().'/'.$route;
  3566. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3567. $route=$module->getId().'/'.$route;
  3568. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3569. }
  3570. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3571. {
  3572. $url=$this->createUrl($route,$params,$ampersand);
  3573. if(strpos($url,'http')===0)
  3574. return $url;
  3575. else
  3576. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  3577. }
  3578. public function getPageTitle()
  3579. {
  3580. if($this->_pageTitle!==null)
  3581. return $this->_pageTitle;
  3582. else
  3583. {
  3584. $name=ucfirst(basename($this->getId()));
  3585. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3586. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3587. else
  3588. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3589. }
  3590. }
  3591. public function setPageTitle($value)
  3592. {
  3593. $this->_pageTitle=$value;
  3594. }
  3595. public function redirect($url,$terminate=true,$statusCode=302)
  3596. {
  3597. if(is_array($url))
  3598. {
  3599. $route=isset($url[0]) ? $url[0] : '';
  3600. $url=$this->createUrl($route,array_splice($url,1));
  3601. }
  3602. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  3603. }
  3604. public function refresh($terminate=true,$anchor='')
  3605. {
  3606. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  3607. }
  3608. public function recordCachingAction($context,$method,$params)
  3609. {
  3610. if($this->_cachingStack) // record only when there is an active output cache
  3611. {
  3612. foreach($this->_cachingStack as $cache)
  3613. $cache->recordAction($context,$method,$params);
  3614. }
  3615. }
  3616. public function getCachingStack($createIfNull=true)
  3617. {
  3618. if(!$this->_cachingStack)
  3619. $this->_cachingStack=new CStack;
  3620. return $this->_cachingStack;
  3621. }
  3622. public function isCachingStackEmpty()
  3623. {
  3624. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  3625. }
  3626. protected function beforeAction($action)
  3627. {
  3628. return true;
  3629. }
  3630. protected function afterAction($action)
  3631. {
  3632. }
  3633. public function filterPostOnly($filterChain)
  3634. {
  3635. if(Yii::app()->getRequest()->getIsPostRequest())
  3636. $filterChain->run();
  3637. else
  3638. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3639. }
  3640. public function filterAjaxOnly($filterChain)
  3641. {
  3642. if(Yii::app()->getRequest()->getIsAjaxRequest())
  3643. $filterChain->run();
  3644. else
  3645. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3646. }
  3647. public function filterAccessControl($filterChain)
  3648. {
  3649. $filter=new CAccessControlFilter;
  3650. $filter->setRules($this->accessRules());
  3651. $filter->filter($filterChain);
  3652. }
  3653. public function getPageState($name,$defaultValue=null)
  3654. {
  3655. if($this->_pageStates===null)
  3656. $this->_pageStates=$this->loadPageStates();
  3657. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  3658. }
  3659. public function setPageState($name,$value,$defaultValue=null)
  3660. {
  3661. if($this->_pageStates===null)
  3662. $this->_pageStates=$this->loadPageStates();
  3663. if($value===$defaultValue)
  3664. unset($this->_pageStates[$name]);
  3665. else
  3666. $this->_pageStates[$name]=$value;
  3667. $params=func_get_args();
  3668. $this->recordCachingAction('','setPageState',$params);
  3669. }
  3670. public function clearPageStates()
  3671. {
  3672. $this->_pageStates=array();
  3673. }
  3674. protected function loadPageStates()
  3675. {
  3676. if(!empty($_POST[self::STATE_INPUT_NAME]))
  3677. {
  3678. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  3679. {
  3680. if(extension_loaded('zlib'))
  3681. $data=@gzuncompress($data);
  3682. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  3683. return unserialize($data);
  3684. }
  3685. }
  3686. return array();
  3687. }
  3688. protected function savePageStates($states,&$output)
  3689. {
  3690. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  3691. if(extension_loaded('zlib'))
  3692. $data=gzcompress($data);
  3693. $value=base64_encode($data);
  3694. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  3695. }
  3696. }
  3697. abstract class CAction extends CComponent implements IAction
  3698. {
  3699. private $_id;
  3700. private $_controller;
  3701. public function __construct($controller,$id)
  3702. {
  3703. $this->_controller=$controller;
  3704. $this->_id=$id;
  3705. }
  3706. public function getController()
  3707. {
  3708. return $this->_controller;
  3709. }
  3710. public function getId()
  3711. {
  3712. return $this->_id;
  3713. }
  3714. public function runWithParams($params)
  3715. {
  3716. $method=new ReflectionMethod($this, 'run');
  3717. if($method->getNumberOfParameters()>0)
  3718. return $this->runWithParamsInternal($this, $method, $params);
  3719. else
  3720. return $this->run();
  3721. }
  3722. protected function runWithParamsInternal($object, $method, $params)
  3723. {
  3724. $ps=array();
  3725. foreach($method->getParameters() as $i=>$param)
  3726. {
  3727. $name=$param->getName();
  3728. if(isset($params[$name]))
  3729. {
  3730. if($param->isArray())
  3731. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  3732. else if(!is_array($params[$name]))
  3733. $ps[]=$params[$name];
  3734. else
  3735. return false;
  3736. }
  3737. else if($param->isDefaultValueAvailable())
  3738. $ps[]=$param->getDefaultValue();
  3739. else
  3740. return false;
  3741. }
  3742. $method->invokeArgs($object,$ps);
  3743. return true;
  3744. }
  3745. }
  3746. class CInlineAction extends CAction
  3747. {
  3748. public function run()
  3749. {
  3750. $method='action'.$this->getId();
  3751. $this->getController()->$method();
  3752. }
  3753. public function runWithParams($params)
  3754. {
  3755. $methodName='action'.$this->getId();
  3756. $controller=$this->getController();
  3757. $method=new ReflectionMethod($controller, $methodName);
  3758. if($method->getNumberOfParameters()>0)
  3759. return $this->runWithParamsInternal($controller, $method, $params);
  3760. else
  3761. return $controller->$methodName();
  3762. }
  3763. }
  3764. class CWebUser extends CApplicationComponent implements IWebUser
  3765. {
  3766. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  3767. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  3768. const STATES_VAR='__states';
  3769. const AUTH_TIMEOUT_VAR='__timeout';
  3770. public $allowAutoLogin=false;
  3771. public $guestName='Guest';
  3772. public $loginUrl=array('/site/login');
  3773. public $identityCookie;
  3774. public $authTimeout;
  3775. public $autoRenewCookie=false;
  3776. public $autoUpdateFlash=true;
  3777. public $loginRequiredAjaxResponse;
  3778. private $_keyPrefix;
  3779. private $_access=array();
  3780. public function __get($name)
  3781. {
  3782. if($this->hasState($name))
  3783. return $this->getState($name);
  3784. else
  3785. return parent::__get($name);
  3786. }
  3787. public function __set($name,$value)
  3788. {
  3789. if($this->hasState($name))
  3790. $this->setState($name,$value);
  3791. else
  3792. parent::__set($name,$value);
  3793. }
  3794. public function __isset($name)
  3795. {
  3796. if($this->hasState($name))
  3797. return $this->getState($name)!==null;
  3798. else
  3799. return parent::__isset($name);
  3800. }
  3801. public function __unset($name)
  3802. {
  3803. if($this->hasState($name))
  3804. $this->setState($name,null);
  3805. else
  3806. parent::__unset($name);
  3807. }
  3808. public function init()
  3809. {
  3810. parent::init();
  3811. Yii::app()->getSession()->open();
  3812. if($this->getIsGuest() && $this->allowAutoLogin)
  3813. $this->restoreFromCookie();
  3814. else if($this->autoRenewCookie && $this->allowAutoLogin)
  3815. $this->renewCookie();
  3816. if($this->autoUpdateFlash)
  3817. $this->updateFlash();
  3818. $this->updateAuthStatus();
  3819. }
  3820. public function login($identity,$duration=0)
  3821. {
  3822. $id=$identity->getId();
  3823. $states=$identity->getPersistentStates();
  3824. if($this->beforeLogin($id,$states,false))
  3825. {
  3826. $this->changeIdentity($id,$identity->getName(),$states);
  3827. if($duration>0)
  3828. {
  3829. if($this->allowAutoLogin)
  3830. $this->saveToCookie($duration);
  3831. else
  3832. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  3833. array('{class}'=>get_class($this))));
  3834. }
  3835. $this->afterLogin(false);
  3836. }
  3837. return !$this->getIsGuest();
  3838. }
  3839. public function logout($destroySession=true)
  3840. {
  3841. if($this->beforeLogout())
  3842. {
  3843. if($this->allowAutoLogin)
  3844. {
  3845. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  3846. if($this->identityCookie!==null)
  3847. {
  3848. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3849. $cookie->value=null;
  3850. $cookie->expire=0;
  3851. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  3852. }
  3853. }
  3854. if($destroySession)
  3855. Yii::app()->getSession()->destroy();
  3856. else
  3857. $this->clearStates();
  3858. $this->afterLogout();
  3859. }
  3860. }
  3861. public function getIsGuest()
  3862. {
  3863. return $this->getState('__id')===null;
  3864. }
  3865. public function getId()
  3866. {
  3867. return $this->getState('__id');
  3868. }
  3869. public function setId($value)
  3870. {
  3871. $this->setState('__id',$value);
  3872. }
  3873. public function getName()
  3874. {
  3875. if(($name=$this->getState('__name'))!==null)
  3876. return $name;
  3877. else
  3878. return $this->guestName;
  3879. }
  3880. public function setName($value)
  3881. {
  3882. $this->setState('__name',$value);
  3883. }
  3884. public function getReturnUrl($defaultUrl=null)
  3885. {
  3886. return $this->getState('__returnUrl', $defaultUrl===null ? Yii::app()->getRequest()->getScriptUrl() : CHtml::normalizeUrl($defaultUrl));
  3887. }
  3888. public function setReturnUrl($value)
  3889. {
  3890. $this->setState('__returnUrl',$value);
  3891. }
  3892. public function loginRequired()
  3893. {
  3894. $app=Yii::app();
  3895. $request=$app->getRequest();
  3896. if(!$request->getIsAjaxRequest())
  3897. $this->setReturnUrl($request->getUrl());
  3898. elseif(isset($this->loginRequiredAjaxResponse))
  3899. {
  3900. echo $this->loginRequiredAjaxResponse;
  3901. Yii::app()->end();
  3902. }
  3903. if(($url=$this->loginUrl)!==null)
  3904. {
  3905. if(is_array($url))
  3906. {
  3907. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  3908. $url=$app->createUrl($route,array_splice($url,1));
  3909. }
  3910. $request->redirect($url);
  3911. }
  3912. else
  3913. throw new CHttpException(403,Yii::t('yii','Login Required'));
  3914. }
  3915. protected function beforeLogin($id,$states,$fromCookie)
  3916. {
  3917. return true;
  3918. }
  3919. protected function afterLogin($fromCookie)
  3920. {
  3921. }
  3922. protected function beforeLogout()
  3923. {
  3924. return true;
  3925. }
  3926. protected function afterLogout()
  3927. {
  3928. }
  3929. protected function restoreFromCookie()
  3930. {
  3931. $app=Yii::app();
  3932. $request=$app->getRequest();
  3933. $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  3934. if($cookie && !empty($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  3935. {
  3936. $data=@unserialize($data);
  3937. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3938. {
  3939. list($id,$name,$duration,$states)=$data;
  3940. if($this->beforeLogin($id,$states,true))
  3941. {
  3942. $this->changeIdentity($id,$name,$states);
  3943. if($this->autoRenewCookie)
  3944. {
  3945. $cookie->expire=time()+$duration;
  3946. $request->getCookies()->add($cookie->name,$cookie);
  3947. }
  3948. $this->afterLogin(true);
  3949. }
  3950. }
  3951. }
  3952. }
  3953. protected function renewCookie()
  3954. {
  3955. $request=Yii::app()->getRequest();
  3956. $cookies=$request->getCookies();
  3957. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  3958. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  3959. {
  3960. $data=@unserialize($data);
  3961. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3962. {
  3963. $cookie->expire=time()+$data[2];
  3964. $cookies->add($cookie->name,$cookie);
  3965. }
  3966. }
  3967. }
  3968. protected function saveToCookie($duration)
  3969. {
  3970. $app=Yii::app();
  3971. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3972. $cookie->expire=time()+$duration;
  3973. $data=array(
  3974. $this->getId(),
  3975. $this->getName(),
  3976. $duration,
  3977. $this->saveIdentityStates(),
  3978. );
  3979. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  3980. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  3981. }
  3982. protected function createIdentityCookie($name)
  3983. {
  3984. $cookie=new CHttpCookie($name,'');
  3985. if(is_array($this->identityCookie))
  3986. {
  3987. foreach($this->identityCookie as $name=>$value)
  3988. $cookie->$name=$value;
  3989. }
  3990. return $cookie;
  3991. }
  3992. public function getStateKeyPrefix()
  3993. {
  3994. if($this->_keyPrefix!==null)
  3995. return $this->_keyPrefix;
  3996. else
  3997. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  3998. }
  3999. public function setStateKeyPrefix($value)
  4000. {
  4001. $this->_keyPrefix=$value;
  4002. }
  4003. public function getState($key,$defaultValue=null)
  4004. {
  4005. $key=$this->getStateKeyPrefix().$key;
  4006. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4007. }
  4008. public function setState($key,$value,$defaultValue=null)
  4009. {
  4010. $key=$this->getStateKeyPrefix().$key;
  4011. if($value===$defaultValue)
  4012. unset($_SESSION[$key]);
  4013. else
  4014. $_SESSION[$key]=$value;
  4015. }
  4016. public function hasState($key)
  4017. {
  4018. $key=$this->getStateKeyPrefix().$key;
  4019. return isset($_SESSION[$key]);
  4020. }
  4021. public function clearStates()
  4022. {
  4023. $keys=array_keys($_SESSION);
  4024. $prefix=$this->getStateKeyPrefix();
  4025. $n=strlen($prefix);
  4026. foreach($keys as $key)
  4027. {
  4028. if(!strncmp($key,$prefix,$n))
  4029. unset($_SESSION[$key]);
  4030. }
  4031. }
  4032. public function getFlashes($delete=true)
  4033. {
  4034. $flashes=array();
  4035. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  4036. $keys=array_keys($_SESSION);
  4037. $n=strlen($prefix);
  4038. foreach($keys as $key)
  4039. {
  4040. if(!strncmp($key,$prefix,$n))
  4041. {
  4042. $flashes[substr($key,$n)]=$_SESSION[$key];
  4043. if($delete)
  4044. unset($_SESSION[$key]);
  4045. }
  4046. }
  4047. if($delete)
  4048. $this->setState(self::FLASH_COUNTERS,array());
  4049. return $flashes;
  4050. }
  4051. public function getFlash($key,$defaultValue=null,$delete=true)
  4052. {
  4053. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4054. if($delete)
  4055. $this->setFlash($key,null);
  4056. return $value;
  4057. }
  4058. public function setFlash($key,$value,$defaultValue=null)
  4059. {
  4060. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4061. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4062. if($value===$defaultValue)
  4063. unset($counters[$key]);
  4064. else
  4065. $counters[$key]=0;
  4066. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4067. }
  4068. public function hasFlash($key)
  4069. {
  4070. return $this->getFlash($key, null, false)!==null;
  4071. }
  4072. protected function changeIdentity($id,$name,$states)
  4073. {
  4074. Yii::app()->getSession()->regenerateID();
  4075. $this->setId($id);
  4076. $this->setName($name);
  4077. $this->loadIdentityStates($states);
  4078. }
  4079. protected function saveIdentityStates()
  4080. {
  4081. $states=array();
  4082. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4083. $states[$name]=$this->getState($name);
  4084. return $states;
  4085. }
  4086. protected function loadIdentityStates($states)
  4087. {
  4088. $names=array();
  4089. if(is_array($states))
  4090. {
  4091. foreach($states as $name=>$value)
  4092. {
  4093. $this->setState($name,$value);
  4094. $names[$name]=true;
  4095. }
  4096. }
  4097. $this->setState(self::STATES_VAR,$names);
  4098. }
  4099. protected function updateFlash()
  4100. {
  4101. $counters=$this->getState(self::FLASH_COUNTERS);
  4102. if(!is_array($counters))
  4103. return;
  4104. foreach($counters as $key=>$count)
  4105. {
  4106. if($count)
  4107. {
  4108. unset($counters[$key]);
  4109. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4110. }
  4111. else
  4112. $counters[$key]++;
  4113. }
  4114. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4115. }
  4116. protected function updateAuthStatus()
  4117. {
  4118. if($this->authTimeout!==null && !$this->getIsGuest())
  4119. {
  4120. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4121. if ($expires!==null && $expires < time())
  4122. $this->logout(false);
  4123. else
  4124. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4125. }
  4126. }
  4127. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4128. {
  4129. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4130. return $this->_access[$operation];
  4131. else
  4132. return $this->_access[$operation]=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4133. }
  4134. }
  4135. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4136. {
  4137. public $autoStart=true;
  4138. public function init()
  4139. {
  4140. parent::init();
  4141. if($this->autoStart)
  4142. $this->open();
  4143. register_shutdown_function(array($this,'close'));
  4144. }
  4145. public function getUseCustomStorage()
  4146. {
  4147. return false;
  4148. }
  4149. public function open()
  4150. {
  4151. if($this->getUseCustomStorage())
  4152. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4153. @session_start();
  4154. if(YII_DEBUG && session_id()=='')
  4155. {
  4156. $message=Yii::t('yii','Failed to start session.');
  4157. if(function_exists('error_get_last'))
  4158. {
  4159. $error=error_get_last();
  4160. if(isset($error['message']))
  4161. $message=$error['message'];
  4162. }
  4163. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4164. }
  4165. }
  4166. public function close()
  4167. {
  4168. if(session_id()!=='')
  4169. @session_write_close();
  4170. }
  4171. public function destroy()
  4172. {
  4173. if(session_id()!=='')
  4174. {
  4175. @session_unset();
  4176. @session_destroy();
  4177. }
  4178. }
  4179. public function getIsStarted()
  4180. {
  4181. return session_id()!=='';
  4182. }
  4183. public function getSessionID()
  4184. {
  4185. return session_id();
  4186. }
  4187. public function setSessionID($value)
  4188. {
  4189. session_id($value);
  4190. }
  4191. public function regenerateID($deleteOldSession=false)
  4192. {
  4193. session_regenerate_id($deleteOldSession);
  4194. }
  4195. public function getSessionName()
  4196. {
  4197. return session_name();
  4198. }
  4199. public function setSessionName($value)
  4200. {
  4201. session_name($value);
  4202. }
  4203. public function getSavePath()
  4204. {
  4205. return session_save_path();
  4206. }
  4207. public function setSavePath($value)
  4208. {
  4209. if(is_dir($value))
  4210. session_save_path($value);
  4211. else
  4212. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4213. array('{path}'=>$value)));
  4214. }
  4215. public function getCookieParams()
  4216. {
  4217. return session_get_cookie_params();
  4218. }
  4219. public function setCookieParams($value)
  4220. {
  4221. $data=session_get_cookie_params();
  4222. extract($data);
  4223. extract($value);
  4224. if(isset($httponly))
  4225. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4226. else
  4227. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4228. }
  4229. public function getCookieMode()
  4230. {
  4231. if(ini_get('session.use_cookies')==='0')
  4232. return 'none';
  4233. else if(ini_get('session.use_only_cookies')==='0')
  4234. return 'allow';
  4235. else
  4236. return 'only';
  4237. }
  4238. public function setCookieMode($value)
  4239. {
  4240. if($value==='none')
  4241. {
  4242. ini_set('session.use_cookies','0');
  4243. ini_set('session.use_only_cookies','0');
  4244. }
  4245. else if($value==='allow')
  4246. {
  4247. ini_set('session.use_cookies','1');
  4248. ini_set('session.use_only_cookies','0');
  4249. }
  4250. else if($value==='only')
  4251. {
  4252. ini_set('session.use_cookies','1');
  4253. ini_set('session.use_only_cookies','1');
  4254. }
  4255. else
  4256. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4257. }
  4258. public function getGCProbability()
  4259. {
  4260. return (int)ini_get('session.gc_probability');
  4261. }
  4262. public function setGCProbability($value)
  4263. {
  4264. $value=(int)$value;
  4265. if($value>=0 && $value<=100)
  4266. {
  4267. ini_set('session.gc_probability',$value);
  4268. ini_set('session.gc_divisor','100');
  4269. }
  4270. else
  4271. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be an integer between 0 and 100.',
  4272. array('{value}'=>$value)));
  4273. }
  4274. public function getUseTransparentSessionID()
  4275. {
  4276. return ini_get('session.use_trans_sid')==1;
  4277. }
  4278. public function setUseTransparentSessionID($value)
  4279. {
  4280. ini_set('session.use_trans_sid',$value?'1':'0');
  4281. }
  4282. public function getTimeout()
  4283. {
  4284. return (int)ini_get('session.gc_maxlifetime');
  4285. }
  4286. public function setTimeout($value)
  4287. {
  4288. ini_set('session.gc_maxlifetime',$value);
  4289. }
  4290. public function openSession($savePath,$sessionName)
  4291. {
  4292. return true;
  4293. }
  4294. public function closeSession()
  4295. {
  4296. return true;
  4297. }
  4298. public function readSession($id)
  4299. {
  4300. return '';
  4301. }
  4302. public function writeSession($id,$data)
  4303. {
  4304. return true;
  4305. }
  4306. public function destroySession($id)
  4307. {
  4308. return true;
  4309. }
  4310. public function gcSession($maxLifetime)
  4311. {
  4312. return true;
  4313. }
  4314. //------ The following methods enable CHttpSession to be CMap-like -----
  4315. public function getIterator()
  4316. {
  4317. return new CHttpSessionIterator;
  4318. }
  4319. public function getCount()
  4320. {
  4321. return count($_SESSION);
  4322. }
  4323. public function count()
  4324. {
  4325. return $this->getCount();
  4326. }
  4327. public function getKeys()
  4328. {
  4329. return array_keys($_SESSION);
  4330. }
  4331. public function get($key,$defaultValue=null)
  4332. {
  4333. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4334. }
  4335. public function itemAt($key)
  4336. {
  4337. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4338. }
  4339. public function add($key,$value)
  4340. {
  4341. $_SESSION[$key]=$value;
  4342. }
  4343. public function remove($key)
  4344. {
  4345. if(isset($_SESSION[$key]))
  4346. {
  4347. $value=$_SESSION[$key];
  4348. unset($_SESSION[$key]);
  4349. return $value;
  4350. }
  4351. else
  4352. return null;
  4353. }
  4354. public function clear()
  4355. {
  4356. foreach(array_keys($_SESSION) as $key)
  4357. unset($_SESSION[$key]);
  4358. }
  4359. public function contains($key)
  4360. {
  4361. return isset($_SESSION[$key]);
  4362. }
  4363. public function toArray()
  4364. {
  4365. return $_SESSION;
  4366. }
  4367. public function offsetExists($offset)
  4368. {
  4369. return isset($_SESSION[$offset]);
  4370. }
  4371. public function offsetGet($offset)
  4372. {
  4373. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4374. }
  4375. public function offsetSet($offset,$item)
  4376. {
  4377. $_SESSION[$offset]=$item;
  4378. }
  4379. public function offsetUnset($offset)
  4380. {
  4381. unset($_SESSION[$offset]);
  4382. }
  4383. }
  4384. class CHtml
  4385. {
  4386. const ID_PREFIX='yt';
  4387. public static $errorSummaryCss='errorSummary';
  4388. public static $errorMessageCss='errorMessage';
  4389. public static $errorCss='error';
  4390. public static $requiredCss='required';
  4391. public static $beforeRequiredLabel='';
  4392. public static $afterRequiredLabel=' <span class="required">*</span>';
  4393. public static $count=0;
  4394. public static $liveEvents = true;
  4395. public static function encode($text)
  4396. {
  4397. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4398. }
  4399. public static function decode($text)
  4400. {
  4401. return htmlspecialchars_decode($text,ENT_QUOTES);
  4402. }
  4403. public static function encodeArray($data)
  4404. {
  4405. $d=array();
  4406. foreach($data as $key=>$value)
  4407. {
  4408. if(is_string($key))
  4409. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4410. if(is_string($value))
  4411. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4412. else if(is_array($value))
  4413. $value=self::encodeArray($value);
  4414. $d[$key]=$value;
  4415. }
  4416. return $d;
  4417. }
  4418. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4419. {
  4420. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4421. if($content===false)
  4422. return $closeTag ? $html.' />' : $html.'>';
  4423. else
  4424. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4425. }
  4426. public static function openTag($tag,$htmlOptions=array())
  4427. {
  4428. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4429. }
  4430. public static function closeTag($tag)
  4431. {
  4432. return '</'.$tag.'>';
  4433. }
  4434. public static function cdata($text)
  4435. {
  4436. return '<![CDATA[' . $text . ']]>';
  4437. }
  4438. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4439. {
  4440. if($name!==null)
  4441. $options['name']=$name;
  4442. if($httpEquiv!==null)
  4443. $options['http-equiv']=$httpEquiv;
  4444. $options['content']=$content;
  4445. return self::tag('meta',$options);
  4446. }
  4447. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4448. {
  4449. if($relation!==null)
  4450. $options['rel']=$relation;
  4451. if($type!==null)
  4452. $options['type']=$type;
  4453. if($href!==null)
  4454. $options['href']=$href;
  4455. if($media!==null)
  4456. $options['media']=$media;
  4457. return self::tag('link',$options);
  4458. }
  4459. public static function css($text,$media='')
  4460. {
  4461. if($media!=='')
  4462. $media=' media="'.$media.'"';
  4463. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4464. }
  4465. public static function refresh($seconds, $url='')
  4466. {
  4467. $content="$seconds";
  4468. if($url!=='')
  4469. $content.=';'.self::normalizeUrl($url);
  4470. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4471. }
  4472. public static function cssFile($url,$media='')
  4473. {
  4474. if($media!=='')
  4475. $media=' media="'.$media.'"';
  4476. return '<link rel="stylesheet" type="text/css" href="'.self::encode($url).'"'.$media.' />';
  4477. }
  4478. public static function script($text)
  4479. {
  4480. return "<script type=\"text/javascript\">\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</script>";
  4481. }
  4482. public static function scriptFile($url)
  4483. {
  4484. return '<script type="text/javascript" src="'.self::encode($url).'"></script>';
  4485. }
  4486. public static function form($action='',$method='post',$htmlOptions=array())
  4487. {
  4488. return self::beginForm($action,$method,$htmlOptions);
  4489. }
  4490. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4491. {
  4492. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4493. $htmlOptions['method']=$method;
  4494. $form=self::tag('form',$htmlOptions,false,false);
  4495. $hiddens=array();
  4496. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4497. {
  4498. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4499. {
  4500. if(($pos=strpos($pair,'='))!==false)
  4501. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4502. }
  4503. }
  4504. $request=Yii::app()->request;
  4505. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4506. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4507. if($hiddens!==array())
  4508. $form.="\n".self::tag('div',array('style'=>'display:none'),implode("\n",$hiddens));
  4509. return $form;
  4510. }
  4511. public static function endForm()
  4512. {
  4513. return '</form>';
  4514. }
  4515. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4516. {
  4517. return self::form($action,$method,$htmlOptions)."\n".
  4518. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4519. }
  4520. public static function pageStateField($value)
  4521. {
  4522. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4523. }
  4524. public static function link($text,$url='#',$htmlOptions=array())
  4525. {
  4526. if($url!=='')
  4527. $htmlOptions['href']=self::normalizeUrl($url);
  4528. self::clientChange('click',$htmlOptions);
  4529. return self::tag('a',$htmlOptions,$text);
  4530. }
  4531. public static function mailto($text,$email='',$htmlOptions=array())
  4532. {
  4533. if($email==='')
  4534. $email=$text;
  4535. return self::link($text,'mailto:'.$email,$htmlOptions);
  4536. }
  4537. public static function image($src,$alt='',$htmlOptions=array())
  4538. {
  4539. $htmlOptions['src']=$src;
  4540. $htmlOptions['alt']=$alt;
  4541. return self::tag('img',$htmlOptions);
  4542. }
  4543. public static function button($label='button',$htmlOptions=array())
  4544. {
  4545. if(!isset($htmlOptions['name']))
  4546. {
  4547. if(!array_key_exists('name',$htmlOptions))
  4548. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4549. }
  4550. if(!isset($htmlOptions['type']))
  4551. $htmlOptions['type']='button';
  4552. if(!isset($htmlOptions['value']))
  4553. $htmlOptions['value']=$label;
  4554. self::clientChange('click',$htmlOptions);
  4555. return self::tag('input',$htmlOptions);
  4556. }
  4557. public static function htmlButton($label='button',$htmlOptions=array())
  4558. {
  4559. if(!isset($htmlOptions['name']))
  4560. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4561. if(!isset($htmlOptions['type']))
  4562. $htmlOptions['type']='button';
  4563. self::clientChange('click',$htmlOptions);
  4564. return self::tag('button',$htmlOptions,$label);
  4565. }
  4566. public static function submitButton($label='submit',$htmlOptions=array())
  4567. {
  4568. $htmlOptions['type']='submit';
  4569. return self::button($label,$htmlOptions);
  4570. }
  4571. public static function resetButton($label='reset',$htmlOptions=array())
  4572. {
  4573. $htmlOptions['type']='reset';
  4574. return self::button($label,$htmlOptions);
  4575. }
  4576. public static function imageButton($src,$htmlOptions=array())
  4577. {
  4578. $htmlOptions['src']=$src;
  4579. $htmlOptions['type']='image';
  4580. return self::button('submit',$htmlOptions);
  4581. }
  4582. public static function linkButton($label='submit',$htmlOptions=array())
  4583. {
  4584. if(!isset($htmlOptions['submit']))
  4585. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  4586. return self::link($label,'#',$htmlOptions);
  4587. }
  4588. public static function label($label,$for,$htmlOptions=array())
  4589. {
  4590. if($for===false)
  4591. unset($htmlOptions['for']);
  4592. else
  4593. $htmlOptions['for']=$for;
  4594. if(isset($htmlOptions['required']))
  4595. {
  4596. if($htmlOptions['required'])
  4597. {
  4598. if(isset($htmlOptions['class']))
  4599. $htmlOptions['class'].=' '.self::$requiredCss;
  4600. else
  4601. $htmlOptions['class']=self::$requiredCss;
  4602. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  4603. }
  4604. unset($htmlOptions['required']);
  4605. }
  4606. return self::tag('label',$htmlOptions,$label);
  4607. }
  4608. public static function textField($name,$value='',$htmlOptions=array())
  4609. {
  4610. self::clientChange('change',$htmlOptions);
  4611. return self::inputField('text',$name,$value,$htmlOptions);
  4612. }
  4613. public static function hiddenField($name,$value='',$htmlOptions=array())
  4614. {
  4615. return self::inputField('hidden',$name,$value,$htmlOptions);
  4616. }
  4617. public static function passwordField($name,$value='',$htmlOptions=array())
  4618. {
  4619. self::clientChange('change',$htmlOptions);
  4620. return self::inputField('password',$name,$value,$htmlOptions);
  4621. }
  4622. public static function fileField($name,$value='',$htmlOptions=array())
  4623. {
  4624. return self::inputField('file',$name,$value,$htmlOptions);
  4625. }
  4626. public static function textArea($name,$value='',$htmlOptions=array())
  4627. {
  4628. $htmlOptions['name']=$name;
  4629. if(!isset($htmlOptions['id']))
  4630. $htmlOptions['id']=self::getIdByName($name);
  4631. else if($htmlOptions['id']===false)
  4632. unset($htmlOptions['id']);
  4633. self::clientChange('change',$htmlOptions);
  4634. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  4635. }
  4636. public static function radioButton($name,$checked=false,$htmlOptions=array())
  4637. {
  4638. if($checked)
  4639. $htmlOptions['checked']='checked';
  4640. else
  4641. unset($htmlOptions['checked']);
  4642. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4643. self::clientChange('click',$htmlOptions);
  4644. if(array_key_exists('uncheckValue',$htmlOptions))
  4645. {
  4646. $uncheck=$htmlOptions['uncheckValue'];
  4647. unset($htmlOptions['uncheckValue']);
  4648. }
  4649. else
  4650. $uncheck=null;
  4651. if($uncheck!==null)
  4652. {
  4653. // add a hidden field so that if the radio button is not selected, it still submits a value
  4654. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4655. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4656. else
  4657. $uncheckOptions=array('id'=>false);
  4658. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4659. }
  4660. else
  4661. $hidden='';
  4662. // add a hidden field so that if the radio button is not selected, it still submits a value
  4663. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  4664. }
  4665. public static function checkBox($name,$checked=false,$htmlOptions=array())
  4666. {
  4667. if($checked)
  4668. $htmlOptions['checked']='checked';
  4669. else
  4670. unset($htmlOptions['checked']);
  4671. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4672. self::clientChange('click',$htmlOptions);
  4673. if(array_key_exists('uncheckValue',$htmlOptions))
  4674. {
  4675. $uncheck=$htmlOptions['uncheckValue'];
  4676. unset($htmlOptions['uncheckValue']);
  4677. }
  4678. else
  4679. $uncheck=null;
  4680. if($uncheck!==null)
  4681. {
  4682. // add a hidden field so that if the radio button is not selected, it still submits a value
  4683. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4684. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4685. else
  4686. $uncheckOptions=array('id'=>false);
  4687. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4688. }
  4689. else
  4690. $hidden='';
  4691. // add a hidden field so that if the checkbox is not selected, it still submits a value
  4692. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  4693. }
  4694. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  4695. {
  4696. $htmlOptions['name']=$name;
  4697. if(!isset($htmlOptions['id']))
  4698. $htmlOptions['id']=self::getIdByName($name);
  4699. else if($htmlOptions['id']===false)
  4700. unset($htmlOptions['id']);
  4701. self::clientChange('change',$htmlOptions);
  4702. $options="\n".self::listOptions($select,$data,$htmlOptions);
  4703. return self::tag('select',$htmlOptions,$options);
  4704. }
  4705. public static function listBox($name,$select,$data,$htmlOptions=array())
  4706. {
  4707. if(!isset($htmlOptions['size']))
  4708. $htmlOptions['size']=4;
  4709. if(isset($htmlOptions['multiple']))
  4710. {
  4711. if(substr($name,-2)!=='[]')
  4712. $name.='[]';
  4713. }
  4714. return self::dropDownList($name,$select,$data,$htmlOptions);
  4715. }
  4716. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  4717. {
  4718. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4719. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4720. unset($htmlOptions['template'],$htmlOptions['separator']);
  4721. if(substr($name,-2)!=='[]')
  4722. $name.='[]';
  4723. if(isset($htmlOptions['checkAll']))
  4724. {
  4725. $checkAllLabel=$htmlOptions['checkAll'];
  4726. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  4727. }
  4728. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  4729. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4730. unset($htmlOptions['labelOptions']);
  4731. $items=array();
  4732. $baseID=self::getIdByName($name);
  4733. $id=0;
  4734. $checkAll=true;
  4735. foreach($data as $value=>$label)
  4736. {
  4737. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  4738. $checkAll=$checkAll && $checked;
  4739. $htmlOptions['value']=$value;
  4740. $htmlOptions['id']=$baseID.'_'.$id++;
  4741. $option=self::checkBox($name,$checked,$htmlOptions);
  4742. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4743. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4744. }
  4745. if(isset($checkAllLabel))
  4746. {
  4747. $htmlOptions['value']=1;
  4748. $htmlOptions['id']=$id=$baseID.'_all';
  4749. $option=self::checkBox($id,$checkAll,$htmlOptions);
  4750. $label=self::label($checkAllLabel,$id,$labelOptions);
  4751. $item=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4752. if($checkAllLast)
  4753. $items[]=$item;
  4754. else
  4755. array_unshift($items,$item);
  4756. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  4757. $js=<<<EOD
  4758. $('#$id').click(function() {
  4759. $("input[name='$name']").prop('checked', this.checked);
  4760. });
  4761. $("input[name='$name']").click(function() {
  4762. $('#$id').prop('checked', !$("input[name='$name']:not(:checked)").length);
  4763. });
  4764. $('#$id').prop('checked', !$("input[name='$name']:not(:checked)").length);
  4765. EOD;
  4766. $cs=Yii::app()->getClientScript();
  4767. $cs->registerCoreScript('jquery');
  4768. $cs->registerScript($id,$js);
  4769. }
  4770. return self::tag('span',array('id'=>$baseID),implode($separator,$items));
  4771. }
  4772. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  4773. {
  4774. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4775. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4776. unset($htmlOptions['template'],$htmlOptions['separator']);
  4777. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4778. unset($htmlOptions['labelOptions']);
  4779. $items=array();
  4780. $baseID=self::getIdByName($name);
  4781. $id=0;
  4782. foreach($data as $value=>$label)
  4783. {
  4784. $checked=!strcmp($value,$select);
  4785. $htmlOptions['value']=$value;
  4786. $htmlOptions['id']=$baseID.'_'.$id++;
  4787. $option=self::radioButton($name,$checked,$htmlOptions);
  4788. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4789. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4790. }
  4791. return self::tag('span',array('id'=>$baseID),implode($separator,$items));
  4792. }
  4793. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  4794. {
  4795. if(!isset($htmlOptions['href']))
  4796. $htmlOptions['href']='#';
  4797. $ajaxOptions['url']=$url;
  4798. $htmlOptions['ajax']=$ajaxOptions;
  4799. self::clientChange('click',$htmlOptions);
  4800. return self::tag('a',$htmlOptions,$text);
  4801. }
  4802. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4803. {
  4804. $ajaxOptions['url']=$url;
  4805. $htmlOptions['ajax']=$ajaxOptions;
  4806. return self::button($label,$htmlOptions);
  4807. }
  4808. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4809. {
  4810. $ajaxOptions['type']='POST';
  4811. $htmlOptions['type']='submit';
  4812. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  4813. }
  4814. public static function ajax($options)
  4815. {
  4816. Yii::app()->getClientScript()->registerCoreScript('jquery');
  4817. if(!isset($options['url']))
  4818. $options['url']='js:location.href';
  4819. else
  4820. $options['url']=self::normalizeUrl($options['url']);
  4821. if(!isset($options['cache']))
  4822. $options['cache']=false;
  4823. if(!isset($options['data']) && isset($options['type']))
  4824. $options['data']='js:jQuery(this).parents("form").serialize()';
  4825. foreach(array('beforeSend','complete','error','success') as $name)
  4826. {
  4827. if(isset($options[$name]) && strpos($options[$name],'js:')!==0)
  4828. $options[$name]='js:'.$options[$name];
  4829. }
  4830. if(isset($options['update']))
  4831. {
  4832. if(!isset($options['success']))
  4833. $options['success']='js:function(html){jQuery("'.$options['update'].'").html(html)}';
  4834. unset($options['update']);
  4835. }
  4836. if(isset($options['replace']))
  4837. {
  4838. if(!isset($options['success']))
  4839. $options['success']='js:function(html){jQuery("'.$options['replace'].'").replaceWith(html)}';
  4840. unset($options['replace']);
  4841. }
  4842. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  4843. }
  4844. public static function asset($path,$hashByName=false)
  4845. {
  4846. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  4847. }
  4848. public static function normalizeUrl($url)
  4849. {
  4850. if(is_array($url))
  4851. {
  4852. if(isset($url[0]))
  4853. {
  4854. if(($c=Yii::app()->getController())!==null)
  4855. $url=$c->createUrl($url[0],array_splice($url,1));
  4856. else
  4857. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  4858. }
  4859. else
  4860. $url='';
  4861. }
  4862. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  4863. }
  4864. protected static function inputField($type,$name,$value,$htmlOptions)
  4865. {
  4866. $htmlOptions['type']=$type;
  4867. $htmlOptions['value']=$value;
  4868. $htmlOptions['name']=$name;
  4869. if(!isset($htmlOptions['id']))
  4870. $htmlOptions['id']=self::getIdByName($name);
  4871. else if($htmlOptions['id']===false)
  4872. unset($htmlOptions['id']);
  4873. return self::tag('input',$htmlOptions);
  4874. }
  4875. public static function activeLabel($model,$attribute,$htmlOptions=array())
  4876. {
  4877. if(isset($htmlOptions['for']))
  4878. {
  4879. $for=$htmlOptions['for'];
  4880. unset($htmlOptions['for']);
  4881. }
  4882. else
  4883. $for=self::getIdByName(self::resolveName($model,$attribute));
  4884. if(isset($htmlOptions['label']))
  4885. {
  4886. if(($label=$htmlOptions['label'])===false)
  4887. return '';
  4888. unset($htmlOptions['label']);
  4889. }
  4890. else
  4891. $label=$model->getAttributeLabel($attribute);
  4892. if($model->hasErrors($attribute))
  4893. self::addErrorCss($htmlOptions);
  4894. return self::label($label,$for,$htmlOptions);
  4895. }
  4896. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  4897. {
  4898. $realAttribute=$attribute;
  4899. self::resolveName($model,$attribute); // strip off square brackets if any
  4900. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  4901. return self::activeLabel($model,$realAttribute,$htmlOptions);
  4902. }
  4903. public static function activeTextField($model,$attribute,$htmlOptions=array())
  4904. {
  4905. self::resolveNameID($model,$attribute,$htmlOptions);
  4906. self::clientChange('change',$htmlOptions);
  4907. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  4908. }
  4909. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  4910. {
  4911. self::resolveNameID($model,$attribute,$htmlOptions);
  4912. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  4913. }
  4914. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  4915. {
  4916. self::resolveNameID($model,$attribute,$htmlOptions);
  4917. self::clientChange('change',$htmlOptions);
  4918. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  4919. }
  4920. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  4921. {
  4922. self::resolveNameID($model,$attribute,$htmlOptions);
  4923. self::clientChange('change',$htmlOptions);
  4924. if($model->hasErrors($attribute))
  4925. self::addErrorCss($htmlOptions);
  4926. $text=self::resolveValue($model,$attribute);
  4927. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  4928. }
  4929. public static function activeFileField($model,$attribute,$htmlOptions=array())
  4930. {
  4931. self::resolveNameID($model,$attribute,$htmlOptions);
  4932. // add a hidden field so that if a model only has a file field, we can
  4933. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  4934. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4935. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  4936. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  4937. }
  4938. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  4939. {
  4940. self::resolveNameID($model,$attribute,$htmlOptions);
  4941. if(!isset($htmlOptions['value']))
  4942. $htmlOptions['value']=1;
  4943. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  4944. $htmlOptions['checked']='checked';
  4945. self::clientChange('click',$htmlOptions);
  4946. if(array_key_exists('uncheckValue',$htmlOptions))
  4947. {
  4948. $uncheck=$htmlOptions['uncheckValue'];
  4949. unset($htmlOptions['uncheckValue']);
  4950. }
  4951. else
  4952. $uncheck='0';
  4953. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4954. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  4955. // add a hidden field so that if the radio button is not selected, it still submits a value
  4956. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  4957. }
  4958. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  4959. {
  4960. self::resolveNameID($model,$attribute,$htmlOptions);
  4961. if(!isset($htmlOptions['value']))
  4962. $htmlOptions['value']=1;
  4963. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  4964. $htmlOptions['checked']='checked';
  4965. self::clientChange('click',$htmlOptions);
  4966. if(array_key_exists('uncheckValue',$htmlOptions))
  4967. {
  4968. $uncheck=$htmlOptions['uncheckValue'];
  4969. unset($htmlOptions['uncheckValue']);
  4970. }
  4971. else
  4972. $uncheck='0';
  4973. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4974. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  4975. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  4976. }
  4977. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  4978. {
  4979. self::resolveNameID($model,$attribute,$htmlOptions);
  4980. $selection=self::resolveValue($model,$attribute);
  4981. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  4982. self::clientChange('change',$htmlOptions);
  4983. if($model->hasErrors($attribute))
  4984. self::addErrorCss($htmlOptions);
  4985. if(isset($htmlOptions['multiple']))
  4986. {
  4987. if(substr($htmlOptions['name'],-2)!=='[]')
  4988. $htmlOptions['name'].='[]';
  4989. }
  4990. return self::tag('select',$htmlOptions,$options);
  4991. }
  4992. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  4993. {
  4994. if(!isset($htmlOptions['size']))
  4995. $htmlOptions['size']=4;
  4996. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  4997. }
  4998. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  4999. {
  5000. self::resolveNameID($model,$attribute,$htmlOptions);
  5001. $selection=self::resolveValue($model,$attribute);
  5002. if($model->hasErrors($attribute))
  5003. self::addErrorCss($htmlOptions);
  5004. $name=$htmlOptions['name'];
  5005. unset($htmlOptions['name']);
  5006. if(array_key_exists('uncheckValue',$htmlOptions))
  5007. {
  5008. $uncheck=$htmlOptions['uncheckValue'];
  5009. unset($htmlOptions['uncheckValue']);
  5010. }
  5011. else
  5012. $uncheck='';
  5013. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5014. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5015. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  5016. }
  5017. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  5018. {
  5019. self::resolveNameID($model,$attribute,$htmlOptions);
  5020. $selection=self::resolveValue($model,$attribute);
  5021. if($model->hasErrors($attribute))
  5022. self::addErrorCss($htmlOptions);
  5023. $name=$htmlOptions['name'];
  5024. unset($htmlOptions['name']);
  5025. if(array_key_exists('uncheckValue',$htmlOptions))
  5026. {
  5027. $uncheck=$htmlOptions['uncheckValue'];
  5028. unset($htmlOptions['uncheckValue']);
  5029. }
  5030. else
  5031. $uncheck='';
  5032. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5033. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5034. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  5035. }
  5036. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  5037. {
  5038. $content='';
  5039. if(!is_array($model))
  5040. $model=array($model);
  5041. if(isset($htmlOptions['firstError']))
  5042. {
  5043. $firstError=$htmlOptions['firstError'];
  5044. unset($htmlOptions['firstError']);
  5045. }
  5046. else
  5047. $firstError=false;
  5048. foreach($model as $m)
  5049. {
  5050. foreach($m->getErrors() as $errors)
  5051. {
  5052. foreach($errors as $error)
  5053. {
  5054. if($error!='')
  5055. $content.="<li>$error</li>\n";
  5056. if($firstError)
  5057. break;
  5058. }
  5059. }
  5060. }
  5061. if($content!=='')
  5062. {
  5063. if($header===null)
  5064. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5065. if(!isset($htmlOptions['class']))
  5066. $htmlOptions['class']=self::$errorSummaryCss;
  5067. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5068. }
  5069. else
  5070. return '';
  5071. }
  5072. public static function error($model,$attribute,$htmlOptions=array())
  5073. {
  5074. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5075. $error=$model->getError($attribute);
  5076. if($error!='')
  5077. {
  5078. if(!isset($htmlOptions['class']))
  5079. $htmlOptions['class']=self::$errorMessageCss;
  5080. return self::tag('div',$htmlOptions,$error);
  5081. }
  5082. else
  5083. return '';
  5084. }
  5085. public static function listData($models,$valueField,$textField,$groupField='')
  5086. {
  5087. $listData=array();
  5088. if($groupField==='')
  5089. {
  5090. foreach($models as $model)
  5091. {
  5092. $value=self::value($model,$valueField);
  5093. $text=self::value($model,$textField);
  5094. $listData[$value]=$text;
  5095. }
  5096. }
  5097. else
  5098. {
  5099. foreach($models as $model)
  5100. {
  5101. $group=self::value($model,$groupField);
  5102. $value=self::value($model,$valueField);
  5103. $text=self::value($model,$textField);
  5104. $listData[$group][$value]=$text;
  5105. }
  5106. }
  5107. return $listData;
  5108. }
  5109. public static function value($model,$attribute,$defaultValue=null)
  5110. {
  5111. foreach(explode('.',$attribute) as $name)
  5112. {
  5113. if(is_object($model))
  5114. $model=$model->$name;
  5115. else if(is_array($model) && isset($model[$name]))
  5116. $model=$model[$name];
  5117. else
  5118. return $defaultValue;
  5119. }
  5120. return $model;
  5121. }
  5122. public static function getIdByName($name)
  5123. {
  5124. return str_replace(array('[]', '][', '[', ']'), array('', '_', '_', ''), $name);
  5125. }
  5126. public static function activeId($model,$attribute)
  5127. {
  5128. return self::getIdByName(self::activeName($model,$attribute));
  5129. }
  5130. public static function activeName($model,$attribute)
  5131. {
  5132. $a=$attribute; // because the attribute name may be changed by resolveName
  5133. return self::resolveName($model,$a);
  5134. }
  5135. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5136. {
  5137. $htmlOptions['type']=$type;
  5138. if($type==='text' || $type==='password')
  5139. {
  5140. if(!isset($htmlOptions['maxlength']))
  5141. {
  5142. foreach($model->getValidators($attribute) as $validator)
  5143. {
  5144. if($validator instanceof CStringValidator && $validator->max!==null)
  5145. {
  5146. $htmlOptions['maxlength']=$validator->max;
  5147. break;
  5148. }
  5149. }
  5150. }
  5151. else if($htmlOptions['maxlength']===false)
  5152. unset($htmlOptions['maxlength']);
  5153. }
  5154. if($type==='file')
  5155. unset($htmlOptions['value']);
  5156. else if(!isset($htmlOptions['value']))
  5157. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5158. if($model->hasErrors($attribute))
  5159. self::addErrorCss($htmlOptions);
  5160. return self::tag('input',$htmlOptions);
  5161. }
  5162. public static function listOptions($selection,$listData,&$htmlOptions)
  5163. {
  5164. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5165. $content='';
  5166. if(isset($htmlOptions['prompt']))
  5167. {
  5168. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5169. unset($htmlOptions['prompt']);
  5170. }
  5171. if(isset($htmlOptions['empty']))
  5172. {
  5173. if(!is_array($htmlOptions['empty']))
  5174. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5175. foreach($htmlOptions['empty'] as $value=>$label)
  5176. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5177. unset($htmlOptions['empty']);
  5178. }
  5179. if(isset($htmlOptions['options']))
  5180. {
  5181. $options=$htmlOptions['options'];
  5182. unset($htmlOptions['options']);
  5183. }
  5184. else
  5185. $options=array();
  5186. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  5187. if(is_array($selection))
  5188. {
  5189. foreach($selection as $i=>$item)
  5190. {
  5191. if(is_object($item))
  5192. $selection[$i]=$item->$key;
  5193. }
  5194. }
  5195. else if(is_object($selection))
  5196. $selection=$selection->$key;
  5197. foreach($listData as $key=>$value)
  5198. {
  5199. if(is_array($value))
  5200. {
  5201. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  5202. $dummy=array('options'=>$options);
  5203. if(isset($htmlOptions['encode']))
  5204. $dummy['encode']=$htmlOptions['encode'];
  5205. $content.=self::listOptions($selection,$value,$dummy);
  5206. $content.='</optgroup>'."\n";
  5207. }
  5208. else
  5209. {
  5210. $attributes=array('value'=>(string)$key, 'encode'=>!$raw);
  5211. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  5212. $attributes['selected']='selected';
  5213. if(isset($options[$key]))
  5214. $attributes=array_merge($attributes,$options[$key]);
  5215. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  5216. }
  5217. }
  5218. unset($htmlOptions['key']);
  5219. return $content;
  5220. }
  5221. protected static function clientChange($event,&$htmlOptions)
  5222. {
  5223. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  5224. return;
  5225. if(isset($htmlOptions['live']))
  5226. {
  5227. $live=$htmlOptions['live'];
  5228. unset($htmlOptions['live']);
  5229. }
  5230. else
  5231. $live = self::$liveEvents;
  5232. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  5233. $return='return true';
  5234. else
  5235. $return='return false';
  5236. if(isset($htmlOptions['on'.$event]))
  5237. {
  5238. $handler=trim($htmlOptions['on'.$event],';').';';
  5239. unset($htmlOptions['on'.$event]);
  5240. }
  5241. else
  5242. $handler='';
  5243. if(isset($htmlOptions['id']))
  5244. $id=$htmlOptions['id'];
  5245. else
  5246. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  5247. $cs=Yii::app()->getClientScript();
  5248. $cs->registerCoreScript('jquery');
  5249. if(isset($htmlOptions['submit']))
  5250. {
  5251. $cs->registerCoreScript('yii');
  5252. $request=Yii::app()->getRequest();
  5253. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  5254. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  5255. if(isset($htmlOptions['params']))
  5256. $params=CJavaScript::encode($htmlOptions['params']);
  5257. else
  5258. $params='{}';
  5259. if($htmlOptions['submit']!=='')
  5260. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  5261. else
  5262. $url='';
  5263. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  5264. }
  5265. if(isset($htmlOptions['ajax']))
  5266. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  5267. if(isset($htmlOptions['confirm']))
  5268. {
  5269. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  5270. if($handler!=='')
  5271. $handler="if($confirm) {".$handler."} else return false;";
  5272. else
  5273. $handler="return $confirm;";
  5274. }
  5275. if($live)
  5276. $cs->registerScript('Yii.CHtml.#' . $id, "$('body').on('$event','#$id',function(){{$handler}});");
  5277. else
  5278. $cs->registerScript('Yii.CHtml.#' . $id, "$('#$id').on('$event', function(){{$handler}});");
  5279. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  5280. }
  5281. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  5282. {
  5283. if(!isset($htmlOptions['name']))
  5284. $htmlOptions['name']=self::resolveName($model,$attribute);
  5285. if(!isset($htmlOptions['id']))
  5286. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  5287. else if($htmlOptions['id']===false)
  5288. unset($htmlOptions['id']);
  5289. }
  5290. public static function resolveName($model,&$attribute)
  5291. {
  5292. if(($pos=strpos($attribute,'['))!==false)
  5293. {
  5294. if($pos!==0) // e.g. name[a][b]
  5295. return get_class($model).'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5296. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5297. {
  5298. $sub=substr($attribute,0,$pos+1);
  5299. $attribute=substr($attribute,$pos+1);
  5300. return get_class($model).$sub.'['.$attribute.']';
  5301. }
  5302. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5303. {
  5304. $name=get_class($model).'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5305. $attribute=$matches[1];
  5306. return $name;
  5307. }
  5308. }
  5309. return get_class($model).'['.$attribute.']';
  5310. }
  5311. public static function resolveValue($model,$attribute)
  5312. {
  5313. if(($pos=strpos($attribute,'['))!==false)
  5314. {
  5315. if($pos===0) // [a]name[b][c], should ignore [a]
  5316. {
  5317. if(preg_match('/\](\w+)/',$attribute,$matches))
  5318. $attribute=$matches[1];
  5319. if(($pos=strpos($attribute,'['))===false)
  5320. return $model->$attribute;
  5321. }
  5322. $name=substr($attribute,0,$pos);
  5323. $value=$model->$name;
  5324. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5325. {
  5326. if(is_array($value) && isset($value[$id]))
  5327. $value=$value[$id];
  5328. else
  5329. return null;
  5330. }
  5331. return $value;
  5332. }
  5333. else
  5334. return $model->$attribute;
  5335. }
  5336. protected static function addErrorCss(&$htmlOptions)
  5337. {
  5338. if(isset($htmlOptions['class']))
  5339. $htmlOptions['class'].=' '.self::$errorCss;
  5340. else
  5341. $htmlOptions['class']=self::$errorCss;
  5342. }
  5343. public static function renderAttributes($htmlOptions)
  5344. {
  5345. static $specialAttributes=array(
  5346. 'checked'=>1,
  5347. 'declare'=>1,
  5348. 'defer'=>1,
  5349. 'disabled'=>1,
  5350. 'ismap'=>1,
  5351. 'multiple'=>1,
  5352. 'nohref'=>1,
  5353. 'noresize'=>1,
  5354. 'readonly'=>1,
  5355. 'selected'=>1,
  5356. );
  5357. if($htmlOptions===array())
  5358. return '';
  5359. $html='';
  5360. if(isset($htmlOptions['encode']))
  5361. {
  5362. $raw=!$htmlOptions['encode'];
  5363. unset($htmlOptions['encode']);
  5364. }
  5365. else
  5366. $raw=false;
  5367. if($raw)
  5368. {
  5369. foreach($htmlOptions as $name=>$value)
  5370. {
  5371. if(isset($specialAttributes[$name]))
  5372. {
  5373. if($value)
  5374. $html .= ' ' . $name . '="' . $name . '"';
  5375. }
  5376. else if($value!==null)
  5377. $html .= ' ' . $name . '="' . $value . '"';
  5378. }
  5379. }
  5380. else
  5381. {
  5382. foreach($htmlOptions as $name=>$value)
  5383. {
  5384. if(isset($specialAttributes[$name]))
  5385. {
  5386. if($value)
  5387. $html .= ' ' . $name . '="' . $name . '"';
  5388. }
  5389. else if($value!==null)
  5390. $html .= ' ' . $name . '="' . self::encode($value) . '"';
  5391. }
  5392. }
  5393. return $html;
  5394. }
  5395. }
  5396. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  5397. {
  5398. public $enableSkin=false;
  5399. public $widgets=array();
  5400. public $skinnableWidgets;
  5401. public $skinPath;
  5402. private $_skins=array(); // class name, skin name, property name => value
  5403. public function init()
  5404. {
  5405. parent::init();
  5406. if($this->enableSkin && $this->skinPath===null)
  5407. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  5408. }
  5409. public function createWidget($owner,$className,$properties=array())
  5410. {
  5411. $className=Yii::import($className,true);
  5412. $widget=new $className($owner);
  5413. if(isset($this->widgets[$className]))
  5414. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  5415. if($this->enableSkin)
  5416. {
  5417. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  5418. {
  5419. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  5420. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  5421. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  5422. }
  5423. }
  5424. foreach($properties as $name=>$value)
  5425. $widget->$name=$value;
  5426. return $widget;
  5427. }
  5428. protected function getSkin($className,$skinName)
  5429. {
  5430. if(!isset($this->_skins[$className][$skinName]))
  5431. {
  5432. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  5433. if(is_file($skinFile))
  5434. $this->_skins[$className]=require($skinFile);
  5435. else
  5436. $this->_skins[$className]=array();
  5437. if(($theme=Yii::app()->getTheme())!==null)
  5438. {
  5439. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  5440. if(is_file($skinFile))
  5441. {
  5442. $skins=require($skinFile);
  5443. foreach($skins as $name=>$skin)
  5444. $this->_skins[$className][$name]=$skin;
  5445. }
  5446. }
  5447. if(!isset($this->_skins[$className][$skinName]))
  5448. $this->_skins[$className][$skinName]=array();
  5449. }
  5450. return $this->_skins[$className][$skinName];
  5451. }
  5452. }
  5453. class CWidget extends CBaseController
  5454. {
  5455. public $actionPrefix;
  5456. public $skin='default';
  5457. private static $_viewPaths;
  5458. private static $_counter=0;
  5459. private $_id;
  5460. private $_owner;
  5461. public static function actions()
  5462. {
  5463. return array();
  5464. }
  5465. public function __construct($owner=null)
  5466. {
  5467. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  5468. }
  5469. public function getOwner()
  5470. {
  5471. return $this->_owner;
  5472. }
  5473. public function getId($autoGenerate=true)
  5474. {
  5475. if($this->_id!==null)
  5476. return $this->_id;
  5477. else if($autoGenerate)
  5478. return $this->_id='yw'.self::$_counter++;
  5479. }
  5480. public function setId($value)
  5481. {
  5482. $this->_id=$value;
  5483. }
  5484. public function getController()
  5485. {
  5486. if($this->_owner instanceof CController)
  5487. return $this->_owner;
  5488. else
  5489. return Yii::app()->getController();
  5490. }
  5491. public function init()
  5492. {
  5493. }
  5494. public function run()
  5495. {
  5496. }
  5497. public function getViewPath($checkTheme=false)
  5498. {
  5499. $className=get_class($this);
  5500. if(isset(self::$_viewPaths[$className]))
  5501. return self::$_viewPaths[$className];
  5502. else
  5503. {
  5504. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  5505. {
  5506. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  5507. if(strpos($className,'\\')!==false) // namespaced class
  5508. $path.=str_replace('\\','_',ltrim($className,'\\'));
  5509. else
  5510. $path.=$className;
  5511. if(is_dir($path))
  5512. return self::$_viewPaths[$className]=$path;
  5513. }
  5514. $class=new ReflectionClass($className);
  5515. return self::$_viewPaths[$className]=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  5516. }
  5517. }
  5518. public function getViewFile($viewName)
  5519. {
  5520. if(($renderer=Yii::app()->getViewRenderer())!==null)
  5521. $extension=$renderer->fileExtension;
  5522. else
  5523. $extension='.php';
  5524. if(strpos($viewName,'.')) // a path alias
  5525. $viewFile=Yii::getPathOfAlias($viewName);
  5526. else
  5527. {
  5528. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  5529. if(is_file($viewFile.$extension))
  5530. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5531. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5532. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5533. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  5534. }
  5535. if(is_file($viewFile.$extension))
  5536. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5537. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5538. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5539. else
  5540. return false;
  5541. }
  5542. public function render($view,$data=null,$return=false)
  5543. {
  5544. if(($viewFile=$this->getViewFile($view))!==false)
  5545. return $this->renderFile($viewFile,$data,$return);
  5546. else
  5547. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  5548. array('{widget}'=>get_class($this), '{view}'=>$view)));
  5549. }
  5550. }
  5551. class CClientScript extends CApplicationComponent
  5552. {
  5553. const POS_HEAD=0;
  5554. const POS_BEGIN=1;
  5555. const POS_END=2;
  5556. const POS_LOAD=3;
  5557. const POS_READY=4;
  5558. public $enableJavaScript=true;
  5559. public $scriptMap=array();
  5560. public $packages=array();
  5561. public $corePackages;
  5562. protected $cssFiles=array();
  5563. protected $scriptFiles=array();
  5564. protected $scripts=array();
  5565. protected $metaTags=array();
  5566. protected $linkTags=array();
  5567. protected $css=array();
  5568. protected $hasScripts=false;
  5569. protected $coreScripts=array();
  5570. public $coreScriptPosition=self::POS_HEAD;
  5571. private $_baseUrl;
  5572. public function reset()
  5573. {
  5574. $this->hasScripts=false;
  5575. $this->coreScripts=array();
  5576. $this->cssFiles=array();
  5577. $this->css=array();
  5578. $this->scriptFiles=array();
  5579. $this->scripts=array();
  5580. $this->metaTags=array();
  5581. $this->linkTags=array();
  5582. $this->recordCachingAction('clientScript','reset',array());
  5583. }
  5584. public function render(&$output)
  5585. {
  5586. if(!$this->hasScripts)
  5587. return;
  5588. $this->renderCoreScripts();
  5589. if(!empty($this->scriptMap))
  5590. $this->remapScripts();
  5591. $this->unifyScripts();
  5592. $this->renderHead($output);
  5593. if($this->enableJavaScript)
  5594. {
  5595. $this->renderBodyBegin($output);
  5596. $this->renderBodyEnd($output);
  5597. }
  5598. }
  5599. protected function unifyScripts()
  5600. {
  5601. if(!$this->enableJavaScript)
  5602. return;
  5603. $map=array();
  5604. if(isset($this->scriptFiles[self::POS_HEAD]))
  5605. $map=$this->scriptFiles[self::POS_HEAD];
  5606. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5607. {
  5608. foreach($this->scriptFiles[self::POS_BEGIN] as $key=>$scriptFile)
  5609. {
  5610. if(isset($map[$scriptFile]))
  5611. unset($this->scriptFiles[self::POS_BEGIN][$key]);
  5612. else
  5613. $map[$scriptFile]=true;
  5614. }
  5615. }
  5616. if(isset($this->scriptFiles[self::POS_END]))
  5617. {
  5618. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  5619. {
  5620. if(isset($map[$scriptFile]))
  5621. unset($this->scriptFiles[self::POS_END][$key]);
  5622. }
  5623. }
  5624. }
  5625. protected function remapScripts()
  5626. {
  5627. $cssFiles=array();
  5628. foreach($this->cssFiles as $url=>$media)
  5629. {
  5630. $name=basename($url);
  5631. if(isset($this->scriptMap[$name]))
  5632. {
  5633. if($this->scriptMap[$name]!==false)
  5634. $cssFiles[$this->scriptMap[$name]]=$media;
  5635. }
  5636. else if(isset($this->scriptMap['*.css']))
  5637. {
  5638. if($this->scriptMap['*.css']!==false)
  5639. $cssFiles[$this->scriptMap['*.css']]=$media;
  5640. }
  5641. else
  5642. $cssFiles[$url]=$media;
  5643. }
  5644. $this->cssFiles=$cssFiles;
  5645. $jsFiles=array();
  5646. foreach($this->scriptFiles as $position=>$scripts)
  5647. {
  5648. $jsFiles[$position]=array();
  5649. foreach($scripts as $key=>$script)
  5650. {
  5651. $name=basename($script);
  5652. if(isset($this->scriptMap[$name]))
  5653. {
  5654. if($this->scriptMap[$name]!==false)
  5655. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  5656. }
  5657. else if(isset($this->scriptMap['*.js']))
  5658. {
  5659. if($this->scriptMap['*.js']!==false)
  5660. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  5661. }
  5662. else
  5663. $jsFiles[$position][$key]=$script;
  5664. }
  5665. }
  5666. $this->scriptFiles=$jsFiles;
  5667. }
  5668. public function renderCoreScripts()
  5669. {
  5670. if($this->coreScripts===null)
  5671. return;
  5672. $cssFiles=array();
  5673. $jsFiles=array();
  5674. foreach($this->coreScripts as $name=>$package)
  5675. {
  5676. $baseUrl=$this->getPackageBaseUrl($name);
  5677. if(!empty($package['js']))
  5678. {
  5679. foreach($package['js'] as $js)
  5680. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  5681. }
  5682. if(!empty($package['css']))
  5683. {
  5684. foreach($package['css'] as $css)
  5685. $cssFiles[$baseUrl.'/'.$css]='';
  5686. }
  5687. }
  5688. // merge in place
  5689. if($cssFiles!==array())
  5690. {
  5691. foreach($this->cssFiles as $cssFile=>$media)
  5692. $cssFiles[$cssFile]=$media;
  5693. $this->cssFiles=$cssFiles;
  5694. }
  5695. if($jsFiles!==array())
  5696. {
  5697. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  5698. {
  5699. foreach($this->scriptFiles[$this->coreScriptPosition] as $url)
  5700. $jsFiles[$url]=$url;
  5701. }
  5702. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  5703. }
  5704. }
  5705. public function renderHead(&$output)
  5706. {
  5707. $html='';
  5708. foreach($this->metaTags as $meta)
  5709. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  5710. foreach($this->linkTags as $link)
  5711. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  5712. foreach($this->cssFiles as $url=>$media)
  5713. $html.=CHtml::cssFile($url,$media)."\n";
  5714. foreach($this->css as $css)
  5715. $html.=CHtml::css($css[0],$css[1])."\n";
  5716. if($this->enableJavaScript)
  5717. {
  5718. if(isset($this->scriptFiles[self::POS_HEAD]))
  5719. {
  5720. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFile)
  5721. $html.=CHtml::scriptFile($scriptFile)."\n";
  5722. }
  5723. if(isset($this->scripts[self::POS_HEAD]))
  5724. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_HEAD]))."\n";
  5725. }
  5726. if($html!=='')
  5727. {
  5728. $count=0;
  5729. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  5730. if($count)
  5731. $output=str_replace('<###head###>',$html,$output);
  5732. else
  5733. $output=$html.$output;
  5734. }
  5735. }
  5736. public function renderBodyBegin(&$output)
  5737. {
  5738. $html='';
  5739. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5740. {
  5741. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile)
  5742. $html.=CHtml::scriptFile($scriptFile)."\n";
  5743. }
  5744. if(isset($this->scripts[self::POS_BEGIN]))
  5745. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_BEGIN]))."\n";
  5746. if($html!=='')
  5747. {
  5748. $count=0;
  5749. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  5750. if($count)
  5751. $output=str_replace('<###begin###>',$html,$output);
  5752. else
  5753. $output=$html.$output;
  5754. }
  5755. }
  5756. public function renderBodyEnd(&$output)
  5757. {
  5758. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  5759. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  5760. return;
  5761. $fullPage=0;
  5762. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  5763. $html='';
  5764. if(isset($this->scriptFiles[self::POS_END]))
  5765. {
  5766. foreach($this->scriptFiles[self::POS_END] as $scriptFile)
  5767. $html.=CHtml::scriptFile($scriptFile)."\n";
  5768. }
  5769. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  5770. if(isset($this->scripts[self::POS_READY]))
  5771. {
  5772. if($fullPage)
  5773. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  5774. else
  5775. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  5776. }
  5777. if(isset($this->scripts[self::POS_LOAD]))
  5778. {
  5779. if($fullPage)
  5780. $scripts[]="jQuery(window).load(function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  5781. else
  5782. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  5783. }
  5784. if(!empty($scripts))
  5785. $html.=CHtml::script(implode("\n",$scripts))."\n";
  5786. if($fullPage)
  5787. $output=str_replace('<###end###>',$html,$output);
  5788. else
  5789. $output=$output.$html;
  5790. }
  5791. public function getCoreScriptUrl()
  5792. {
  5793. if($this->_baseUrl!==null)
  5794. return $this->_baseUrl;
  5795. else
  5796. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  5797. }
  5798. public function setCoreScriptUrl($value)
  5799. {
  5800. $this->_baseUrl=$value;
  5801. }
  5802. public function getPackageBaseUrl($name)
  5803. {
  5804. if(!isset($this->coreScripts[$name]))
  5805. return false;
  5806. $package=$this->coreScripts[$name];
  5807. if(isset($package['baseUrl']))
  5808. {
  5809. $baseUrl=$package['baseUrl'];
  5810. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  5811. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  5812. $baseUrl=rtrim($baseUrl,'/');
  5813. }
  5814. else if(isset($package['basePath']))
  5815. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  5816. else
  5817. $baseUrl=$this->getCoreScriptUrl();
  5818. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  5819. }
  5820. public function registerPackage($name)
  5821. {
  5822. return $this->registerCoreScript($name);
  5823. }
  5824. public function registerCoreScript($name)
  5825. {
  5826. if(isset($this->coreScripts[$name]))
  5827. return $this;
  5828. if(isset($this->packages[$name]))
  5829. $package=$this->packages[$name];
  5830. else
  5831. {
  5832. if($this->corePackages===null)
  5833. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  5834. if(isset($this->corePackages[$name]))
  5835. $package=$this->corePackages[$name];
  5836. }
  5837. if(isset($package))
  5838. {
  5839. if(!empty($package['depends']))
  5840. {
  5841. foreach($package['depends'] as $p)
  5842. $this->registerCoreScript($p);
  5843. }
  5844. $this->coreScripts[$name]=$package;
  5845. $this->hasScripts=true;
  5846. $params=func_get_args();
  5847. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  5848. }
  5849. return $this;
  5850. }
  5851. public function registerCssFile($url,$media='')
  5852. {
  5853. $this->hasScripts=true;
  5854. $this->cssFiles[$url]=$media;
  5855. $params=func_get_args();
  5856. $this->recordCachingAction('clientScript','registerCssFile',$params);
  5857. return $this;
  5858. }
  5859. public function registerCss($id,$css,$media='')
  5860. {
  5861. $this->hasScripts=true;
  5862. $this->css[$id]=array($css,$media);
  5863. $params=func_get_args();
  5864. $this->recordCachingAction('clientScript','registerCss',$params);
  5865. return $this;
  5866. }
  5867. public function registerScriptFile($url,$position=self::POS_HEAD)
  5868. {
  5869. $this->hasScripts=true;
  5870. $this->scriptFiles[$position][$url]=$url;
  5871. $params=func_get_args();
  5872. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  5873. return $this;
  5874. }
  5875. public function registerScript($id,$script,$position=self::POS_READY)
  5876. {
  5877. $this->hasScripts=true;
  5878. $this->scripts[$position][$id]=$script;
  5879. if($position===self::POS_READY || $position===self::POS_LOAD)
  5880. $this->registerCoreScript('jquery');
  5881. $params=func_get_args();
  5882. $this->recordCachingAction('clientScript','registerScript',$params);
  5883. return $this;
  5884. }
  5885. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array())
  5886. {
  5887. $this->hasScripts=true;
  5888. if($name!==null)
  5889. $options['name']=$name;
  5890. if($httpEquiv!==null)
  5891. $options['http-equiv']=$httpEquiv;
  5892. $options['content']=$content;
  5893. $this->metaTags[serialize($options)]=$options;
  5894. $params=func_get_args();
  5895. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  5896. return $this;
  5897. }
  5898. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  5899. {
  5900. $this->hasScripts=true;
  5901. if($relation!==null)
  5902. $options['rel']=$relation;
  5903. if($type!==null)
  5904. $options['type']=$type;
  5905. if($href!==null)
  5906. $options['href']=$href;
  5907. if($media!==null)
  5908. $options['media']=$media;
  5909. $this->linkTags[serialize($options)]=$options;
  5910. $params=func_get_args();
  5911. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  5912. return $this;
  5913. }
  5914. public function isCssFileRegistered($url)
  5915. {
  5916. return isset($this->cssFiles[$url]);
  5917. }
  5918. public function isCssRegistered($id)
  5919. {
  5920. return isset($this->css[$id]);
  5921. }
  5922. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  5923. {
  5924. return isset($this->scriptFiles[$position][$url]);
  5925. }
  5926. public function isScriptRegistered($id,$position=self::POS_READY)
  5927. {
  5928. return isset($this->scripts[$position][$id]);
  5929. }
  5930. protected function recordCachingAction($context,$method,$params)
  5931. {
  5932. if(($controller=Yii::app()->getController())!==null)
  5933. $controller->recordCachingAction($context,$method,$params);
  5934. }
  5935. public function addPackage($name,$definition)
  5936. {
  5937. $this->packages[$name]=$definition;
  5938. return $this;
  5939. }
  5940. }
  5941. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  5942. {
  5943. private $_d=array();
  5944. private $_c=0;
  5945. private $_r=false;
  5946. public function __construct($data=null,$readOnly=false)
  5947. {
  5948. if($data!==null)
  5949. $this->copyFrom($data);
  5950. $this->setReadOnly($readOnly);
  5951. }
  5952. public function getReadOnly()
  5953. {
  5954. return $this->_r;
  5955. }
  5956. protected function setReadOnly($value)
  5957. {
  5958. $this->_r=$value;
  5959. }
  5960. public function getIterator()
  5961. {
  5962. return new CListIterator($this->_d);
  5963. }
  5964. public function count()
  5965. {
  5966. return $this->getCount();
  5967. }
  5968. public function getCount()
  5969. {
  5970. return $this->_c;
  5971. }
  5972. public function itemAt($index)
  5973. {
  5974. if(isset($this->_d[$index]))
  5975. return $this->_d[$index];
  5976. else if($index>=0 && $index<$this->_c) // in case the value is null
  5977. return $this->_d[$index];
  5978. else
  5979. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  5980. array('{index}'=>$index)));
  5981. }
  5982. public function add($item)
  5983. {
  5984. $this->insertAt($this->_c,$item);
  5985. return $this->_c-1;
  5986. }
  5987. public function insertAt($index,$item)
  5988. {
  5989. if(!$this->_r)
  5990. {
  5991. if($index===$this->_c)
  5992. $this->_d[$this->_c++]=$item;
  5993. else if($index>=0 && $index<$this->_c)
  5994. {
  5995. array_splice($this->_d,$index,0,array($item));
  5996. $this->_c++;
  5997. }
  5998. else
  5999. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6000. array('{index}'=>$index)));
  6001. }
  6002. else
  6003. throw new CException(Yii::t('yii','The list is read only.'));
  6004. }
  6005. public function remove($item)
  6006. {
  6007. if(($index=$this->indexOf($item))>=0)
  6008. {
  6009. $this->removeAt($index);
  6010. return $index;
  6011. }
  6012. else
  6013. return false;
  6014. }
  6015. public function removeAt($index)
  6016. {
  6017. if(!$this->_r)
  6018. {
  6019. if($index>=0 && $index<$this->_c)
  6020. {
  6021. $this->_c--;
  6022. if($index===$this->_c)
  6023. return array_pop($this->_d);
  6024. else
  6025. {
  6026. $item=$this->_d[$index];
  6027. array_splice($this->_d,$index,1);
  6028. return $item;
  6029. }
  6030. }
  6031. else
  6032. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6033. array('{index}'=>$index)));
  6034. }
  6035. else
  6036. throw new CException(Yii::t('yii','The list is read only.'));
  6037. }
  6038. public function clear()
  6039. {
  6040. for($i=$this->_c-1;$i>=0;--$i)
  6041. $this->removeAt($i);
  6042. }
  6043. public function contains($item)
  6044. {
  6045. return $this->indexOf($item)>=0;
  6046. }
  6047. public function indexOf($item)
  6048. {
  6049. if(($index=array_search($item,$this->_d,true))!==false)
  6050. return $index;
  6051. else
  6052. return -1;
  6053. }
  6054. public function toArray()
  6055. {
  6056. return $this->_d;
  6057. }
  6058. public function copyFrom($data)
  6059. {
  6060. if(is_array($data) || ($data instanceof Traversable))
  6061. {
  6062. if($this->_c>0)
  6063. $this->clear();
  6064. if($data instanceof CList)
  6065. $data=$data->_d;
  6066. foreach($data as $item)
  6067. $this->add($item);
  6068. }
  6069. else if($data!==null)
  6070. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6071. }
  6072. public function mergeWith($data)
  6073. {
  6074. if(is_array($data) || ($data instanceof Traversable))
  6075. {
  6076. if($data instanceof CList)
  6077. $data=$data->_d;
  6078. foreach($data as $item)
  6079. $this->add($item);
  6080. }
  6081. else if($data!==null)
  6082. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6083. }
  6084. public function offsetExists($offset)
  6085. {
  6086. return ($offset>=0 && $offset<$this->_c);
  6087. }
  6088. public function offsetGet($offset)
  6089. {
  6090. return $this->itemAt($offset);
  6091. }
  6092. public function offsetSet($offset,$item)
  6093. {
  6094. if($offset===null || $offset===$this->_c)
  6095. $this->insertAt($this->_c,$item);
  6096. else
  6097. {
  6098. $this->removeAt($offset);
  6099. $this->insertAt($offset,$item);
  6100. }
  6101. }
  6102. public function offsetUnset($offset)
  6103. {
  6104. $this->removeAt($offset);
  6105. }
  6106. }
  6107. class CFilterChain extends CList
  6108. {
  6109. public $controller;
  6110. public $action;
  6111. public $filterIndex=0;
  6112. public function __construct($controller,$action)
  6113. {
  6114. $this->controller=$controller;
  6115. $this->action=$action;
  6116. }
  6117. public static function create($controller,$action,$filters)
  6118. {
  6119. $chain=new CFilterChain($controller,$action);
  6120. $actionID=$action->getId();
  6121. foreach($filters as $filter)
  6122. {
  6123. if(is_string($filter)) // filterName [+|- action1 action2]
  6124. {
  6125. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  6126. {
  6127. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  6128. if(($filter[$pos]==='+')===$matched)
  6129. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  6130. }
  6131. else
  6132. $filter=CInlineFilter::create($controller,$filter);
  6133. }
  6134. else if(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  6135. {
  6136. if(!isset($filter[0]))
  6137. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  6138. $filterClass=$filter[0];
  6139. unset($filter[0]);
  6140. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  6141. {
  6142. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  6143. if(($filterClass[$pos]==='+')===$matched)
  6144. $filterClass=trim(substr($filterClass,0,$pos));
  6145. else
  6146. continue;
  6147. }
  6148. $filter['class']=$filterClass;
  6149. $filter=Yii::createComponent($filter);
  6150. }
  6151. if(is_object($filter))
  6152. {
  6153. $filter->init();
  6154. $chain->add($filter);
  6155. }
  6156. }
  6157. return $chain;
  6158. }
  6159. public function insertAt($index,$item)
  6160. {
  6161. if($item instanceof IFilter)
  6162. parent::insertAt($index,$item);
  6163. else
  6164. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  6165. }
  6166. public function run()
  6167. {
  6168. if($this->offsetExists($this->filterIndex))
  6169. {
  6170. $filter=$this->itemAt($this->filterIndex++);
  6171. $filter->filter($this);
  6172. }
  6173. else
  6174. $this->controller->runAction($this->action);
  6175. }
  6176. }
  6177. class CFilter extends CComponent implements IFilter
  6178. {
  6179. public function filter($filterChain)
  6180. {
  6181. if($this->preFilter($filterChain))
  6182. {
  6183. $filterChain->run();
  6184. $this->postFilter($filterChain);
  6185. }
  6186. }
  6187. public function init()
  6188. {
  6189. }
  6190. protected function preFilter($filterChain)
  6191. {
  6192. return true;
  6193. }
  6194. protected function postFilter($filterChain)
  6195. {
  6196. }
  6197. }
  6198. class CInlineFilter extends CFilter
  6199. {
  6200. public $name;
  6201. public static function create($controller,$filterName)
  6202. {
  6203. if(method_exists($controller,'filter'.$filterName))
  6204. {
  6205. $filter=new CInlineFilter;
  6206. $filter->name=$filterName;
  6207. return $filter;
  6208. }
  6209. else
  6210. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  6211. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  6212. }
  6213. public function filter($filterChain)
  6214. {
  6215. $method='filter'.$this->name;
  6216. $filterChain->controller->$method($filterChain);
  6217. }
  6218. }
  6219. class CAccessControlFilter extends CFilter
  6220. {
  6221. public $message;
  6222. private $_rules=array();
  6223. public function getRules()
  6224. {
  6225. return $this->_rules;
  6226. }
  6227. public function setRules($rules)
  6228. {
  6229. foreach($rules as $rule)
  6230. {
  6231. if(is_array($rule) && isset($rule[0]))
  6232. {
  6233. $r=new CAccessRule;
  6234. $r->allow=$rule[0]==='allow';
  6235. foreach(array_slice($rule,1) as $name=>$value)
  6236. {
  6237. if($name==='expression' || $name==='roles' || $name==='message')
  6238. $r->$name=$value;
  6239. else
  6240. $r->$name=array_map('strtolower',$value);
  6241. }
  6242. $this->_rules[]=$r;
  6243. }
  6244. }
  6245. }
  6246. protected function preFilter($filterChain)
  6247. {
  6248. $app=Yii::app();
  6249. $request=$app->getRequest();
  6250. $user=$app->getUser();
  6251. $verb=$request->getRequestType();
  6252. $ip=$request->getUserHostAddress();
  6253. foreach($this->getRules() as $rule)
  6254. {
  6255. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  6256. break;
  6257. else if($allow<0) // denied
  6258. {
  6259. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  6260. return false;
  6261. }
  6262. }
  6263. return true;
  6264. }
  6265. protected function resolveErrorMessage($rule)
  6266. {
  6267. if($rule->message!==null)
  6268. return $rule->message;
  6269. else if($this->message!==null)
  6270. return $this->message;
  6271. else
  6272. return Yii::t('yii','You are not authorized to perform this action.');
  6273. }
  6274. protected function accessDenied($user,$message)
  6275. {
  6276. if($user->getIsGuest())
  6277. $user->loginRequired();
  6278. else
  6279. throw new CHttpException(403,$message);
  6280. }
  6281. }
  6282. class CAccessRule extends CComponent
  6283. {
  6284. public $allow;
  6285. public $actions;
  6286. public $controllers;
  6287. public $users;
  6288. public $roles;
  6289. public $ips;
  6290. public $verbs;
  6291. public $expression;
  6292. public $message;
  6293. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  6294. {
  6295. if($this->isActionMatched($action)
  6296. && $this->isUserMatched($user)
  6297. && $this->isRoleMatched($user)
  6298. && $this->isIpMatched($ip)
  6299. && $this->isVerbMatched($verb)
  6300. && $this->isControllerMatched($controller)
  6301. && $this->isExpressionMatched($user))
  6302. return $this->allow ? 1 : -1;
  6303. else
  6304. return 0;
  6305. }
  6306. protected function isActionMatched($action)
  6307. {
  6308. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  6309. }
  6310. protected function isControllerMatched($controller)
  6311. {
  6312. return empty($this->controllers) || in_array(strtolower($controller->getId()),$this->controllers);
  6313. }
  6314. protected function isUserMatched($user)
  6315. {
  6316. if(empty($this->users))
  6317. return true;
  6318. foreach($this->users as $u)
  6319. {
  6320. if($u==='*')
  6321. return true;
  6322. else if($u==='?' && $user->getIsGuest())
  6323. return true;
  6324. else if($u==='@' && !$user->getIsGuest())
  6325. return true;
  6326. else if(!strcasecmp($u,$user->getName()))
  6327. return true;
  6328. }
  6329. return false;
  6330. }
  6331. protected function isRoleMatched($user)
  6332. {
  6333. if(empty($this->roles))
  6334. return true;
  6335. foreach($this->roles as $role)
  6336. {
  6337. if($user->checkAccess($role))
  6338. return true;
  6339. }
  6340. return false;
  6341. }
  6342. protected function isIpMatched($ip)
  6343. {
  6344. if(empty($this->ips))
  6345. return true;
  6346. foreach($this->ips as $rule)
  6347. {
  6348. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  6349. return true;
  6350. }
  6351. return false;
  6352. }
  6353. protected function isVerbMatched($verb)
  6354. {
  6355. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  6356. }
  6357. protected function isExpressionMatched($user)
  6358. {
  6359. if($this->expression===null)
  6360. return true;
  6361. else
  6362. return $this->evaluateExpression($this->expression, array('user'=>$user));
  6363. }
  6364. }
  6365. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  6366. {
  6367. private $_errors=array(); // attribute name => array of errors
  6368. private $_validators; // validators
  6369. private $_scenario=''; // scenario
  6370. abstract public function attributeNames();
  6371. public function rules()
  6372. {
  6373. return array();
  6374. }
  6375. public function behaviors()
  6376. {
  6377. return array();
  6378. }
  6379. public function attributeLabels()
  6380. {
  6381. return array();
  6382. }
  6383. public function validate($attributes=null, $clearErrors=true)
  6384. {
  6385. if($clearErrors)
  6386. $this->clearErrors();
  6387. if($this->beforeValidate())
  6388. {
  6389. foreach($this->getValidators() as $validator)
  6390. $validator->validate($this,$attributes);
  6391. $this->afterValidate();
  6392. return !$this->hasErrors();
  6393. }
  6394. else
  6395. return false;
  6396. }
  6397. protected function afterConstruct()
  6398. {
  6399. if($this->hasEventHandler('onAfterConstruct'))
  6400. $this->onAfterConstruct(new CEvent($this));
  6401. }
  6402. protected function beforeValidate()
  6403. {
  6404. $event=new CModelEvent($this);
  6405. $this->onBeforeValidate($event);
  6406. return $event->isValid;
  6407. }
  6408. protected function afterValidate()
  6409. {
  6410. $this->onAfterValidate(new CEvent($this));
  6411. }
  6412. public function onAfterConstruct($event)
  6413. {
  6414. $this->raiseEvent('onAfterConstruct',$event);
  6415. }
  6416. public function onBeforeValidate($event)
  6417. {
  6418. $this->raiseEvent('onBeforeValidate',$event);
  6419. }
  6420. public function onAfterValidate($event)
  6421. {
  6422. $this->raiseEvent('onAfterValidate',$event);
  6423. }
  6424. public function getValidatorList()
  6425. {
  6426. if($this->_validators===null)
  6427. $this->_validators=$this->createValidators();
  6428. return $this->_validators;
  6429. }
  6430. public function getValidators($attribute=null)
  6431. {
  6432. if($this->_validators===null)
  6433. $this->_validators=$this->createValidators();
  6434. $validators=array();
  6435. $scenario=$this->getScenario();
  6436. foreach($this->_validators as $validator)
  6437. {
  6438. if($validator->applyTo($scenario))
  6439. {
  6440. if($attribute===null || in_array($attribute,$validator->attributes,true))
  6441. $validators[]=$validator;
  6442. }
  6443. }
  6444. return $validators;
  6445. }
  6446. public function createValidators()
  6447. {
  6448. $validators=new CList;
  6449. foreach($this->rules() as $rule)
  6450. {
  6451. if(isset($rule[0],$rule[1])) // attributes, validator name
  6452. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  6453. else
  6454. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  6455. array('{class}'=>get_class($this))));
  6456. }
  6457. return $validators;
  6458. }
  6459. public function isAttributeRequired($attribute)
  6460. {
  6461. foreach($this->getValidators($attribute) as $validator)
  6462. {
  6463. if($validator instanceof CRequiredValidator)
  6464. return true;
  6465. }
  6466. return false;
  6467. }
  6468. public function isAttributeSafe($attribute)
  6469. {
  6470. $attributes=$this->getSafeAttributeNames();
  6471. return in_array($attribute,$attributes);
  6472. }
  6473. public function getAttributeLabel($attribute)
  6474. {
  6475. $labels=$this->attributeLabels();
  6476. if(isset($labels[$attribute]))
  6477. return $labels[$attribute];
  6478. else
  6479. return $this->generateAttributeLabel($attribute);
  6480. }
  6481. public function hasErrors($attribute=null)
  6482. {
  6483. if($attribute===null)
  6484. return $this->_errors!==array();
  6485. else
  6486. return isset($this->_errors[$attribute]);
  6487. }
  6488. public function getErrors($attribute=null)
  6489. {
  6490. if($attribute===null)
  6491. return $this->_errors;
  6492. else
  6493. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  6494. }
  6495. public function getError($attribute)
  6496. {
  6497. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  6498. }
  6499. public function addError($attribute,$error)
  6500. {
  6501. $this->_errors[$attribute][]=$error;
  6502. }
  6503. public function addErrors($errors)
  6504. {
  6505. foreach($errors as $attribute=>$error)
  6506. {
  6507. if(is_array($error))
  6508. {
  6509. foreach($error as $e)
  6510. $this->_errors[$attribute][]=$e;
  6511. }
  6512. else
  6513. $this->_errors[$attribute][]=$error;
  6514. }
  6515. }
  6516. public function clearErrors($attribute=null)
  6517. {
  6518. if($attribute===null)
  6519. $this->_errors=array();
  6520. else
  6521. unset($this->_errors[$attribute]);
  6522. }
  6523. public function generateAttributeLabel($name)
  6524. {
  6525. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  6526. }
  6527. public function getAttributes($names=null)
  6528. {
  6529. $values=array();
  6530. foreach($this->attributeNames() as $name)
  6531. $values[$name]=$this->$name;
  6532. if(is_array($names))
  6533. {
  6534. $values2=array();
  6535. foreach($names as $name)
  6536. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  6537. return $values2;
  6538. }
  6539. else
  6540. return $values;
  6541. }
  6542. public function setAttributes($values,$safeOnly=true)
  6543. {
  6544. if(!is_array($values))
  6545. return;
  6546. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  6547. foreach($values as $name=>$value)
  6548. {
  6549. if(isset($attributes[$name]))
  6550. $this->$name=$value;
  6551. else if($safeOnly)
  6552. $this->onUnsafeAttribute($name,$value);
  6553. }
  6554. }
  6555. public function unsetAttributes($names=null)
  6556. {
  6557. if($names===null)
  6558. $names=$this->attributeNames();
  6559. foreach($names as $name)
  6560. $this->$name=null;
  6561. }
  6562. public function onUnsafeAttribute($name,$value)
  6563. {
  6564. if(YII_DEBUG)
  6565. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  6566. }
  6567. public function getScenario()
  6568. {
  6569. return $this->_scenario;
  6570. }
  6571. public function setScenario($value)
  6572. {
  6573. $this->_scenario=$value;
  6574. }
  6575. public function getSafeAttributeNames()
  6576. {
  6577. $attributes=array();
  6578. $unsafe=array();
  6579. foreach($this->getValidators() as $validator)
  6580. {
  6581. if(!$validator->safe)
  6582. {
  6583. foreach($validator->attributes as $name)
  6584. $unsafe[]=$name;
  6585. }
  6586. else
  6587. {
  6588. foreach($validator->attributes as $name)
  6589. $attributes[$name]=true;
  6590. }
  6591. }
  6592. foreach($unsafe as $name)
  6593. unset($attributes[$name]);
  6594. return array_keys($attributes);
  6595. }
  6596. public function getIterator()
  6597. {
  6598. $attributes=$this->getAttributes();
  6599. return new CMapIterator($attributes);
  6600. }
  6601. public function offsetExists($offset)
  6602. {
  6603. return property_exists($this,$offset);
  6604. }
  6605. public function offsetGet($offset)
  6606. {
  6607. return $this->$offset;
  6608. }
  6609. public function offsetSet($offset,$item)
  6610. {
  6611. $this->$offset=$item;
  6612. }
  6613. public function offsetUnset($offset)
  6614. {
  6615. unset($this->$offset);
  6616. }
  6617. }
  6618. abstract class CActiveRecord extends CModel
  6619. {
  6620. const BELONGS_TO='CBelongsToRelation';
  6621. const HAS_ONE='CHasOneRelation';
  6622. const HAS_MANY='CHasManyRelation';
  6623. const MANY_MANY='CManyManyRelation';
  6624. const STAT='CStatRelation';
  6625. public static $db;
  6626. private static $_models=array(); // class name => model
  6627. private $_md; // meta data
  6628. private $_new=false; // whether this instance is new or not
  6629. private $_attributes=array(); // attribute name => attribute value
  6630. private $_related=array(); // attribute name => related objects
  6631. private $_c; // query criteria (used by finder only)
  6632. private $_pk; // old primary key value
  6633. private $_alias='t'; // the table alias being used for query
  6634. public function __construct($scenario='insert')
  6635. {
  6636. if($scenario===null) // internally used by populateRecord() and model()
  6637. return;
  6638. $this->setScenario($scenario);
  6639. $this->setIsNewRecord(true);
  6640. $this->_attributes=$this->getMetaData()->attributeDefaults;
  6641. $this->init();
  6642. $this->attachBehaviors($this->behaviors());
  6643. $this->afterConstruct();
  6644. }
  6645. public function init()
  6646. {
  6647. }
  6648. public function cache($duration, $dependency=null, $queryCount=1)
  6649. {
  6650. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  6651. return $this;
  6652. }
  6653. public function __sleep()
  6654. {
  6655. $this->_md=null;
  6656. return array_keys((array)$this);
  6657. }
  6658. public function __get($name)
  6659. {
  6660. if(isset($this->_attributes[$name]))
  6661. return $this->_attributes[$name];
  6662. else if(isset($this->getMetaData()->columns[$name]))
  6663. return null;
  6664. else if(isset($this->_related[$name]))
  6665. return $this->_related[$name];
  6666. else if(isset($this->getMetaData()->relations[$name]))
  6667. return $this->getRelated($name);
  6668. else
  6669. return parent::__get($name);
  6670. }
  6671. public function __set($name,$value)
  6672. {
  6673. if($this->setAttribute($name,$value)===false)
  6674. {
  6675. if(isset($this->getMetaData()->relations[$name]))
  6676. $this->_related[$name]=$value;
  6677. else
  6678. parent::__set($name,$value);
  6679. }
  6680. }
  6681. public function __isset($name)
  6682. {
  6683. if(isset($this->_attributes[$name]))
  6684. return true;
  6685. else if(isset($this->getMetaData()->columns[$name]))
  6686. return false;
  6687. else if(isset($this->_related[$name]))
  6688. return true;
  6689. else if(isset($this->getMetaData()->relations[$name]))
  6690. return $this->getRelated($name)!==null;
  6691. else
  6692. return parent::__isset($name);
  6693. }
  6694. public function __unset($name)
  6695. {
  6696. if(isset($this->getMetaData()->columns[$name]))
  6697. unset($this->_attributes[$name]);
  6698. else if(isset($this->getMetaData()->relations[$name]))
  6699. unset($this->_related[$name]);
  6700. else
  6701. parent::__unset($name);
  6702. }
  6703. public function __call($name,$parameters)
  6704. {
  6705. if(isset($this->getMetaData()->relations[$name]))
  6706. {
  6707. if(empty($parameters))
  6708. return $this->getRelated($name,false);
  6709. else
  6710. return $this->getRelated($name,false,$parameters[0]);
  6711. }
  6712. $scopes=$this->scopes();
  6713. if(isset($scopes[$name]))
  6714. {
  6715. $this->getDbCriteria()->mergeWith($scopes[$name]);
  6716. return $this;
  6717. }
  6718. return parent::__call($name,$parameters);
  6719. }
  6720. public function getRelated($name,$refresh=false,$params=array())
  6721. {
  6722. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  6723. return $this->_related[$name];
  6724. $md=$this->getMetaData();
  6725. if(!isset($md->relations[$name]))
  6726. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  6727. array('{class}'=>get_class($this), '{name}'=>$name)));
  6728. $relation=$md->relations[$name];
  6729. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  6730. return $relation instanceof CHasOneRelation ? null : array();
  6731. if($params!==array()) // dynamic query
  6732. {
  6733. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6734. if($exists)
  6735. $save=$this->_related[$name];
  6736. $r=array($name=>$params);
  6737. }
  6738. else
  6739. $r=$name;
  6740. unset($this->_related[$name]);
  6741. $finder=new CActiveFinder($this,$r);
  6742. $finder->lazyFind($this);
  6743. if(!isset($this->_related[$name]))
  6744. {
  6745. if($relation instanceof CHasManyRelation)
  6746. $this->_related[$name]=array();
  6747. else if($relation instanceof CStatRelation)
  6748. $this->_related[$name]=$relation->defaultValue;
  6749. else
  6750. $this->_related[$name]=null;
  6751. }
  6752. if($params!==array())
  6753. {
  6754. $results=$this->_related[$name];
  6755. if($exists)
  6756. $this->_related[$name]=$save;
  6757. else
  6758. unset($this->_related[$name]);
  6759. return $results;
  6760. }
  6761. else
  6762. return $this->_related[$name];
  6763. }
  6764. public function hasRelated($name)
  6765. {
  6766. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6767. }
  6768. public function getDbCriteria($createIfNull=true)
  6769. {
  6770. if($this->_c===null)
  6771. {
  6772. if(($c=$this->defaultScope())!==array() || $createIfNull)
  6773. $this->_c=new CDbCriteria($c);
  6774. }
  6775. return $this->_c;
  6776. }
  6777. public function setDbCriteria($criteria)
  6778. {
  6779. $this->_c=$criteria;
  6780. }
  6781. public function defaultScope()
  6782. {
  6783. return array();
  6784. }
  6785. public function resetScope()
  6786. {
  6787. $this->_c=new CDbCriteria();
  6788. return $this;
  6789. }
  6790. public static function model($className=__CLASS__)
  6791. {
  6792. if(isset(self::$_models[$className]))
  6793. return self::$_models[$className];
  6794. else
  6795. {
  6796. $model=self::$_models[$className]=new $className(null);
  6797. $model->_md=new CActiveRecordMetaData($model);
  6798. $model->attachBehaviors($model->behaviors());
  6799. return $model;
  6800. }
  6801. }
  6802. public function getMetaData()
  6803. {
  6804. if($this->_md!==null)
  6805. return $this->_md;
  6806. else
  6807. return $this->_md=self::model(get_class($this))->_md;
  6808. }
  6809. public function refreshMetaData()
  6810. {
  6811. $finder=self::model(get_class($this));
  6812. $finder->_md=new CActiveRecordMetaData($finder);
  6813. if($this!==$finder)
  6814. $this->_md=$finder->_md;
  6815. }
  6816. public function tableName()
  6817. {
  6818. return get_class($this);
  6819. }
  6820. public function primaryKey()
  6821. {
  6822. }
  6823. public function relations()
  6824. {
  6825. return array();
  6826. }
  6827. public function scopes()
  6828. {
  6829. return array();
  6830. }
  6831. public function attributeNames()
  6832. {
  6833. return array_keys($this->getMetaData()->columns);
  6834. }
  6835. public function getAttributeLabel($attribute)
  6836. {
  6837. $labels=$this->attributeLabels();
  6838. if(isset($labels[$attribute]))
  6839. return $labels[$attribute];
  6840. else if(strpos($attribute,'.')!==false)
  6841. {
  6842. $segs=explode('.',$attribute);
  6843. $name=array_pop($segs);
  6844. $model=$this;
  6845. foreach($segs as $seg)
  6846. {
  6847. $relations=$model->getMetaData()->relations;
  6848. if(isset($relations[$seg]))
  6849. $model=CActiveRecord::model($relations[$seg]->className);
  6850. else
  6851. break;
  6852. }
  6853. return $model->getAttributeLabel($name);
  6854. }
  6855. else
  6856. return $this->generateAttributeLabel($attribute);
  6857. }
  6858. public function getDbConnection()
  6859. {
  6860. if(self::$db!==null)
  6861. return self::$db;
  6862. else
  6863. {
  6864. self::$db=Yii::app()->getDb();
  6865. if(self::$db instanceof CDbConnection)
  6866. return self::$db;
  6867. else
  6868. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  6869. }
  6870. }
  6871. public function getActiveRelation($name)
  6872. {
  6873. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  6874. }
  6875. public function getTableSchema()
  6876. {
  6877. return $this->getMetaData()->tableSchema;
  6878. }
  6879. public function getCommandBuilder()
  6880. {
  6881. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  6882. }
  6883. public function hasAttribute($name)
  6884. {
  6885. return isset($this->getMetaData()->columns[$name]);
  6886. }
  6887. public function getAttribute($name)
  6888. {
  6889. if(property_exists($this,$name))
  6890. return $this->$name;
  6891. else if(isset($this->_attributes[$name]))
  6892. return $this->_attributes[$name];
  6893. }
  6894. public function setAttribute($name,$value)
  6895. {
  6896. if(property_exists($this,$name))
  6897. $this->$name=$value;
  6898. else if(isset($this->getMetaData()->columns[$name]))
  6899. $this->_attributes[$name]=$value;
  6900. else
  6901. return false;
  6902. return true;
  6903. }
  6904. public function addRelatedRecord($name,$record,$index)
  6905. {
  6906. if($index!==false)
  6907. {
  6908. if(!isset($this->_related[$name]))
  6909. $this->_related[$name]=array();
  6910. if($record instanceof CActiveRecord)
  6911. {
  6912. if($index===true)
  6913. $this->_related[$name][]=$record;
  6914. else
  6915. $this->_related[$name][$index]=$record;
  6916. }
  6917. }
  6918. else if(!isset($this->_related[$name]))
  6919. $this->_related[$name]=$record;
  6920. }
  6921. public function getAttributes($names=true)
  6922. {
  6923. $attributes=$this->_attributes;
  6924. foreach($this->getMetaData()->columns as $name=>$column)
  6925. {
  6926. if(property_exists($this,$name))
  6927. $attributes[$name]=$this->$name;
  6928. else if($names===true && !isset($attributes[$name]))
  6929. $attributes[$name]=null;
  6930. }
  6931. if(is_array($names))
  6932. {
  6933. $attrs=array();
  6934. foreach($names as $name)
  6935. {
  6936. if(property_exists($this,$name))
  6937. $attrs[$name]=$this->$name;
  6938. else
  6939. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  6940. }
  6941. return $attrs;
  6942. }
  6943. else
  6944. return $attributes;
  6945. }
  6946. public function save($runValidation=true,$attributes=null)
  6947. {
  6948. if(!$runValidation || $this->validate($attributes))
  6949. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  6950. else
  6951. return false;
  6952. }
  6953. public function getIsNewRecord()
  6954. {
  6955. return $this->_new;
  6956. }
  6957. public function setIsNewRecord($value)
  6958. {
  6959. $this->_new=$value;
  6960. }
  6961. public function onBeforeSave($event)
  6962. {
  6963. $this->raiseEvent('onBeforeSave',$event);
  6964. }
  6965. public function onAfterSave($event)
  6966. {
  6967. $this->raiseEvent('onAfterSave',$event);
  6968. }
  6969. public function onBeforeDelete($event)
  6970. {
  6971. $this->raiseEvent('onBeforeDelete',$event);
  6972. }
  6973. public function onAfterDelete($event)
  6974. {
  6975. $this->raiseEvent('onAfterDelete',$event);
  6976. }
  6977. public function onBeforeFind($event)
  6978. {
  6979. $this->raiseEvent('onBeforeFind',$event);
  6980. }
  6981. public function onAfterFind($event)
  6982. {
  6983. $this->raiseEvent('onAfterFind',$event);
  6984. }
  6985. protected function beforeSave()
  6986. {
  6987. if($this->hasEventHandler('onBeforeSave'))
  6988. {
  6989. $event=new CModelEvent($this);
  6990. $this->onBeforeSave($event);
  6991. return $event->isValid;
  6992. }
  6993. else
  6994. return true;
  6995. }
  6996. protected function afterSave()
  6997. {
  6998. if($this->hasEventHandler('onAfterSave'))
  6999. $this->onAfterSave(new CEvent($this));
  7000. }
  7001. protected function beforeDelete()
  7002. {
  7003. if($this->hasEventHandler('onBeforeDelete'))
  7004. {
  7005. $event=new CModelEvent($this);
  7006. $this->onBeforeDelete($event);
  7007. return $event->isValid;
  7008. }
  7009. else
  7010. return true;
  7011. }
  7012. protected function afterDelete()
  7013. {
  7014. if($this->hasEventHandler('onAfterDelete'))
  7015. $this->onAfterDelete(new CEvent($this));
  7016. }
  7017. protected function beforeFind()
  7018. {
  7019. if($this->hasEventHandler('onBeforeFind'))
  7020. {
  7021. $event=new CModelEvent($this);
  7022. // for backward compatibility
  7023. $event->criteria=func_num_args()>0 ? func_get_arg(0) : null;
  7024. $this->onBeforeFind($event);
  7025. }
  7026. }
  7027. protected function afterFind()
  7028. {
  7029. if($this->hasEventHandler('onAfterFind'))
  7030. $this->onAfterFind(new CEvent($this));
  7031. }
  7032. public function beforeFindInternal()
  7033. {
  7034. $this->beforeFind();
  7035. }
  7036. public function afterFindInternal()
  7037. {
  7038. $this->afterFind();
  7039. }
  7040. public function insert($attributes=null)
  7041. {
  7042. if(!$this->getIsNewRecord())
  7043. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  7044. if($this->beforeSave())
  7045. {
  7046. $builder=$this->getCommandBuilder();
  7047. $table=$this->getMetaData()->tableSchema;
  7048. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  7049. if($command->execute())
  7050. {
  7051. $primaryKey=$table->primaryKey;
  7052. if($table->sequenceName!==null)
  7053. {
  7054. if(is_string($primaryKey) && $this->$primaryKey===null)
  7055. $this->$primaryKey=$builder->getLastInsertID($table);
  7056. else if(is_array($primaryKey))
  7057. {
  7058. foreach($primaryKey as $pk)
  7059. {
  7060. if($this->$pk===null)
  7061. {
  7062. $this->$pk=$builder->getLastInsertID($table);
  7063. break;
  7064. }
  7065. }
  7066. }
  7067. }
  7068. $this->_pk=$this->getPrimaryKey();
  7069. $this->afterSave();
  7070. $this->setIsNewRecord(false);
  7071. $this->setScenario('update');
  7072. return true;
  7073. }
  7074. }
  7075. return false;
  7076. }
  7077. public function update($attributes=null)
  7078. {
  7079. if($this->getIsNewRecord())
  7080. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7081. if($this->beforeSave())
  7082. {
  7083. if($this->_pk===null)
  7084. $this->_pk=$this->getPrimaryKey();
  7085. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  7086. $this->_pk=$this->getPrimaryKey();
  7087. $this->afterSave();
  7088. return true;
  7089. }
  7090. else
  7091. return false;
  7092. }
  7093. public function saveAttributes($attributes)
  7094. {
  7095. if(!$this->getIsNewRecord())
  7096. {
  7097. $values=array();
  7098. foreach($attributes as $name=>$value)
  7099. {
  7100. if(is_integer($name))
  7101. $values[$value]=$this->$value;
  7102. else
  7103. $values[$name]=$this->$name=$value;
  7104. }
  7105. if($this->_pk===null)
  7106. $this->_pk=$this->getPrimaryKey();
  7107. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  7108. {
  7109. $this->_pk=$this->getPrimaryKey();
  7110. return true;
  7111. }
  7112. else
  7113. return false;
  7114. }
  7115. else
  7116. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7117. }
  7118. public function saveCounters($counters)
  7119. {
  7120. $builder=$this->getCommandBuilder();
  7121. $table=$this->getTableSchema();
  7122. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  7123. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7124. if($command->execute())
  7125. {
  7126. foreach($counters as $name=>$value)
  7127. $this->$name=$this->$name+$value;
  7128. return true;
  7129. }
  7130. else
  7131. return false;
  7132. }
  7133. public function delete()
  7134. {
  7135. if(!$this->getIsNewRecord())
  7136. {
  7137. if($this->beforeDelete())
  7138. {
  7139. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  7140. $this->afterDelete();
  7141. return $result;
  7142. }
  7143. else
  7144. return false;
  7145. }
  7146. else
  7147. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  7148. }
  7149. public function refresh()
  7150. {
  7151. if(!$this->getIsNewRecord() && ($record=$this->findByPk($this->getPrimaryKey()))!==null)
  7152. {
  7153. $this->_attributes=array();
  7154. $this->_related=array();
  7155. foreach($this->getMetaData()->columns as $name=>$column)
  7156. {
  7157. if(property_exists($this,$name))
  7158. $this->$name=$record->$name;
  7159. else
  7160. $this->_attributes[$name]=$record->$name;
  7161. }
  7162. return true;
  7163. }
  7164. else
  7165. return false;
  7166. }
  7167. public function equals($record)
  7168. {
  7169. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  7170. }
  7171. public function getPrimaryKey()
  7172. {
  7173. $table=$this->getMetaData()->tableSchema;
  7174. if(is_string($table->primaryKey))
  7175. return $this->{$table->primaryKey};
  7176. else if(is_array($table->primaryKey))
  7177. {
  7178. $values=array();
  7179. foreach($table->primaryKey as $name)
  7180. $values[$name]=$this->$name;
  7181. return $values;
  7182. }
  7183. else
  7184. return null;
  7185. }
  7186. public function setPrimaryKey($value)
  7187. {
  7188. $this->_pk=$this->getPrimaryKey();
  7189. $table=$this->getMetaData()->tableSchema;
  7190. if(is_string($table->primaryKey))
  7191. $this->{$table->primaryKey}=$value;
  7192. else if(is_array($table->primaryKey))
  7193. {
  7194. foreach($table->primaryKey as $name)
  7195. $this->$name=$value[$name];
  7196. }
  7197. }
  7198. public function getOldPrimaryKey()
  7199. {
  7200. return $this->_pk;
  7201. }
  7202. public function setOldPrimaryKey($value)
  7203. {
  7204. $this->_pk=$value;
  7205. }
  7206. protected function query($criteria,$all=false)
  7207. {
  7208. $this->beforeFind();
  7209. $this->applyScopes($criteria);
  7210. if(empty($criteria->with))
  7211. {
  7212. if(!$all)
  7213. $criteria->limit=1;
  7214. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  7215. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  7216. }
  7217. else
  7218. {
  7219. $finder=new CActiveFinder($this,$criteria->with);
  7220. return $finder->query($criteria,$all);
  7221. }
  7222. }
  7223. public function applyScopes(&$criteria)
  7224. {
  7225. if(!empty($criteria->scopes))
  7226. {
  7227. $scs=$this->scopes();
  7228. $c=$this->getDbCriteria();
  7229. foreach((array)$criteria->scopes as $k=>$v)
  7230. {
  7231. if(is_integer($k))
  7232. {
  7233. if(is_string($v))
  7234. {
  7235. if(isset($scs[$v]))
  7236. {
  7237. $c->mergeWith($scs[$v],true);
  7238. continue;
  7239. }
  7240. $scope=$v;
  7241. $params=array();
  7242. }
  7243. else if(is_array($v))
  7244. {
  7245. $scope=key($v);
  7246. $params=current($v);
  7247. }
  7248. }
  7249. else if(is_string($k))
  7250. {
  7251. $scope=$k;
  7252. $params=$v;
  7253. }
  7254. call_user_func_array(array($this,$scope),(array)$params);
  7255. }
  7256. }
  7257. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  7258. {
  7259. $c->mergeWith($criteria);
  7260. $criteria=$c;
  7261. $this->_c=null;
  7262. }
  7263. }
  7264. public function getTableAlias($quote=false, $checkScopes=true)
  7265. {
  7266. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  7267. $alias=$criteria->alias;
  7268. else
  7269. $alias=$this->_alias;
  7270. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  7271. }
  7272. public function setTableAlias($alias)
  7273. {
  7274. $this->_alias=$alias;
  7275. }
  7276. public function find($condition='',$params=array())
  7277. {
  7278. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7279. return $this->query($criteria);
  7280. }
  7281. public function findAll($condition='',$params=array())
  7282. {
  7283. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7284. return $this->query($criteria,true);
  7285. }
  7286. public function findByPk($pk,$condition='',$params=array())
  7287. {
  7288. $prefix=$this->getTableAlias(true).'.';
  7289. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7290. return $this->query($criteria);
  7291. }
  7292. public function findAllByPk($pk,$condition='',$params=array())
  7293. {
  7294. $prefix=$this->getTableAlias(true).'.';
  7295. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7296. return $this->query($criteria,true);
  7297. }
  7298. public function findByAttributes($attributes,$condition='',$params=array())
  7299. {
  7300. $prefix=$this->getTableAlias(true).'.';
  7301. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7302. return $this->query($criteria);
  7303. }
  7304. public function findAllByAttributes($attributes,$condition='',$params=array())
  7305. {
  7306. $prefix=$this->getTableAlias(true).'.';
  7307. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7308. return $this->query($criteria,true);
  7309. }
  7310. public function findBySql($sql,$params=array())
  7311. {
  7312. $this->beforeFind();
  7313. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7314. {
  7315. $this->_c=null;
  7316. $finder=new CActiveFinder($this,$criteria->with);
  7317. return $finder->findBySql($sql,$params);
  7318. }
  7319. else
  7320. {
  7321. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7322. return $this->populateRecord($command->queryRow());
  7323. }
  7324. }
  7325. public function findAllBySql($sql,$params=array())
  7326. {
  7327. $this->beforeFind();
  7328. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7329. {
  7330. $this->_c=null;
  7331. $finder=new CActiveFinder($this,$criteria->with);
  7332. return $finder->findAllBySql($sql,$params);
  7333. }
  7334. else
  7335. {
  7336. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7337. return $this->populateRecords($command->queryAll());
  7338. }
  7339. }
  7340. public function count($condition='',$params=array())
  7341. {
  7342. $builder=$this->getCommandBuilder();
  7343. $criteria=$builder->createCriteria($condition,$params);
  7344. $this->applyScopes($criteria);
  7345. if(empty($criteria->with))
  7346. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7347. else
  7348. {
  7349. $finder=new CActiveFinder($this,$criteria->with);
  7350. return $finder->count($criteria);
  7351. }
  7352. }
  7353. public function countByAttributes($attributes,$condition='',$params=array())
  7354. {
  7355. $prefix=$this->getTableAlias(true).'.';
  7356. $builder=$this->getCommandBuilder();
  7357. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7358. $this->applyScopes($criteria);
  7359. if(empty($criteria->with))
  7360. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7361. else
  7362. {
  7363. $finder=new CActiveFinder($this,$criteria->with);
  7364. return $finder->count($criteria);
  7365. }
  7366. }
  7367. public function countBySql($sql,$params=array())
  7368. {
  7369. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  7370. }
  7371. public function exists($condition='',$params=array())
  7372. {
  7373. $builder=$this->getCommandBuilder();
  7374. $criteria=$builder->createCriteria($condition,$params);
  7375. $table=$this->getTableSchema();
  7376. $criteria->select='1';
  7377. $criteria->limit=1;
  7378. $this->applyScopes($criteria);
  7379. if(empty($criteria->with))
  7380. return $builder->createFindCommand($table,$criteria)->queryRow()!==false;
  7381. else
  7382. {
  7383. $criteria->select='*';
  7384. $finder=new CActiveFinder($this,$criteria->with);
  7385. return $finder->count($criteria)>0;
  7386. }
  7387. }
  7388. public function with()
  7389. {
  7390. if(func_num_args()>0)
  7391. {
  7392. $with=func_get_args();
  7393. if(is_array($with[0])) // the parameter is given as an array
  7394. $with=$with[0];
  7395. if(!empty($with))
  7396. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  7397. }
  7398. return $this;
  7399. }
  7400. public function together()
  7401. {
  7402. $this->getDbCriteria()->together=true;
  7403. return $this;
  7404. }
  7405. public function updateByPk($pk,$attributes,$condition='',$params=array())
  7406. {
  7407. $builder=$this->getCommandBuilder();
  7408. $table=$this->getTableSchema();
  7409. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  7410. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  7411. return $command->execute();
  7412. }
  7413. public function updateAll($attributes,$condition='',$params=array())
  7414. {
  7415. $builder=$this->getCommandBuilder();
  7416. $criteria=$builder->createCriteria($condition,$params);
  7417. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  7418. return $command->execute();
  7419. }
  7420. public function updateCounters($counters,$condition='',$params=array())
  7421. {
  7422. $builder=$this->getCommandBuilder();
  7423. $criteria=$builder->createCriteria($condition,$params);
  7424. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7425. return $command->execute();
  7426. }
  7427. public function deleteByPk($pk,$condition='',$params=array())
  7428. {
  7429. $builder=$this->getCommandBuilder();
  7430. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  7431. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7432. return $command->execute();
  7433. }
  7434. public function deleteAll($condition='',$params=array())
  7435. {
  7436. $builder=$this->getCommandBuilder();
  7437. $criteria=$builder->createCriteria($condition,$params);
  7438. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7439. return $command->execute();
  7440. }
  7441. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  7442. {
  7443. $builder=$this->getCommandBuilder();
  7444. $table=$this->getTableSchema();
  7445. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  7446. $command=$builder->createDeleteCommand($table,$criteria);
  7447. return $command->execute();
  7448. }
  7449. public function populateRecord($attributes,$callAfterFind=true)
  7450. {
  7451. if($attributes!==false)
  7452. {
  7453. $record=$this->instantiate($attributes);
  7454. $record->setScenario('update');
  7455. $record->init();
  7456. $md=$record->getMetaData();
  7457. foreach($attributes as $name=>$value)
  7458. {
  7459. if(property_exists($record,$name))
  7460. $record->$name=$value;
  7461. else if(isset($md->columns[$name]))
  7462. $record->_attributes[$name]=$value;
  7463. }
  7464. $record->_pk=$record->getPrimaryKey();
  7465. $record->attachBehaviors($record->behaviors());
  7466. if($callAfterFind)
  7467. $record->afterFind();
  7468. return $record;
  7469. }
  7470. else
  7471. return null;
  7472. }
  7473. public function populateRecords($data,$callAfterFind=true,$index=null)
  7474. {
  7475. $records=array();
  7476. foreach($data as $attributes)
  7477. {
  7478. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  7479. {
  7480. if($index===null)
  7481. $records[]=$record;
  7482. else
  7483. $records[$record->$index]=$record;
  7484. }
  7485. }
  7486. return $records;
  7487. }
  7488. protected function instantiate($attributes)
  7489. {
  7490. $class=get_class($this);
  7491. $model=new $class(null);
  7492. return $model;
  7493. }
  7494. public function offsetExists($offset)
  7495. {
  7496. return $this->__isset($offset);
  7497. }
  7498. }
  7499. class CBaseActiveRelation extends CComponent
  7500. {
  7501. public $name;
  7502. public $className;
  7503. public $foreignKey;
  7504. public $select='*';
  7505. public $condition='';
  7506. public $params=array();
  7507. public $group='';
  7508. public $join='';
  7509. public $having='';
  7510. public $order='';
  7511. public function __construct($name,$className,$foreignKey,$options=array())
  7512. {
  7513. $this->name=$name;
  7514. $this->className=$className;
  7515. $this->foreignKey=$foreignKey;
  7516. foreach($options as $name=>$value)
  7517. $this->$name=$value;
  7518. }
  7519. public function mergeWith($criteria,$fromScope=false)
  7520. {
  7521. if($criteria instanceof CDbCriteria)
  7522. $criteria=$criteria->toArray();
  7523. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  7524. {
  7525. if($this->select==='*')
  7526. $this->select=$criteria['select'];
  7527. else if($criteria['select']!=='*')
  7528. {
  7529. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  7530. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  7531. $this->select=array_merge($select1,array_diff($select2,$select1));
  7532. }
  7533. }
  7534. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  7535. {
  7536. if($this->condition==='')
  7537. $this->condition=$criteria['condition'];
  7538. else if($criteria['condition']!=='')
  7539. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  7540. }
  7541. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  7542. $this->params=array_merge($this->params,$criteria['params']);
  7543. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  7544. {
  7545. if($this->order==='')
  7546. $this->order=$criteria['order'];
  7547. else if($criteria['order']!=='')
  7548. $this->order=$criteria['order'].', '.$this->order;
  7549. }
  7550. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  7551. {
  7552. if($this->group==='')
  7553. $this->group=$criteria['group'];
  7554. else if($criteria['group']!=='')
  7555. $this->group.=', '.$criteria['group'];
  7556. }
  7557. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  7558. {
  7559. if($this->join==='')
  7560. $this->join=$criteria['join'];
  7561. else if($criteria['join']!=='')
  7562. $this->join.=' '.$criteria['join'];
  7563. }
  7564. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  7565. {
  7566. if($this->having==='')
  7567. $this->having=$criteria['having'];
  7568. else if($criteria['having']!=='')
  7569. $this->having="({$this->having}) AND ({$criteria['having']})";
  7570. }
  7571. }
  7572. }
  7573. class CStatRelation extends CBaseActiveRelation
  7574. {
  7575. public $select='COUNT(*)';
  7576. public $defaultValue=0;
  7577. public function mergeWith($criteria,$fromScope=false)
  7578. {
  7579. if($criteria instanceof CDbCriteria)
  7580. $criteria=$criteria->toArray();
  7581. parent::mergeWith($criteria,$fromScope);
  7582. if(isset($criteria['defaultValue']))
  7583. $this->defaultValue=$criteria['defaultValue'];
  7584. }
  7585. }
  7586. class CActiveRelation extends CBaseActiveRelation
  7587. {
  7588. public $joinType='LEFT OUTER JOIN';
  7589. public $on='';
  7590. public $alias;
  7591. public $with=array();
  7592. public $together;
  7593. public $scopes;
  7594. public function mergeWith($criteria,$fromScope=false)
  7595. {
  7596. if($criteria instanceof CDbCriteria)
  7597. $criteria=$criteria->toArray();
  7598. if($fromScope)
  7599. {
  7600. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  7601. {
  7602. if($this->on==='')
  7603. $this->on=$criteria['condition'];
  7604. else if($criteria['condition']!=='')
  7605. $this->on="({$this->on}) AND ({$criteria['condition']})";
  7606. }
  7607. unset($criteria['condition']);
  7608. }
  7609. parent::mergeWith($criteria);
  7610. if(isset($criteria['joinType']))
  7611. $this->joinType=$criteria['joinType'];
  7612. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  7613. {
  7614. if($this->on==='')
  7615. $this->on=$criteria['on'];
  7616. else if($criteria['on']!=='')
  7617. $this->on="({$this->on}) AND ({$criteria['on']})";
  7618. }
  7619. if(isset($criteria['with']))
  7620. $this->with=$criteria['with'];
  7621. if(isset($criteria['alias']))
  7622. $this->alias=$criteria['alias'];
  7623. if(isset($criteria['together']))
  7624. $this->together=$criteria['together'];
  7625. }
  7626. }
  7627. class CBelongsToRelation extends CActiveRelation
  7628. {
  7629. }
  7630. class CHasOneRelation extends CActiveRelation
  7631. {
  7632. public $through;
  7633. }
  7634. class CHasManyRelation extends CActiveRelation
  7635. {
  7636. public $limit=-1;
  7637. public $offset=-1;
  7638. public $index;
  7639. public $through;
  7640. public function mergeWith($criteria,$fromScope=false)
  7641. {
  7642. if($criteria instanceof CDbCriteria)
  7643. $criteria=$criteria->toArray();
  7644. parent::mergeWith($criteria,$fromScope);
  7645. if(isset($criteria['limit']) && $criteria['limit']>0)
  7646. $this->limit=$criteria['limit'];
  7647. if(isset($criteria['offset']) && $criteria['offset']>=0)
  7648. $this->offset=$criteria['offset'];
  7649. if(isset($criteria['index']))
  7650. $this->index=$criteria['index'];
  7651. }
  7652. }
  7653. class CManyManyRelation extends CHasManyRelation
  7654. {
  7655. }
  7656. class CActiveRecordMetaData
  7657. {
  7658. public $tableSchema;
  7659. public $columns;
  7660. public $relations=array();
  7661. public $attributeDefaults=array();
  7662. private $_model;
  7663. public function __construct($model)
  7664. {
  7665. $this->_model=$model;
  7666. $tableName=$model->tableName();
  7667. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  7668. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  7669. array('{class}'=>get_class($model),'{table}'=>$tableName)));
  7670. if($table->primaryKey===null)
  7671. {
  7672. $table->primaryKey=$model->primaryKey();
  7673. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  7674. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  7675. else if(is_array($table->primaryKey))
  7676. {
  7677. foreach($table->primaryKey as $name)
  7678. {
  7679. if(isset($table->columns[$name]))
  7680. $table->columns[$name]->isPrimaryKey=true;
  7681. }
  7682. }
  7683. }
  7684. $this->tableSchema=$table;
  7685. $this->columns=$table->columns;
  7686. foreach($table->columns as $name=>$column)
  7687. {
  7688. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  7689. $this->attributeDefaults[$name]=$column->defaultValue;
  7690. }
  7691. foreach($model->relations() as $name=>$config)
  7692. {
  7693. $this->addRelation($name,$config);
  7694. }
  7695. }
  7696. public function addRelation($name,$config)
  7697. {
  7698. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  7699. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  7700. else
  7701. 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)));
  7702. }
  7703. public function hasRelation($name)
  7704. {
  7705. return isset($this->relations[$name]);
  7706. }
  7707. public function removeRelation($name)
  7708. {
  7709. unset($this->relations[$name]);
  7710. }
  7711. }
  7712. class CDbConnection extends CApplicationComponent
  7713. {
  7714. public $connectionString;
  7715. public $username='';
  7716. public $password='';
  7717. public $schemaCachingDuration=0;
  7718. public $schemaCachingExclude=array();
  7719. public $schemaCacheID='cache';
  7720. public $queryCachingDuration=0;
  7721. public $queryCachingDependency;
  7722. public $queryCachingCount=0;
  7723. public $queryCacheID='cache';
  7724. public $autoConnect=true;
  7725. public $charset;
  7726. public $emulatePrepare;
  7727. public $enableParamLogging=false;
  7728. public $enableProfiling=false;
  7729. public $tablePrefix;
  7730. public $initSQLs;
  7731. public $driverMap=array(
  7732. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  7733. 'mysqli'=>'CMysqlSchema', // MySQL
  7734. 'mysql'=>'CMysqlSchema', // MySQL
  7735. 'sqlite'=>'CSqliteSchema', // sqlite 3
  7736. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  7737. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  7738. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  7739. 'sqlsrv'=>'CMssqlSchema', // Mssql
  7740. 'oci'=>'COciSchema', // Oracle driver
  7741. );
  7742. public $pdoClass = 'PDO';
  7743. private $_attributes=array();
  7744. private $_active=false;
  7745. private $_pdo;
  7746. private $_transaction;
  7747. private $_schema;
  7748. public function __construct($dsn='',$username='',$password='')
  7749. {
  7750. $this->connectionString=$dsn;
  7751. $this->username=$username;
  7752. $this->password=$password;
  7753. }
  7754. public function __sleep()
  7755. {
  7756. $this->close();
  7757. return array_keys(get_object_vars($this));
  7758. }
  7759. public static function getAvailableDrivers()
  7760. {
  7761. return PDO::getAvailableDrivers();
  7762. }
  7763. public function init()
  7764. {
  7765. parent::init();
  7766. if($this->autoConnect)
  7767. $this->setActive(true);
  7768. }
  7769. public function getActive()
  7770. {
  7771. return $this->_active;
  7772. }
  7773. public function setActive($value)
  7774. {
  7775. if($value!=$this->_active)
  7776. {
  7777. if($value)
  7778. $this->open();
  7779. else
  7780. $this->close();
  7781. }
  7782. }
  7783. public function cache($duration, $dependency=null, $queryCount=1)
  7784. {
  7785. $this->queryCachingDuration=$duration;
  7786. $this->queryCachingDependency=$dependency;
  7787. $this->queryCachingCount=$queryCount;
  7788. return $this;
  7789. }
  7790. protected function open()
  7791. {
  7792. if($this->_pdo===null)
  7793. {
  7794. if(empty($this->connectionString))
  7795. throw new CDbException(Yii::t('yii','CDbConnection.connectionString cannot be empty.'));
  7796. try
  7797. {
  7798. $this->_pdo=$this->createPdoInstance();
  7799. $this->initConnection($this->_pdo);
  7800. $this->_active=true;
  7801. }
  7802. catch(PDOException $e)
  7803. {
  7804. if(YII_DEBUG)
  7805. {
  7806. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection: {error}',
  7807. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$e->errorInfo);
  7808. }
  7809. else
  7810. {
  7811. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  7812. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'),(int)$e->getCode(),$e->errorInfo);
  7813. }
  7814. }
  7815. }
  7816. }
  7817. protected function close()
  7818. {
  7819. $this->_pdo=null;
  7820. $this->_active=false;
  7821. $this->_schema=null;
  7822. }
  7823. protected function createPdoInstance()
  7824. {
  7825. $pdoClass=$this->pdoClass;
  7826. if(($pos=strpos($this->connectionString,':'))!==false)
  7827. {
  7828. $driver=strtolower(substr($this->connectionString,0,$pos));
  7829. if($driver==='mssql' || $driver==='dblib' || $driver==='sqlsrv')
  7830. $pdoClass='CMssqlPdoAdapter';
  7831. }
  7832. return new $pdoClass($this->connectionString,$this->username,
  7833. $this->password,$this->_attributes);
  7834. }
  7835. protected function initConnection($pdo)
  7836. {
  7837. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  7838. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  7839. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  7840. if($this->charset!==null)
  7841. {
  7842. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  7843. if(in_array($driver,array('pgsql','mysql','mysqli')))
  7844. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  7845. }
  7846. if($this->initSQLs!==null)
  7847. {
  7848. foreach($this->initSQLs as $sql)
  7849. $pdo->exec($sql);
  7850. }
  7851. }
  7852. public function getPdoInstance()
  7853. {
  7854. return $this->_pdo;
  7855. }
  7856. public function createCommand($query=null)
  7857. {
  7858. $this->setActive(true);
  7859. return new CDbCommand($this,$query);
  7860. }
  7861. public function getCurrentTransaction()
  7862. {
  7863. if($this->_transaction!==null)
  7864. {
  7865. if($this->_transaction->getActive())
  7866. return $this->_transaction;
  7867. }
  7868. return null;
  7869. }
  7870. public function beginTransaction()
  7871. {
  7872. $this->setActive(true);
  7873. $this->_pdo->beginTransaction();
  7874. return $this->_transaction=new CDbTransaction($this);
  7875. }
  7876. public function getSchema()
  7877. {
  7878. if($this->_schema!==null)
  7879. return $this->_schema;
  7880. else
  7881. {
  7882. $driver=$this->getDriverName();
  7883. if(isset($this->driverMap[$driver]))
  7884. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  7885. else
  7886. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  7887. array('{driver}'=>$driver)));
  7888. }
  7889. }
  7890. public function getCommandBuilder()
  7891. {
  7892. return $this->getSchema()->getCommandBuilder();
  7893. }
  7894. public function getLastInsertID($sequenceName='')
  7895. {
  7896. $this->setActive(true);
  7897. return $this->_pdo->lastInsertId($sequenceName);
  7898. }
  7899. public function quoteValue($str)
  7900. {
  7901. if(is_int($str) || is_float($str))
  7902. return $str;
  7903. $this->setActive(true);
  7904. if(($value=$this->_pdo->quote($str))!==false)
  7905. return $value;
  7906. else // the driver doesn't support quote (e.g. oci)
  7907. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  7908. }
  7909. public function quoteTableName($name)
  7910. {
  7911. return $this->getSchema()->quoteTableName($name);
  7912. }
  7913. public function quoteColumnName($name)
  7914. {
  7915. return $this->getSchema()->quoteColumnName($name);
  7916. }
  7917. public function getPdoType($type)
  7918. {
  7919. static $map=array
  7920. (
  7921. 'boolean'=>PDO::PARAM_BOOL,
  7922. 'integer'=>PDO::PARAM_INT,
  7923. 'string'=>PDO::PARAM_STR,
  7924. 'NULL'=>PDO::PARAM_NULL,
  7925. );
  7926. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  7927. }
  7928. public function getColumnCase()
  7929. {
  7930. return $this->getAttribute(PDO::ATTR_CASE);
  7931. }
  7932. public function setColumnCase($value)
  7933. {
  7934. $this->setAttribute(PDO::ATTR_CASE,$value);
  7935. }
  7936. public function getNullConversion()
  7937. {
  7938. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  7939. }
  7940. public function setNullConversion($value)
  7941. {
  7942. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  7943. }
  7944. public function getAutoCommit()
  7945. {
  7946. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  7947. }
  7948. public function setAutoCommit($value)
  7949. {
  7950. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  7951. }
  7952. public function getPersistent()
  7953. {
  7954. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  7955. }
  7956. public function setPersistent($value)
  7957. {
  7958. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  7959. }
  7960. public function getDriverName()
  7961. {
  7962. if(($pos=strpos($this->connectionString, ':'))!==false)
  7963. return strtolower(substr($this->connectionString, 0, $pos));
  7964. // return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  7965. }
  7966. public function getClientVersion()
  7967. {
  7968. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  7969. }
  7970. public function getConnectionStatus()
  7971. {
  7972. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  7973. }
  7974. public function getPrefetch()
  7975. {
  7976. return $this->getAttribute(PDO::ATTR_PREFETCH);
  7977. }
  7978. public function getServerInfo()
  7979. {
  7980. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  7981. }
  7982. public function getServerVersion()
  7983. {
  7984. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  7985. }
  7986. public function getTimeout()
  7987. {
  7988. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  7989. }
  7990. public function getAttribute($name)
  7991. {
  7992. $this->setActive(true);
  7993. return $this->_pdo->getAttribute($name);
  7994. }
  7995. public function setAttribute($name,$value)
  7996. {
  7997. if($this->_pdo instanceof PDO)
  7998. $this->_pdo->setAttribute($name,$value);
  7999. else
  8000. $this->_attributes[$name]=$value;
  8001. }
  8002. public function getAttributes()
  8003. {
  8004. return $this->_attributes;
  8005. }
  8006. public function setAttributes($values)
  8007. {
  8008. foreach($values as $name=>$value)
  8009. $this->_attributes[$name]=$value;
  8010. }
  8011. public function getStats()
  8012. {
  8013. $logger=Yii::getLogger();
  8014. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  8015. $count=count($timings);
  8016. $time=array_sum($timings);
  8017. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  8018. $count+=count($timings);
  8019. $time+=array_sum($timings);
  8020. return array($count,$time);
  8021. }
  8022. }
  8023. abstract class CDbSchema extends CComponent
  8024. {
  8025. public $columnTypes=array();
  8026. private $_tableNames=array();
  8027. private $_tables=array();
  8028. private $_connection;
  8029. private $_builder;
  8030. private $_cacheExclude=array();
  8031. abstract protected function loadTable($name);
  8032. public function __construct($conn)
  8033. {
  8034. $this->_connection=$conn;
  8035. foreach($conn->schemaCachingExclude as $name)
  8036. $this->_cacheExclude[$name]=true;
  8037. }
  8038. public function getDbConnection()
  8039. {
  8040. return $this->_connection;
  8041. }
  8042. public function getTable($name,$refresh=false)
  8043. {
  8044. if($refresh===false && isset($this->_tables[$name]))
  8045. return $this->_tables[$name];
  8046. else
  8047. {
  8048. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  8049. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  8050. else
  8051. $realName=$name;
  8052. // temporarily disable query caching
  8053. if($this->_connection->queryCachingDuration>0)
  8054. {
  8055. $qcDuration=$this->_connection->queryCachingDuration;
  8056. $this->_connection->queryCachingDuration=0;
  8057. }
  8058. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8059. {
  8060. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8061. $table=$cache->get($key);
  8062. if($refresh===true || $table===false)
  8063. {
  8064. $table=$this->loadTable($realName);
  8065. if($table!==null)
  8066. $cache->set($key,$table,$duration);
  8067. }
  8068. $this->_tables[$name]=$table;
  8069. }
  8070. else
  8071. $this->_tables[$name]=$table=$this->loadTable($realName);
  8072. if(isset($qcDuration)) // re-enable query caching
  8073. $this->_connection->queryCachingDuration=$qcDuration;
  8074. return $table;
  8075. }
  8076. }
  8077. public function getTables($schema='')
  8078. {
  8079. $tables=array();
  8080. foreach($this->getTableNames($schema) as $name)
  8081. {
  8082. if(($table=$this->getTable($name))!==null)
  8083. $tables[$name]=$table;
  8084. }
  8085. return $tables;
  8086. }
  8087. public function getTableNames($schema='')
  8088. {
  8089. if(!isset($this->_tableNames[$schema]))
  8090. $this->_tableNames[$schema]=$this->findTableNames($schema);
  8091. return $this->_tableNames[$schema];
  8092. }
  8093. public function getCommandBuilder()
  8094. {
  8095. if($this->_builder!==null)
  8096. return $this->_builder;
  8097. else
  8098. return $this->_builder=$this->createCommandBuilder();
  8099. }
  8100. public function refresh()
  8101. {
  8102. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8103. {
  8104. foreach(array_keys($this->_tables) as $name)
  8105. {
  8106. if(!isset($this->_cacheExclude[$name]))
  8107. {
  8108. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8109. $cache->delete($key);
  8110. }
  8111. }
  8112. }
  8113. $this->_tables=array();
  8114. $this->_tableNames=array();
  8115. $this->_builder=null;
  8116. }
  8117. public function quoteTableName($name)
  8118. {
  8119. if(strpos($name,'.')===false)
  8120. return $this->quoteSimpleTableName($name);
  8121. $parts=explode('.',$name);
  8122. foreach($parts as $i=>$part)
  8123. $parts[$i]=$this->quoteSimpleTableName($part);
  8124. return implode('.',$parts);
  8125. }
  8126. public function quoteSimpleTableName($name)
  8127. {
  8128. return "'".$name."'";
  8129. }
  8130. public function quoteColumnName($name)
  8131. {
  8132. if(($pos=strrpos($name,'.'))!==false)
  8133. {
  8134. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  8135. $name=substr($name,$pos+1);
  8136. }
  8137. else
  8138. $prefix='';
  8139. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  8140. }
  8141. public function quoteSimpleColumnName($name)
  8142. {
  8143. return '"'.$name.'"';
  8144. }
  8145. public function compareTableNames($name1,$name2)
  8146. {
  8147. $name1=str_replace(array('"','`',"'"),'',$name1);
  8148. $name2=str_replace(array('"','`',"'"),'',$name2);
  8149. if(($pos=strrpos($name1,'.'))!==false)
  8150. $name1=substr($name1,$pos+1);
  8151. if(($pos=strrpos($name2,'.'))!==false)
  8152. $name2=substr($name2,$pos+1);
  8153. if($this->_connection->tablePrefix!==null)
  8154. {
  8155. if(strpos($name1,'{')!==false)
  8156. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  8157. if(strpos($name2,'{')!==false)
  8158. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  8159. }
  8160. return $name1===$name2;
  8161. }
  8162. public function resetSequence($table,$value=null)
  8163. {
  8164. }
  8165. public function checkIntegrity($check=true,$schema='')
  8166. {
  8167. }
  8168. protected function createCommandBuilder()
  8169. {
  8170. return new CDbCommandBuilder($this);
  8171. }
  8172. protected function findTableNames($schema='')
  8173. {
  8174. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  8175. array('{class}'=>get_class($this))));
  8176. }
  8177. public function getColumnType($type)
  8178. {
  8179. if(isset($this->columnTypes[$type]))
  8180. return $this->columnTypes[$type];
  8181. else if(($pos=strpos($type,' '))!==false)
  8182. {
  8183. $t=substr($type,0,$pos);
  8184. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  8185. }
  8186. else
  8187. return $type;
  8188. }
  8189. public function createTable($table, $columns, $options=null)
  8190. {
  8191. $cols=array();
  8192. foreach($columns as $name=>$type)
  8193. {
  8194. if(is_string($name))
  8195. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  8196. else
  8197. $cols[]="\t".$type;
  8198. }
  8199. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  8200. return $options===null ? $sql : $sql.' '.$options;
  8201. }
  8202. public function renameTable($table, $newName)
  8203. {
  8204. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  8205. }
  8206. public function dropTable($table)
  8207. {
  8208. return "DROP TABLE ".$this->quoteTableName($table);
  8209. }
  8210. public function truncateTable($table)
  8211. {
  8212. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  8213. }
  8214. public function addColumn($table, $column, $type)
  8215. {
  8216. return 'ALTER TABLE ' . $this->quoteTableName($table)
  8217. . ' ADD ' . $this->quoteColumnName($column) . ' '
  8218. . $this->getColumnType($type);
  8219. }
  8220. public function dropColumn($table, $column)
  8221. {
  8222. return "ALTER TABLE ".$this->quoteTableName($table)
  8223. ." DROP COLUMN ".$this->quoteColumnName($column);
  8224. }
  8225. public function renameColumn($table, $name, $newName)
  8226. {
  8227. return "ALTER TABLE ".$this->quoteTableName($table)
  8228. . " RENAME COLUMN ".$this->quoteColumnName($name)
  8229. . " TO ".$this->quoteColumnName($newName);
  8230. }
  8231. public function alterColumn($table, $column, $type)
  8232. {
  8233. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  8234. . $this->quoteColumnName($column) . ' '
  8235. . $this->quoteColumnName($column) . ' '
  8236. . $this->getColumnType($type);
  8237. }
  8238. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8239. {
  8240. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  8241. foreach($columns as $i=>$col)
  8242. $columns[$i]=$this->quoteColumnName($col);
  8243. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  8244. foreach($refColumns as $i=>$col)
  8245. $refColumns[$i]=$this->quoteColumnName($col);
  8246. $sql='ALTER TABLE '.$this->quoteTableName($table)
  8247. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  8248. .' FOREIGN KEY ('.implode(', ', $columns).')'
  8249. .' REFERENCES '.$this->quoteTableName($refTable)
  8250. .' ('.implode(', ', $refColumns).')';
  8251. if($delete!==null)
  8252. $sql.=' ON DELETE '.$delete;
  8253. if($update!==null)
  8254. $sql.=' ON UPDATE '.$update;
  8255. return $sql;
  8256. }
  8257. public function dropForeignKey($name, $table)
  8258. {
  8259. return 'ALTER TABLE '.$this->quoteTableName($table)
  8260. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  8261. }
  8262. public function createIndex($name, $table, $column, $unique=false)
  8263. {
  8264. $cols=array();
  8265. $columns=preg_split('/\s*,\s*/',$column,-1,PREG_SPLIT_NO_EMPTY);
  8266. foreach($columns as $col)
  8267. {
  8268. if(strpos($col,'(')!==false)
  8269. $cols[]=$col;
  8270. else
  8271. $cols[]=$this->quoteColumnName($col);
  8272. }
  8273. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  8274. . $this->quoteTableName($name).' ON '
  8275. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  8276. }
  8277. public function dropIndex($name, $table)
  8278. {
  8279. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  8280. }
  8281. }
  8282. class CSqliteSchema extends CDbSchema
  8283. {
  8284. public $columnTypes=array(
  8285. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  8286. 'string' => 'varchar(255)',
  8287. 'text' => 'text',
  8288. 'integer' => 'integer',
  8289. 'float' => 'float',
  8290. 'decimal' => 'decimal',
  8291. 'datetime' => 'datetime',
  8292. 'timestamp' => 'timestamp',
  8293. 'time' => 'time',
  8294. 'date' => 'date',
  8295. 'binary' => 'blob',
  8296. 'boolean' => 'tinyint(1)',
  8297. 'money' => 'decimal(19,4)',
  8298. );
  8299. public function resetSequence($table,$value=null)
  8300. {
  8301. if($table->sequenceName!==null)
  8302. {
  8303. if($value===null)
  8304. $value=$this->getDbConnection()->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")->queryScalar();
  8305. else
  8306. $value=(int)$value-1;
  8307. try
  8308. {
  8309. // it's possible sqlite_sequence does not exist
  8310. $this->getDbConnection()->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")->execute();
  8311. }
  8312. catch(Exception $e)
  8313. {
  8314. }
  8315. }
  8316. }
  8317. public function checkIntegrity($check=true,$schema='')
  8318. {
  8319. // SQLite doesn't enforce integrity
  8320. return;
  8321. }
  8322. protected function findTableNames($schema='')
  8323. {
  8324. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  8325. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  8326. }
  8327. protected function createCommandBuilder()
  8328. {
  8329. return new CSqliteCommandBuilder($this);
  8330. }
  8331. protected function loadTable($name)
  8332. {
  8333. $table=new CDbTableSchema;
  8334. $table->name=$name;
  8335. $table->rawName=$this->quoteTableName($name);
  8336. if($this->findColumns($table))
  8337. {
  8338. $this->findConstraints($table);
  8339. return $table;
  8340. }
  8341. else
  8342. return null;
  8343. }
  8344. protected function findColumns($table)
  8345. {
  8346. $sql="PRAGMA table_info({$table->rawName})";
  8347. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  8348. if(empty($columns))
  8349. return false;
  8350. foreach($columns as $column)
  8351. {
  8352. $c=$this->createColumn($column);
  8353. $table->columns[$c->name]=$c;
  8354. if($c->isPrimaryKey)
  8355. {
  8356. if($table->primaryKey===null)
  8357. $table->primaryKey=$c->name;
  8358. else if(is_string($table->primaryKey))
  8359. $table->primaryKey=array($table->primaryKey,$c->name);
  8360. else
  8361. $table->primaryKey[]=$c->name;
  8362. }
  8363. }
  8364. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  8365. {
  8366. $table->sequenceName='';
  8367. $table->columns[$table->primaryKey]->autoIncrement=true;
  8368. }
  8369. return true;
  8370. }
  8371. protected function findConstraints($table)
  8372. {
  8373. $foreignKeys=array();
  8374. $sql="PRAGMA foreign_key_list({$table->rawName})";
  8375. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  8376. foreach($keys as $key)
  8377. {
  8378. $column=$table->columns[$key['from']];
  8379. $column->isForeignKey=true;
  8380. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  8381. }
  8382. $table->foreignKeys=$foreignKeys;
  8383. }
  8384. protected function createColumn($column)
  8385. {
  8386. $c=new CSqliteColumnSchema;
  8387. $c->name=$column['name'];
  8388. $c->rawName=$this->quoteColumnName($c->name);
  8389. $c->allowNull=!$column['notnull'];
  8390. $c->isPrimaryKey=$column['pk']!=0;
  8391. $c->isForeignKey=false;
  8392. $c->init(strtolower($column['type']),$column['dflt_value']);
  8393. return $c;
  8394. }
  8395. public function truncateTable($table)
  8396. {
  8397. return "DELETE FROM ".$this->quoteTableName($table);
  8398. }
  8399. public function dropColumn($table, $column)
  8400. {
  8401. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  8402. }
  8403. public function renameColumn($table, $name, $newName)
  8404. {
  8405. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  8406. }
  8407. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8408. {
  8409. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  8410. }
  8411. public function dropForeignKey($name, $table)
  8412. {
  8413. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  8414. }
  8415. public function alterColumn($table, $column, $type)
  8416. {
  8417. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  8418. }
  8419. public function dropIndex($name, $table)
  8420. {
  8421. return 'DROP INDEX '.$this->quoteTableName($name);
  8422. }
  8423. }
  8424. class CDbTableSchema extends CComponent
  8425. {
  8426. public $name;
  8427. public $rawName;
  8428. public $primaryKey;
  8429. public $sequenceName;
  8430. public $foreignKeys=array();
  8431. public $columns=array();
  8432. public function getColumn($name)
  8433. {
  8434. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  8435. }
  8436. public function getColumnNames()
  8437. {
  8438. return array_keys($this->columns);
  8439. }
  8440. }
  8441. class CDbCommand extends CComponent
  8442. {
  8443. public $params=array();
  8444. private $_connection;
  8445. private $_text;
  8446. private $_statement;
  8447. private $_paramLog=array();
  8448. private $_query;
  8449. private $_fetchMode = array(PDO::FETCH_ASSOC);
  8450. public function __construct(CDbConnection $connection,$query=null)
  8451. {
  8452. $this->_connection=$connection;
  8453. if(is_array($query))
  8454. {
  8455. foreach($query as $name=>$value)
  8456. $this->$name=$value;
  8457. }
  8458. else
  8459. $this->setText($query);
  8460. }
  8461. public function __sleep()
  8462. {
  8463. $this->_statement=null;
  8464. return array_keys(get_object_vars($this));
  8465. }
  8466. public function setFetchMode($mode)
  8467. {
  8468. $params=func_get_args();
  8469. $this->_fetchMode = $params;
  8470. return $this;
  8471. }
  8472. public function reset()
  8473. {
  8474. $this->_text=null;
  8475. $this->_query=null;
  8476. $this->_statement=null;
  8477. $this->_paramLog=array();
  8478. $this->params=array();
  8479. return $this;
  8480. }
  8481. public function getText()
  8482. {
  8483. if($this->_text=='' && !empty($this->_query))
  8484. $this->setText($this->buildQuery($this->_query));
  8485. return $this->_text;
  8486. }
  8487. public function setText($value)
  8488. {
  8489. if($this->_connection->tablePrefix!==null && $value!='')
  8490. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  8491. else
  8492. $this->_text=$value;
  8493. $this->cancel();
  8494. return $this;
  8495. }
  8496. public function getConnection()
  8497. {
  8498. return $this->_connection;
  8499. }
  8500. public function getPdoStatement()
  8501. {
  8502. return $this->_statement;
  8503. }
  8504. public function prepare()
  8505. {
  8506. if($this->_statement==null)
  8507. {
  8508. try
  8509. {
  8510. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  8511. $this->_paramLog=array();
  8512. }
  8513. catch(Exception $e)
  8514. {
  8515. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8516. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8517. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  8518. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  8519. }
  8520. }
  8521. }
  8522. public function cancel()
  8523. {
  8524. $this->_statement=null;
  8525. }
  8526. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  8527. {
  8528. $this->prepare();
  8529. if($dataType===null)
  8530. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  8531. else if($length===null)
  8532. $this->_statement->bindParam($name,$value,$dataType);
  8533. else if($driverOptions===null)
  8534. $this->_statement->bindParam($name,$value,$dataType,$length);
  8535. else
  8536. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  8537. $this->_paramLog[$name]=&$value;
  8538. return $this;
  8539. }
  8540. public function bindValue($name, $value, $dataType=null)
  8541. {
  8542. $this->prepare();
  8543. if($dataType===null)
  8544. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8545. else
  8546. $this->_statement->bindValue($name,$value,$dataType);
  8547. $this->_paramLog[$name]=$value;
  8548. return $this;
  8549. }
  8550. public function bindValues($values)
  8551. {
  8552. $this->prepare();
  8553. foreach($values as $name=>$value)
  8554. {
  8555. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8556. $this->_paramLog[$name]=$value;
  8557. }
  8558. return $this;
  8559. }
  8560. public function execute($params=array())
  8561. {
  8562. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8563. {
  8564. $p=array();
  8565. foreach($pars as $name=>$value)
  8566. $p[$name]=$name.'='.var_export($value,true);
  8567. $par='. Bound with ' .implode(', ',$p);
  8568. }
  8569. else
  8570. $par='';
  8571. try
  8572. {
  8573. if($this->_connection->enableProfiling)
  8574. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8575. $this->prepare();
  8576. if($params===array())
  8577. $this->_statement->execute();
  8578. else
  8579. $this->_statement->execute($params);
  8580. $n=$this->_statement->rowCount();
  8581. if($this->_connection->enableProfiling)
  8582. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8583. return $n;
  8584. }
  8585. catch(Exception $e)
  8586. {
  8587. if($this->_connection->enableProfiling)
  8588. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8589. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8590. $message = $e->getMessage();
  8591. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  8592. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8593. if(YII_DEBUG)
  8594. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  8595. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8596. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8597. }
  8598. }
  8599. public function query($params=array())
  8600. {
  8601. return $this->queryInternal('',0,$params);
  8602. }
  8603. public function queryAll($fetchAssociative=true,$params=array())
  8604. {
  8605. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8606. }
  8607. public function queryRow($fetchAssociative=true,$params=array())
  8608. {
  8609. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8610. }
  8611. public function queryScalar($params=array())
  8612. {
  8613. $result=$this->queryInternal('fetchColumn',0,$params);
  8614. if(is_resource($result) && get_resource_type($result)==='stream')
  8615. return stream_get_contents($result);
  8616. else
  8617. return $result;
  8618. }
  8619. public function queryColumn($params=array())
  8620. {
  8621. return $this->queryInternal('fetchAll',PDO::FETCH_COLUMN,$params);
  8622. }
  8623. private function queryInternal($method,$mode,$params=array())
  8624. {
  8625. $params=array_merge($this->params,$params);
  8626. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8627. {
  8628. $p=array();
  8629. foreach($pars as $name=>$value)
  8630. $p[$name]=$name.'='.var_export($value,true);
  8631. $par='. Bound with '.implode(', ',$p);
  8632. }
  8633. else
  8634. $par='';
  8635. if($this->_connection->queryCachingCount>0 && $method!==''
  8636. && $this->_connection->queryCachingDuration>0
  8637. && $this->_connection->queryCacheID!==false
  8638. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  8639. {
  8640. $this->_connection->queryCachingCount--;
  8641. $cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
  8642. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  8643. if(($result=$cache->get($cacheKey))!==false)
  8644. {
  8645. return $result;
  8646. }
  8647. }
  8648. try
  8649. {
  8650. if($this->_connection->enableProfiling)
  8651. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8652. $this->prepare();
  8653. if($params===array())
  8654. $this->_statement->execute();
  8655. else
  8656. $this->_statement->execute($params);
  8657. if($method==='')
  8658. $result=new CDbDataReader($this);
  8659. else
  8660. {
  8661. $mode=(array)$mode;
  8662. $result=call_user_func_array(array($this->_statement, $method), $mode);
  8663. $this->_statement->closeCursor();
  8664. }
  8665. if($this->_connection->enableProfiling)
  8666. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8667. if(isset($cache,$cacheKey))
  8668. $cache->set($cacheKey, $result, $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  8669. return $result;
  8670. }
  8671. catch(Exception $e)
  8672. {
  8673. if($this->_connection->enableProfiling)
  8674. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8675. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8676. $message = $e->getMessage();
  8677. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  8678. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8679. if(YII_DEBUG)
  8680. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  8681. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8682. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8683. }
  8684. }
  8685. public function buildQuery($query)
  8686. {
  8687. $sql=isset($query['distinct']) && $query['distinct'] ? 'SELECT DISTINCT' : 'SELECT';
  8688. $sql.=' '.(isset($query['select']) ? $query['select'] : '*');
  8689. if(isset($query['from']))
  8690. $sql.="\nFROM ".$query['from'];
  8691. else
  8692. throw new CDbException(Yii::t('yii','The DB query must contain the "from" portion.'));
  8693. if(isset($query['join']))
  8694. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  8695. if(isset($query['where']))
  8696. $sql.="\nWHERE ".$query['where'];
  8697. if(isset($query['group']))
  8698. $sql.="\nGROUP BY ".$query['group'];
  8699. if(isset($query['having']))
  8700. $sql.="\nHAVING ".$query['having'];
  8701. if(isset($query['order']))
  8702. $sql.="\nORDER BY ".$query['order'];
  8703. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  8704. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  8705. if($limit>=0 || $offset>0)
  8706. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  8707. if(isset($query['union']))
  8708. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  8709. return $sql;
  8710. }
  8711. public function select($columns='*', $option='')
  8712. {
  8713. if(is_string($columns) && strpos($columns,'(')!==false)
  8714. $this->_query['select']=$columns;
  8715. else
  8716. {
  8717. if(!is_array($columns))
  8718. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8719. foreach($columns as $i=>$column)
  8720. {
  8721. if(is_object($column))
  8722. $columns[$i]=(string)$column;
  8723. else if(strpos($column,'(')===false)
  8724. {
  8725. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  8726. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  8727. else
  8728. $columns[$i]=$this->_connection->quoteColumnName($column);
  8729. }
  8730. }
  8731. $this->_query['select']=implode(', ',$columns);
  8732. }
  8733. if($option!='')
  8734. $this->_query['select']=$option.' '.$this->_query['select'];
  8735. return $this;
  8736. }
  8737. public function getSelect()
  8738. {
  8739. return isset($this->_query['select']) ? $this->_query['select'] : '';
  8740. }
  8741. public function setSelect($value)
  8742. {
  8743. $this->select($value);
  8744. }
  8745. public function selectDistinct($columns='*')
  8746. {
  8747. $this->_query['distinct']=true;
  8748. return $this->select($columns);
  8749. }
  8750. public function getDistinct()
  8751. {
  8752. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  8753. }
  8754. public function setDistinct($value)
  8755. {
  8756. $this->_query['distinct']=$value;
  8757. }
  8758. public function from($tables)
  8759. {
  8760. if(is_string($tables) && strpos($tables,'(')!==false)
  8761. $this->_query['from']=$tables;
  8762. else
  8763. {
  8764. if(!is_array($tables))
  8765. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  8766. foreach($tables as $i=>$table)
  8767. {
  8768. if(strpos($table,'(')===false)
  8769. {
  8770. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  8771. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  8772. else
  8773. $tables[$i]=$this->_connection->quoteTableName($table);
  8774. }
  8775. }
  8776. $this->_query['from']=implode(', ',$tables);
  8777. }
  8778. return $this;
  8779. }
  8780. public function getFrom()
  8781. {
  8782. return isset($this->_query['from']) ? $this->_query['from'] : '';
  8783. }
  8784. public function setFrom($value)
  8785. {
  8786. $this->from($value);
  8787. }
  8788. public function where($conditions, $params=array())
  8789. {
  8790. $this->_query['where']=$this->processConditions($conditions);
  8791. foreach($params as $name=>$value)
  8792. $this->params[$name]=$value;
  8793. return $this;
  8794. }
  8795. public function getWhere()
  8796. {
  8797. return isset($this->_query['where']) ? $this->_query['where'] : '';
  8798. }
  8799. public function setWhere($value)
  8800. {
  8801. $this->where($value);
  8802. }
  8803. public function join($table, $conditions, $params=array())
  8804. {
  8805. return $this->joinInternal('join', $table, $conditions, $params);
  8806. }
  8807. public function getJoin()
  8808. {
  8809. return isset($this->_query['join']) ? $this->_query['join'] : '';
  8810. }
  8811. public function setJoin($value)
  8812. {
  8813. $this->_query['join']=$value;
  8814. }
  8815. public function leftJoin($table, $conditions, $params=array())
  8816. {
  8817. return $this->joinInternal('left join', $table, $conditions, $params);
  8818. }
  8819. public function rightJoin($table, $conditions, $params=array())
  8820. {
  8821. return $this->joinInternal('right join', $table, $conditions, $params);
  8822. }
  8823. public function crossJoin($table)
  8824. {
  8825. return $this->joinInternal('cross join', $table);
  8826. }
  8827. public function naturalJoin($table)
  8828. {
  8829. return $this->joinInternal('natural join', $table);
  8830. }
  8831. public function group($columns)
  8832. {
  8833. if(is_string($columns) && strpos($columns,'(')!==false)
  8834. $this->_query['group']=$columns;
  8835. else
  8836. {
  8837. if(!is_array($columns))
  8838. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8839. foreach($columns as $i=>$column)
  8840. {
  8841. if(is_object($column))
  8842. $columns[$i]=(string)$column;
  8843. else if(strpos($column,'(')===false)
  8844. $columns[$i]=$this->_connection->quoteColumnName($column);
  8845. }
  8846. $this->_query['group']=implode(', ',$columns);
  8847. }
  8848. return $this;
  8849. }
  8850. public function getGroup()
  8851. {
  8852. return isset($this->_query['group']) ? $this->_query['group'] : '';
  8853. }
  8854. public function setGroup($value)
  8855. {
  8856. $this->group($value);
  8857. }
  8858. public function having($conditions, $params=array())
  8859. {
  8860. $this->_query['having']=$this->processConditions($conditions);
  8861. foreach($params as $name=>$value)
  8862. $this->params[$name]=$value;
  8863. return $this;
  8864. }
  8865. public function getHaving()
  8866. {
  8867. return isset($this->_query['having']) ? $this->_query['having'] : '';
  8868. }
  8869. public function setHaving($value)
  8870. {
  8871. $this->having($value);
  8872. }
  8873. public function order($columns)
  8874. {
  8875. if(is_string($columns) && strpos($columns,'(')!==false)
  8876. $this->_query['order']=$columns;
  8877. else
  8878. {
  8879. if(!is_array($columns))
  8880. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8881. foreach($columns as $i=>$column)
  8882. {
  8883. if(is_object($column))
  8884. $columns[$i]=(string)$column;
  8885. else if(strpos($column,'(')===false)
  8886. {
  8887. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  8888. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  8889. else
  8890. $columns[$i]=$this->_connection->quoteColumnName($column);
  8891. }
  8892. }
  8893. $this->_query['order']=implode(', ',$columns);
  8894. }
  8895. return $this;
  8896. }
  8897. public function getOrder()
  8898. {
  8899. return isset($this->_query['order']) ? $this->_query['order'] : '';
  8900. }
  8901. public function setOrder($value)
  8902. {
  8903. $this->order($value);
  8904. }
  8905. public function limit($limit, $offset=null)
  8906. {
  8907. $this->_query['limit']=(int)$limit;
  8908. if($offset!==null)
  8909. $this->offset($offset);
  8910. return $this;
  8911. }
  8912. public function getLimit()
  8913. {
  8914. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  8915. }
  8916. public function setLimit($value)
  8917. {
  8918. $this->limit($value);
  8919. }
  8920. public function offset($offset)
  8921. {
  8922. $this->_query['offset']=(int)$offset;
  8923. return $this;
  8924. }
  8925. public function getOffset()
  8926. {
  8927. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  8928. }
  8929. public function setOffset($value)
  8930. {
  8931. $this->offset($value);
  8932. }
  8933. public function union($sql)
  8934. {
  8935. if(isset($this->_query['union']) && is_string($this->_query['union']))
  8936. $this->_query['union']=array($this->_query['union']);
  8937. $this->_query['union'][]=$sql;
  8938. return $this;
  8939. }
  8940. public function getUnion()
  8941. {
  8942. return isset($this->_query['union']) ? $this->_query['union'] : '';
  8943. }
  8944. public function setUnion($value)
  8945. {
  8946. $this->_query['union']=$value;
  8947. }
  8948. public function insert($table, $columns)
  8949. {
  8950. $params=array();
  8951. $names=array();
  8952. $placeholders=array();
  8953. foreach($columns as $name=>$value)
  8954. {
  8955. $names[]=$this->_connection->quoteColumnName($name);
  8956. if($value instanceof CDbExpression)
  8957. {
  8958. $placeholders[] = $value->expression;
  8959. foreach($value->params as $n => $v)
  8960. $params[$n] = $v;
  8961. }
  8962. else
  8963. {
  8964. $placeholders[] = ':' . $name;
  8965. $params[':' . $name] = $value;
  8966. }
  8967. }
  8968. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  8969. . ' (' . implode(', ',$names) . ') VALUES ('
  8970. . implode(', ', $placeholders) . ')';
  8971. return $this->setText($sql)->execute($params);
  8972. }
  8973. public function update($table, $columns, $conditions='', $params=array())
  8974. {
  8975. $lines=array();
  8976. foreach($columns as $name=>$value)
  8977. {
  8978. if($value instanceof CDbExpression)
  8979. {
  8980. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  8981. foreach($value->params as $n => $v)
  8982. $params[$n] = $v;
  8983. }
  8984. else
  8985. {
  8986. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  8987. $params[':' . $name]=$value;
  8988. }
  8989. }
  8990. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  8991. if(($where=$this->processConditions($conditions))!='')
  8992. $sql.=' WHERE '.$where;
  8993. return $this->setText($sql)->execute($params);
  8994. }
  8995. public function delete($table, $conditions='', $params=array())
  8996. {
  8997. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  8998. if(($where=$this->processConditions($conditions))!='')
  8999. $sql.=' WHERE '.$where;
  9000. return $this->setText($sql)->execute($params);
  9001. }
  9002. public function createTable($table, $columns, $options=null)
  9003. {
  9004. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  9005. }
  9006. public function renameTable($table, $newName)
  9007. {
  9008. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  9009. }
  9010. public function dropTable($table)
  9011. {
  9012. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  9013. }
  9014. public function truncateTable($table)
  9015. {
  9016. $schema=$this->getConnection()->getSchema();
  9017. $n=$this->setText($schema->truncateTable($table))->execute();
  9018. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  9019. $schema->resetSequence($schema->getTable($table));
  9020. return $n;
  9021. }
  9022. public function addColumn($table, $column, $type)
  9023. {
  9024. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  9025. }
  9026. public function dropColumn($table, $column)
  9027. {
  9028. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  9029. }
  9030. public function renameColumn($table, $name, $newName)
  9031. {
  9032. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  9033. }
  9034. public function alterColumn($table, $column, $type)
  9035. {
  9036. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  9037. }
  9038. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9039. {
  9040. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  9041. }
  9042. public function dropForeignKey($name, $table)
  9043. {
  9044. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  9045. }
  9046. public function createIndex($name, $table, $column, $unique=false)
  9047. {
  9048. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $column, $unique))->execute();
  9049. }
  9050. public function dropIndex($name, $table)
  9051. {
  9052. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  9053. }
  9054. private function processConditions($conditions)
  9055. {
  9056. if(!is_array($conditions))
  9057. return $conditions;
  9058. else if($conditions===array())
  9059. return '';
  9060. $n=count($conditions);
  9061. $operator=strtoupper($conditions[0]);
  9062. if($operator==='OR' || $operator==='AND')
  9063. {
  9064. $parts=array();
  9065. for($i=1;$i<$n;++$i)
  9066. {
  9067. $condition=$this->processConditions($conditions[$i]);
  9068. if($condition!=='')
  9069. $parts[]='('.$condition.')';
  9070. }
  9071. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  9072. }
  9073. if(!isset($conditions[1],$conditions[2]))
  9074. return '';
  9075. $column=$conditions[1];
  9076. if(strpos($column,'(')===false)
  9077. $column=$this->_connection->quoteColumnName($column);
  9078. $values=$conditions[2];
  9079. if(!is_array($values))
  9080. $values=array($values);
  9081. if($operator==='IN' || $operator==='NOT IN')
  9082. {
  9083. if($values===array())
  9084. return $operator==='IN' ? '0=1' : '';
  9085. foreach($values as $i=>$value)
  9086. {
  9087. if(is_string($value))
  9088. $values[$i]=$this->_connection->quoteValue($value);
  9089. else
  9090. $values[$i]=(string)$value;
  9091. }
  9092. return $column.' '.$operator.' ('.implode(', ',$values).')';
  9093. }
  9094. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  9095. {
  9096. if($values===array())
  9097. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  9098. if($operator==='LIKE' || $operator==='NOT LIKE')
  9099. $andor=' AND ';
  9100. else
  9101. {
  9102. $andor=' OR ';
  9103. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  9104. }
  9105. $expressions=array();
  9106. foreach($values as $value)
  9107. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  9108. return implode($andor,$expressions);
  9109. }
  9110. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  9111. }
  9112. private function joinInternal($type, $table, $conditions='', $params=array())
  9113. {
  9114. if(strpos($table,'(')===false)
  9115. {
  9116. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9117. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9118. else
  9119. $table=$this->_connection->quoteTableName($table);
  9120. }
  9121. $conditions=$this->processConditions($conditions);
  9122. if($conditions!='')
  9123. $conditions=' ON '.$conditions;
  9124. if(isset($this->_query['join']) && is_string($this->_query['join']))
  9125. $this->_query['join']=array($this->_query['join']);
  9126. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  9127. foreach($params as $name=>$value)
  9128. $this->params[$name]=$value;
  9129. return $this;
  9130. }
  9131. }
  9132. class CDbColumnSchema extends CComponent
  9133. {
  9134. public $name;
  9135. public $rawName;
  9136. public $allowNull;
  9137. public $dbType;
  9138. public $type;
  9139. public $defaultValue;
  9140. public $size;
  9141. public $precision;
  9142. public $scale;
  9143. public $isPrimaryKey;
  9144. public $isForeignKey;
  9145. public $autoIncrement=false;
  9146. public function init($dbType, $defaultValue)
  9147. {
  9148. $this->dbType=$dbType;
  9149. $this->extractType($dbType);
  9150. $this->extractLimit($dbType);
  9151. if($defaultValue!==null)
  9152. $this->extractDefault($defaultValue);
  9153. }
  9154. protected function extractType($dbType)
  9155. {
  9156. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  9157. $this->type='integer';
  9158. else if(stripos($dbType,'bool')!==false)
  9159. $this->type='boolean';
  9160. else if(preg_match('/(real|floa|doub)/i',$dbType))
  9161. $this->type='double';
  9162. else
  9163. $this->type='string';
  9164. }
  9165. protected function extractLimit($dbType)
  9166. {
  9167. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  9168. {
  9169. $values=explode(',',$matches[1]);
  9170. $this->size=$this->precision=(int)$values[0];
  9171. if(isset($values[1]))
  9172. $this->scale=(int)$values[1];
  9173. }
  9174. }
  9175. protected function extractDefault($defaultValue)
  9176. {
  9177. $this->defaultValue=$this->typecast($defaultValue);
  9178. }
  9179. public function typecast($value)
  9180. {
  9181. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  9182. return $value;
  9183. if($value==='' && $this->allowNull)
  9184. return $this->type==='string' ? '' : null;
  9185. switch($this->type)
  9186. {
  9187. case 'string': return (string)$value;
  9188. case 'integer': return (integer)$value;
  9189. case 'boolean': return (boolean)$value;
  9190. case 'double':
  9191. default: return $value;
  9192. }
  9193. }
  9194. }
  9195. class CSqliteColumnSchema extends CDbColumnSchema
  9196. {
  9197. protected function extractDefault($defaultValue)
  9198. {
  9199. if($this->type==='string') // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  9200. $this->defaultValue=trim($defaultValue,"'\"");
  9201. else
  9202. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  9203. }
  9204. }
  9205. abstract class CValidator extends CComponent
  9206. {
  9207. public static $builtInValidators=array(
  9208. 'required'=>'CRequiredValidator',
  9209. 'filter'=>'CFilterValidator',
  9210. 'match'=>'CRegularExpressionValidator',
  9211. 'email'=>'CEmailValidator',
  9212. 'url'=>'CUrlValidator',
  9213. 'unique'=>'CUniqueValidator',
  9214. 'compare'=>'CCompareValidator',
  9215. 'length'=>'CStringValidator',
  9216. 'in'=>'CRangeValidator',
  9217. 'numerical'=>'CNumberValidator',
  9218. 'captcha'=>'CCaptchaValidator',
  9219. 'type'=>'CTypeValidator',
  9220. 'file'=>'CFileValidator',
  9221. 'default'=>'CDefaultValueValidator',
  9222. 'exist'=>'CExistValidator',
  9223. 'boolean'=>'CBooleanValidator',
  9224. 'safe'=>'CSafeValidator',
  9225. 'unsafe'=>'CUnsafeValidator',
  9226. 'date'=>'CDateValidator',
  9227. );
  9228. public $attributes;
  9229. public $message;
  9230. public $skipOnError=false;
  9231. public $on;
  9232. public $safe=true;
  9233. public $enableClientValidation=true;
  9234. abstract protected function validateAttribute($object,$attribute);
  9235. public static function createValidator($name,$object,$attributes,$params=array())
  9236. {
  9237. if(is_string($attributes))
  9238. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  9239. if(isset($params['on']))
  9240. {
  9241. if(is_array($params['on']))
  9242. $on=$params['on'];
  9243. else
  9244. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  9245. }
  9246. else
  9247. $on=array();
  9248. if(method_exists($object,$name))
  9249. {
  9250. $validator=new CInlineValidator;
  9251. $validator->attributes=$attributes;
  9252. $validator->method=$name;
  9253. if(isset($params['clientValidate']))
  9254. {
  9255. $validator->clientValidate=$params['clientValidate'];
  9256. unset($params['clientValidate']);
  9257. }
  9258. $validator->params=$params;
  9259. if(isset($params['skipOnError']))
  9260. $validator->skipOnError=$params['skipOnError'];
  9261. }
  9262. else
  9263. {
  9264. $params['attributes']=$attributes;
  9265. if(isset(self::$builtInValidators[$name]))
  9266. $className=Yii::import(self::$builtInValidators[$name],true);
  9267. else
  9268. $className=Yii::import($name,true);
  9269. $validator=new $className;
  9270. foreach($params as $name=>$value)
  9271. $validator->$name=$value;
  9272. }
  9273. $validator->on=empty($on) ? array() : array_combine($on,$on);
  9274. return $validator;
  9275. }
  9276. public function validate($object,$attributes=null)
  9277. {
  9278. if(is_array($attributes))
  9279. $attributes=array_intersect($this->attributes,$attributes);
  9280. else
  9281. $attributes=$this->attributes;
  9282. foreach($attributes as $attribute)
  9283. {
  9284. if(!$this->skipOnError || !$object->hasErrors($attribute))
  9285. $this->validateAttribute($object,$attribute);
  9286. }
  9287. }
  9288. public function clientValidateAttribute($object,$attribute)
  9289. {
  9290. }
  9291. public function applyTo($scenario)
  9292. {
  9293. return empty($this->on) || isset($this->on[$scenario]);
  9294. }
  9295. protected function addError($object,$attribute,$message,$params=array())
  9296. {
  9297. $params['{attribute}']=$object->getAttributeLabel($attribute);
  9298. $object->addError($attribute,strtr($message,$params));
  9299. }
  9300. protected function isEmpty($value,$trim=false)
  9301. {
  9302. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  9303. }
  9304. }
  9305. class CStringValidator extends CValidator
  9306. {
  9307. public $max;
  9308. public $min;
  9309. public $is;
  9310. public $tooShort;
  9311. public $tooLong;
  9312. public $allowEmpty=true;
  9313. public $encoding;
  9314. protected function validateAttribute($object,$attribute)
  9315. {
  9316. $value=$object->$attribute;
  9317. if($this->allowEmpty && $this->isEmpty($value))
  9318. return;
  9319. if(function_exists('mb_strlen') && $this->encoding!==false)
  9320. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  9321. else
  9322. $length=strlen($value);
  9323. if($this->min!==null && $length<$this->min)
  9324. {
  9325. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9326. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9327. }
  9328. if($this->max!==null && $length>$this->max)
  9329. {
  9330. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9331. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9332. }
  9333. if($this->is!==null && $length!==$this->is)
  9334. {
  9335. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9336. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  9337. }
  9338. }
  9339. public function clientValidateAttribute($object,$attribute)
  9340. {
  9341. $label=$object->getAttributeLabel($attribute);
  9342. if(($message=$this->message)===null)
  9343. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9344. $message=strtr($message, array(
  9345. '{attribute}'=>$label,
  9346. '{length}'=>$this->is,
  9347. ));
  9348. if(($tooShort=$this->tooShort)===null)
  9349. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9350. $tooShort=strtr($tooShort, array(
  9351. '{attribute}'=>$label,
  9352. '{min}'=>$this->min,
  9353. ));
  9354. if(($tooLong=$this->tooLong)===null)
  9355. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9356. $tooLong=strtr($tooLong, array(
  9357. '{attribute}'=>$label,
  9358. '{max}'=>$this->max,
  9359. ));
  9360. $js='';
  9361. if($this->min!==null)
  9362. {
  9363. $js.="
  9364. if(value.length<{$this->min}) {
  9365. messages.push(".CJSON::encode($tooShort).");
  9366. }
  9367. ";
  9368. }
  9369. if($this->max!==null)
  9370. {
  9371. $js.="
  9372. if(value.length>{$this->max}) {
  9373. messages.push(".CJSON::encode($tooLong).");
  9374. }
  9375. ";
  9376. }
  9377. if($this->is!==null)
  9378. {
  9379. $js.="
  9380. if(value.length!={$this->is}) {
  9381. messages.push(".CJSON::encode($message).");
  9382. }
  9383. ";
  9384. }
  9385. if($this->allowEmpty)
  9386. {
  9387. $js="
  9388. if($.trim(value)!='') {
  9389. $js
  9390. }
  9391. ";
  9392. }
  9393. return $js;
  9394. }
  9395. }
  9396. class CRequiredValidator extends CValidator
  9397. {
  9398. public $requiredValue;
  9399. public $strict=false;
  9400. protected function validateAttribute($object,$attribute)
  9401. {
  9402. $value=$object->$attribute;
  9403. if($this->requiredValue!==null)
  9404. {
  9405. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  9406. {
  9407. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  9408. array('{value}'=>$this->requiredValue));
  9409. $this->addError($object,$attribute,$message);
  9410. }
  9411. }
  9412. else if($this->isEmpty($value,true))
  9413. {
  9414. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  9415. $this->addError($object,$attribute,$message);
  9416. }
  9417. }
  9418. public function clientValidateAttribute($object,$attribute)
  9419. {
  9420. $message=$this->message;
  9421. if($this->requiredValue!==null)
  9422. {
  9423. if($message===null)
  9424. $message=Yii::t('yii','{attribute} must be {value}.');
  9425. $message=strtr($message, array(
  9426. '{value}'=>$this->requiredValue,
  9427. '{attribute}'=>$object->getAttributeLabel($attribute),
  9428. ));
  9429. return "
  9430. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  9431. messages.push(".CJSON::encode($message).");
  9432. }
  9433. ";
  9434. }
  9435. else
  9436. {
  9437. if($message===null)
  9438. $message=Yii::t('yii','{attribute} cannot be blank.');
  9439. $message=strtr($message, array(
  9440. '{attribute}'=>$object->getAttributeLabel($attribute),
  9441. ));
  9442. return "
  9443. if($.trim(value)=='') {
  9444. messages.push(".CJSON::encode($message).");
  9445. }
  9446. ";
  9447. }
  9448. }
  9449. }
  9450. class CNumberValidator extends CValidator
  9451. {
  9452. public $integerOnly=false;
  9453. public $allowEmpty=true;
  9454. public $max;
  9455. public $min;
  9456. public $tooBig;
  9457. public $tooSmall;
  9458. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  9459. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  9460. protected function validateAttribute($object,$attribute)
  9461. {
  9462. $value=$object->$attribute;
  9463. if($this->allowEmpty && $this->isEmpty($value))
  9464. return;
  9465. if($this->integerOnly)
  9466. {
  9467. if(!preg_match($this->integerPattern,"$value"))
  9468. {
  9469. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  9470. $this->addError($object,$attribute,$message);
  9471. }
  9472. }
  9473. else
  9474. {
  9475. if(!preg_match($this->numberPattern,"$value"))
  9476. {
  9477. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  9478. $this->addError($object,$attribute,$message);
  9479. }
  9480. }
  9481. if($this->min!==null && $value<$this->min)
  9482. {
  9483. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9484. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9485. }
  9486. if($this->max!==null && $value>$this->max)
  9487. {
  9488. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9489. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9490. }
  9491. }
  9492. public function clientValidateAttribute($object,$attribute)
  9493. {
  9494. $label=$object->getAttributeLabel($attribute);
  9495. if(($message=$this->message)===null)
  9496. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  9497. $message=strtr($message, array(
  9498. '{attribute}'=>$label,
  9499. ));
  9500. if(($tooBig=$this->tooBig)===null)
  9501. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9502. $tooBig=strtr($tooBig, array(
  9503. '{attribute}'=>$label,
  9504. '{max}'=>$this->max,
  9505. ));
  9506. if(($tooSmall=$this->tooSmall)===null)
  9507. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9508. $tooSmall=strtr($tooSmall, array(
  9509. '{attribute}'=>$label,
  9510. '{min}'=>$this->min,
  9511. ));
  9512. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  9513. $js="
  9514. if(!value.match($pattern)) {
  9515. messages.push(".CJSON::encode($message).");
  9516. }
  9517. ";
  9518. if($this->min!==null)
  9519. {
  9520. $js.="
  9521. if(value<{$this->min}) {
  9522. messages.push(".CJSON::encode($tooSmall).");
  9523. }
  9524. ";
  9525. }
  9526. if($this->max!==null)
  9527. {
  9528. $js.="
  9529. if(value>{$this->max}) {
  9530. messages.push(".CJSON::encode($tooBig).");
  9531. }
  9532. ";
  9533. }
  9534. if($this->allowEmpty)
  9535. {
  9536. $js="
  9537. if($.trim(value)!='') {
  9538. $js
  9539. }
  9540. ";
  9541. }
  9542. return $js;
  9543. }
  9544. }
  9545. class CListIterator implements Iterator
  9546. {
  9547. private $_d;
  9548. private $_i;
  9549. private $_c;
  9550. public function __construct(&$data)
  9551. {
  9552. $this->_d=&$data;
  9553. $this->_i=0;
  9554. $this->_c=count($this->_d);
  9555. }
  9556. public function rewind()
  9557. {
  9558. $this->_i=0;
  9559. }
  9560. public function key()
  9561. {
  9562. return $this->_i;
  9563. }
  9564. public function current()
  9565. {
  9566. return $this->_d[$this->_i];
  9567. }
  9568. public function next()
  9569. {
  9570. $this->_i++;
  9571. }
  9572. public function valid()
  9573. {
  9574. return $this->_i<$this->_c;
  9575. }
  9576. }
  9577. interface IApplicationComponent
  9578. {
  9579. public function init();
  9580. public function getIsInitialized();
  9581. }
  9582. interface ICache
  9583. {
  9584. public function get($id);
  9585. public function mget($ids);
  9586. public function set($id,$value,$expire=0,$dependency=null);
  9587. public function add($id,$value,$expire=0,$dependency=null);
  9588. public function delete($id);
  9589. public function flush();
  9590. }
  9591. interface ICacheDependency
  9592. {
  9593. public function evaluateDependency();
  9594. public function getHasChanged();
  9595. }
  9596. interface IStatePersister
  9597. {
  9598. public function load();
  9599. public function save($state);
  9600. }
  9601. interface IFilter
  9602. {
  9603. public function filter($filterChain);
  9604. }
  9605. interface IAction
  9606. {
  9607. public function getId();
  9608. public function getController();
  9609. }
  9610. interface IWebServiceProvider
  9611. {
  9612. public function beforeWebMethod($service);
  9613. public function afterWebMethod($service);
  9614. }
  9615. interface IViewRenderer
  9616. {
  9617. public function renderFile($context,$file,$data,$return);
  9618. }
  9619. interface IUserIdentity
  9620. {
  9621. public function authenticate();
  9622. public function getIsAuthenticated();
  9623. public function getId();
  9624. public function getName();
  9625. public function getPersistentStates();
  9626. }
  9627. interface IWebUser
  9628. {
  9629. public function getId();
  9630. public function getName();
  9631. public function getIsGuest();
  9632. public function checkAccess($operation,$params=array());
  9633. }
  9634. interface IAuthManager
  9635. {
  9636. public function checkAccess($itemName,$userId,$params=array());
  9637. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  9638. public function removeAuthItem($name);
  9639. public function getAuthItems($type=null,$userId=null);
  9640. public function getAuthItem($name);
  9641. public function saveAuthItem($item,$oldName=null);
  9642. public function addItemChild($itemName,$childName);
  9643. public function removeItemChild($itemName,$childName);
  9644. public function hasItemChild($itemName,$childName);
  9645. public function getItemChildren($itemName);
  9646. public function assign($itemName,$userId,$bizRule=null,$data=null);
  9647. public function revoke($itemName,$userId);
  9648. public function isAssigned($itemName,$userId);
  9649. public function getAuthAssignment($itemName,$userId);
  9650. public function getAuthAssignments($userId);
  9651. public function saveAuthAssignment($assignment);
  9652. public function clearAll();
  9653. public function clearAuthAssignments();
  9654. public function save();
  9655. public function executeBizRule($bizRule,$params,$data);
  9656. }
  9657. interface IBehavior
  9658. {
  9659. public function attach($component);
  9660. public function detach($component);
  9661. public function getEnabled();
  9662. public function setEnabled($value);
  9663. }
  9664. interface IWidgetFactory
  9665. {
  9666. public function createWidget($owner,$className,$properties=array());
  9667. }
  9668. interface IDataProvider
  9669. {
  9670. public function getId();
  9671. public function getItemCount($refresh=false);
  9672. public function getTotalItemCount($refresh=false);
  9673. public function getData($refresh=false);
  9674. public function getKeys($refresh=false);
  9675. public function getSort();
  9676. public function getPagination();
  9677. }
  9678. ?>