PageRenderTime 114ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/framework/yiilite.php

https://bitbucket.org/negge/songbook
PHP | 9798 lines | 9746 code | 2 blank | 50 comment | 744 complexity | b546603d3823bc6334904abcde17930a MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, BSD-2-Clause
  1. <?php
  2. /**
  3. * Yii bootstrap file.
  4. *
  5. * This file is automatically generated using 'build lite' command.
  6. * It is the result of merging commonly used Yii class files with
  7. * comments and trace statements removed away.
  8. *
  9. * By using this file instead of yii.php, an Yii application may
  10. * improve performance due to the reduction of PHP parsing time.
  11. * The performance improvement is especially obvious when PHP APC extension
  12. * is enabled.
  13. *
  14. * DO NOT modify this file manually.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @link http://www.yiiframework.com/
  18. * @copyright Copyright &copy; 2008-2012 Yii Software LLC
  19. * @license http://www.yiiframework.com/license/
  20. * @version $Id: $
  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.11';
  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 and the file is readable.',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 and the file is readable.',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. if(YII_DEBUG && basename(realpath($classFile))!==$className.'.php')
  227. throw new CException(Yii::t('yii','Class name "{class}" does not match class file "{file}".', array(
  228. '{class}'=>$className,
  229. '{file}'=>$classFile,
  230. )));
  231. break;
  232. }
  233. }
  234. }
  235. else
  236. include($className.'.php');
  237. }
  238. else // class name with namespace in PHP 5.3
  239. {
  240. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  241. if(($path=self::getPathOfAlias($namespace))!==false)
  242. include($path.'.php');
  243. else
  244. return false;
  245. }
  246. return class_exists($className,false) || interface_exists($className,false);
  247. }
  248. return true;
  249. }
  250. public static function trace($msg,$category='application')
  251. {
  252. if(YII_DEBUG)
  253. self::log($msg,CLogger::LEVEL_TRACE,$category);
  254. }
  255. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  256. {
  257. if(self::$_logger===null)
  258. self::$_logger=new CLogger;
  259. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  260. {
  261. $traces=debug_backtrace();
  262. $count=0;
  263. foreach($traces as $trace)
  264. {
  265. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  266. {
  267. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  268. if(++$count>=YII_TRACE_LEVEL)
  269. break;
  270. }
  271. }
  272. }
  273. self::$_logger->log($msg,$level,$category);
  274. }
  275. public static function beginProfile($token,$category='application')
  276. {
  277. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  278. }
  279. public static function endProfile($token,$category='application')
  280. {
  281. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  282. }
  283. public static function getLogger()
  284. {
  285. if(self::$_logger!==null)
  286. return self::$_logger;
  287. else
  288. return self::$_logger=new CLogger;
  289. }
  290. public static function setLogger($logger)
  291. {
  292. self::$_logger=$logger;
  293. }
  294. public static function powered()
  295. {
  296. return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
  297. }
  298. public static function t($category,$message,$params=array(),$source=null,$language=null)
  299. {
  300. if(self::$_app!==null)
  301. {
  302. if($source===null)
  303. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  304. if(($source=self::$_app->getComponent($source))!==null)
  305. $message=$source->translate($category,$message,$language);
  306. }
  307. if($params===array())
  308. return $message;
  309. if(!is_array($params))
  310. $params=array($params);
  311. if(isset($params[0])) // number choice
  312. {
  313. if(strpos($message,'|')!==false)
  314. {
  315. if(strpos($message,'#')===false)
  316. {
  317. $chunks=explode('|',$message);
  318. $expressions=self::$_app->getLocale($language)->getPluralRules();
  319. if($n=min(count($chunks),count($expressions)))
  320. {
  321. for($i=0;$i<$n;$i++)
  322. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  323. $message=implode('|',$chunks);
  324. }
  325. }
  326. $message=CChoiceFormat::format($message,$params[0]);
  327. }
  328. if(!isset($params['{n}']))
  329. $params['{n}']=$params[0];
  330. unset($params[0]);
  331. }
  332. return $params!==array() ? strtr($message,$params) : $message;
  333. }
  334. public static function registerAutoloader($callback, $append=false)
  335. {
  336. if($append)
  337. {
  338. self::$enableIncludePath=false;
  339. spl_autoload_register($callback);
  340. }
  341. else
  342. {
  343. spl_autoload_unregister(array('YiiBase','autoload'));
  344. spl_autoload_register($callback);
  345. spl_autoload_register(array('YiiBase','autoload'));
  346. }
  347. }
  348. private static $_coreClasses=array(
  349. 'CApplication' => '/base/CApplication.php',
  350. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  351. 'CBehavior' => '/base/CBehavior.php',
  352. 'CComponent' => '/base/CComponent.php',
  353. 'CErrorEvent' => '/base/CErrorEvent.php',
  354. 'CErrorHandler' => '/base/CErrorHandler.php',
  355. 'CException' => '/base/CException.php',
  356. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  357. 'CHttpException' => '/base/CHttpException.php',
  358. 'CModel' => '/base/CModel.php',
  359. 'CModelBehavior' => '/base/CModelBehavior.php',
  360. 'CModelEvent' => '/base/CModelEvent.php',
  361. 'CModule' => '/base/CModule.php',
  362. 'CSecurityManager' => '/base/CSecurityManager.php',
  363. 'CStatePersister' => '/base/CStatePersister.php',
  364. 'CApcCache' => '/caching/CApcCache.php',
  365. 'CCache' => '/caching/CCache.php',
  366. 'CDbCache' => '/caching/CDbCache.php',
  367. 'CDummyCache' => '/caching/CDummyCache.php',
  368. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  369. 'CFileCache' => '/caching/CFileCache.php',
  370. 'CMemCache' => '/caching/CMemCache.php',
  371. 'CWinCache' => '/caching/CWinCache.php',
  372. 'CXCache' => '/caching/CXCache.php',
  373. 'CZendDataCache' => '/caching/CZendDataCache.php',
  374. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  375. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  376. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  377. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  378. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  379. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  380. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  381. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  382. 'CConfiguration' => '/collections/CConfiguration.php',
  383. 'CList' => '/collections/CList.php',
  384. 'CListIterator' => '/collections/CListIterator.php',
  385. 'CMap' => '/collections/CMap.php',
  386. 'CMapIterator' => '/collections/CMapIterator.php',
  387. 'CQueue' => '/collections/CQueue.php',
  388. 'CQueueIterator' => '/collections/CQueueIterator.php',
  389. 'CStack' => '/collections/CStack.php',
  390. 'CStackIterator' => '/collections/CStackIterator.php',
  391. 'CTypedList' => '/collections/CTypedList.php',
  392. 'CTypedMap' => '/collections/CTypedMap.php',
  393. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  394. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  395. 'CConsoleCommandBehavior' => '/console/CConsoleCommandBehavior.php',
  396. 'CConsoleCommandEvent' => '/console/CConsoleCommandEvent.php',
  397. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  398. 'CHelpCommand' => '/console/CHelpCommand.php',
  399. 'CDbCommand' => '/db/CDbCommand.php',
  400. 'CDbConnection' => '/db/CDbConnection.php',
  401. 'CDbDataReader' => '/db/CDbDataReader.php',
  402. 'CDbException' => '/db/CDbException.php',
  403. 'CDbMigration' => '/db/CDbMigration.php',
  404. 'CDbTransaction' => '/db/CDbTransaction.php',
  405. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  406. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  407. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  408. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  409. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  410. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  411. 'CDbExpression' => '/db/schema/CDbExpression.php',
  412. 'CDbSchema' => '/db/schema/CDbSchema.php',
  413. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  414. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  415. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  416. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  417. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  418. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  419. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  420. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  421. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  422. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  423. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  424. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  425. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  426. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  427. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  428. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  429. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  430. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  431. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  432. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  433. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  434. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  435. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  436. 'CLocale' => '/i18n/CLocale.php',
  437. 'CMessageSource' => '/i18n/CMessageSource.php',
  438. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  439. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  440. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  441. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  442. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  443. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  444. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  445. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  446. 'CLogFilter' => '/logging/CLogFilter.php',
  447. 'CLogRoute' => '/logging/CLogRoute.php',
  448. 'CLogRouter' => '/logging/CLogRouter.php',
  449. 'CLogger' => '/logging/CLogger.php',
  450. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  451. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  452. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  453. 'CFileHelper' => '/utils/CFileHelper.php',
  454. 'CFormatter' => '/utils/CFormatter.php',
  455. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  456. 'CPropertyValue' => '/utils/CPropertyValue.php',
  457. 'CTimestamp' => '/utils/CTimestamp.php',
  458. 'CVarDumper' => '/utils/CVarDumper.php',
  459. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  460. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  461. 'CCompareValidator' => '/validators/CCompareValidator.php',
  462. 'CDateValidator' => '/validators/CDateValidator.php',
  463. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  464. 'CEmailValidator' => '/validators/CEmailValidator.php',
  465. 'CExistValidator' => '/validators/CExistValidator.php',
  466. 'CFileValidator' => '/validators/CFileValidator.php',
  467. 'CFilterValidator' => '/validators/CFilterValidator.php',
  468. 'CInlineValidator' => '/validators/CInlineValidator.php',
  469. 'CNumberValidator' => '/validators/CNumberValidator.php',
  470. 'CRangeValidator' => '/validators/CRangeValidator.php',
  471. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  472. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  473. 'CSafeValidator' => '/validators/CSafeValidator.php',
  474. 'CStringValidator' => '/validators/CStringValidator.php',
  475. 'CTypeValidator' => '/validators/CTypeValidator.php',
  476. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  477. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  478. 'CUrlValidator' => '/validators/CUrlValidator.php',
  479. 'CValidator' => '/validators/CValidator.php',
  480. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  481. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  482. 'CAssetManager' => '/web/CAssetManager.php',
  483. 'CBaseController' => '/web/CBaseController.php',
  484. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  485. 'CClientScript' => '/web/CClientScript.php',
  486. 'CController' => '/web/CController.php',
  487. 'CDataProvider' => '/web/CDataProvider.php',
  488. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  489. 'CExtController' => '/web/CExtController.php',
  490. 'CFormModel' => '/web/CFormModel.php',
  491. 'CHttpCookie' => '/web/CHttpCookie.php',
  492. 'CHttpRequest' => '/web/CHttpRequest.php',
  493. 'CHttpSession' => '/web/CHttpSession.php',
  494. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  495. 'COutputEvent' => '/web/COutputEvent.php',
  496. 'CPagination' => '/web/CPagination.php',
  497. 'CSort' => '/web/CSort.php',
  498. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  499. 'CTheme' => '/web/CTheme.php',
  500. 'CThemeManager' => '/web/CThemeManager.php',
  501. 'CUploadedFile' => '/web/CUploadedFile.php',
  502. 'CUrlManager' => '/web/CUrlManager.php',
  503. 'CWebApplication' => '/web/CWebApplication.php',
  504. 'CWebModule' => '/web/CWebModule.php',
  505. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  506. 'CAction' => '/web/actions/CAction.php',
  507. 'CInlineAction' => '/web/actions/CInlineAction.php',
  508. 'CViewAction' => '/web/actions/CViewAction.php',
  509. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  510. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  511. 'CAuthItem' => '/web/auth/CAuthItem.php',
  512. 'CAuthManager' => '/web/auth/CAuthManager.php',
  513. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  514. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  515. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  516. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  517. 'CWebUser' => '/web/auth/CWebUser.php',
  518. 'CFilter' => '/web/filters/CFilter.php',
  519. 'CFilterChain' => '/web/filters/CFilterChain.php',
  520. 'CHttpCacheFilter' => '/web/filters/CHttpCacheFilter.php',
  521. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  522. 'CForm' => '/web/form/CForm.php',
  523. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  524. 'CFormElement' => '/web/form/CFormElement.php',
  525. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  526. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  527. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  528. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  529. 'CHtml' => '/web/helpers/CHtml.php',
  530. 'CJSON' => '/web/helpers/CJSON.php',
  531. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  532. 'CJavaScriptExpression' => '/web/helpers/CJavaScriptExpression.php',
  533. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  534. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  535. 'CWebService' => '/web/services/CWebService.php',
  536. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  537. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  538. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  539. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  540. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  541. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  542. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  543. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  544. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  545. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  546. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  547. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  548. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  549. 'COutputCache' => '/web/widgets/COutputCache.php',
  550. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  551. 'CStarRating' => '/web/widgets/CStarRating.php',
  552. 'CTabView' => '/web/widgets/CTabView.php',
  553. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  554. 'CTreeView' => '/web/widgets/CTreeView.php',
  555. 'CWidget' => '/web/widgets/CWidget.php',
  556. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  557. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  558. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  559. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  560. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  561. );
  562. }
  563. spl_autoload_register(array('YiiBase','autoload'));
  564. class Yii extends YiiBase
  565. {
  566. }
  567. class CComponent
  568. {
  569. private $_e;
  570. private $_m;
  571. public function __get($name)
  572. {
  573. $getter='get'.$name;
  574. if(method_exists($this,$getter))
  575. return $this->$getter();
  576. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  577. {
  578. // duplicating getEventHandlers() here for performance
  579. $name=strtolower($name);
  580. if(!isset($this->_e[$name]))
  581. $this->_e[$name]=new CList;
  582. return $this->_e[$name];
  583. }
  584. else if(isset($this->_m[$name]))
  585. return $this->_m[$name];
  586. else if(is_array($this->_m))
  587. {
  588. foreach($this->_m as $object)
  589. {
  590. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  591. return $object->$name;
  592. }
  593. }
  594. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  595. array('{class}'=>get_class($this), '{property}'=>$name)));
  596. }
  597. public function __set($name,$value)
  598. {
  599. $setter='set'.$name;
  600. if(method_exists($this,$setter))
  601. return $this->$setter($value);
  602. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  603. {
  604. // duplicating getEventHandlers() here for performance
  605. $name=strtolower($name);
  606. if(!isset($this->_e[$name]))
  607. $this->_e[$name]=new CList;
  608. return $this->_e[$name]->add($value);
  609. }
  610. else if(is_array($this->_m))
  611. {
  612. foreach($this->_m as $object)
  613. {
  614. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  615. return $object->$name=$value;
  616. }
  617. }
  618. if(method_exists($this,'get'.$name))
  619. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  620. array('{class}'=>get_class($this), '{property}'=>$name)));
  621. else
  622. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  623. array('{class}'=>get_class($this), '{property}'=>$name)));
  624. }
  625. public function __isset($name)
  626. {
  627. $getter='get'.$name;
  628. if(method_exists($this,$getter))
  629. return $this->$getter()!==null;
  630. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  631. {
  632. $name=strtolower($name);
  633. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  634. }
  635. else if(is_array($this->_m))
  636. {
  637. if(isset($this->_m[$name]))
  638. return true;
  639. foreach($this->_m as $object)
  640. {
  641. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  642. return $object->$name!==null;
  643. }
  644. }
  645. return false;
  646. }
  647. public function __unset($name)
  648. {
  649. $setter='set'.$name;
  650. if(method_exists($this,$setter))
  651. $this->$setter(null);
  652. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  653. unset($this->_e[strtolower($name)]);
  654. else if(is_array($this->_m))
  655. {
  656. if(isset($this->_m[$name]))
  657. $this->detachBehavior($name);
  658. else
  659. {
  660. foreach($this->_m as $object)
  661. {
  662. if($object->getEnabled())
  663. {
  664. if(property_exists($object,$name))
  665. return $object->$name=null;
  666. else if($object->canSetProperty($name))
  667. return $object->$setter(null);
  668. }
  669. }
  670. }
  671. }
  672. else if(method_exists($this,'get'.$name))
  673. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  674. array('{class}'=>get_class($this), '{property}'=>$name)));
  675. }
  676. public function __call($name,$parameters)
  677. {
  678. if($this->_m!==null)
  679. {
  680. foreach($this->_m as $object)
  681. {
  682. if($object->getEnabled() && method_exists($object,$name))
  683. return call_user_func_array(array($object,$name),$parameters);
  684. }
  685. }
  686. if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)
  687. return call_user_func_array($this->$name, $parameters);
  688. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  689. array('{class}'=>get_class($this), '{name}'=>$name)));
  690. }
  691. public function asa($behavior)
  692. {
  693. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  694. }
  695. public function attachBehaviors($behaviors)
  696. {
  697. foreach($behaviors as $name=>$behavior)
  698. $this->attachBehavior($name,$behavior);
  699. }
  700. public function detachBehaviors()
  701. {
  702. if($this->_m!==null)
  703. {
  704. foreach($this->_m as $name=>$behavior)
  705. $this->detachBehavior($name);
  706. $this->_m=null;
  707. }
  708. }
  709. public function attachBehavior($name,$behavior)
  710. {
  711. if(!($behavior instanceof IBehavior))
  712. $behavior=Yii::createComponent($behavior);
  713. $behavior->setEnabled(true);
  714. $behavior->attach($this);
  715. return $this->_m[$name]=$behavior;
  716. }
  717. public function detachBehavior($name)
  718. {
  719. if(isset($this->_m[$name]))
  720. {
  721. $this->_m[$name]->detach($this);
  722. $behavior=$this->_m[$name];
  723. unset($this->_m[$name]);
  724. return $behavior;
  725. }
  726. }
  727. public function enableBehaviors()
  728. {
  729. if($this->_m!==null)
  730. {
  731. foreach($this->_m as $behavior)
  732. $behavior->setEnabled(true);
  733. }
  734. }
  735. public function disableBehaviors()
  736. {
  737. if($this->_m!==null)
  738. {
  739. foreach($this->_m as $behavior)
  740. $behavior->setEnabled(false);
  741. }
  742. }
  743. public function enableBehavior($name)
  744. {
  745. if(isset($this->_m[$name]))
  746. $this->_m[$name]->setEnabled(true);
  747. }
  748. public function disableBehavior($name)
  749. {
  750. if(isset($this->_m[$name]))
  751. $this->_m[$name]->setEnabled(false);
  752. }
  753. public function hasProperty($name)
  754. {
  755. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  756. }
  757. public function canGetProperty($name)
  758. {
  759. return method_exists($this,'get'.$name);
  760. }
  761. public function canSetProperty($name)
  762. {
  763. return method_exists($this,'set'.$name);
  764. }
  765. public function hasEvent($name)
  766. {
  767. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  768. }
  769. public function hasEventHandler($name)
  770. {
  771. $name=strtolower($name);
  772. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  773. }
  774. public function getEventHandlers($name)
  775. {
  776. if($this->hasEvent($name))
  777. {
  778. $name=strtolower($name);
  779. if(!isset($this->_e[$name]))
  780. $this->_e[$name]=new CList;
  781. return $this->_e[$name];
  782. }
  783. else
  784. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  785. array('{class}'=>get_class($this), '{event}'=>$name)));
  786. }
  787. public function attachEventHandler($name,$handler)
  788. {
  789. $this->getEventHandlers($name)->add($handler);
  790. }
  791. public function detachEventHandler($name,$handler)
  792. {
  793. if($this->hasEventHandler($name))
  794. return $this->getEventHandlers($name)->remove($handler)!==false;
  795. else
  796. return false;
  797. }
  798. public function raiseEvent($name,$event)
  799. {
  800. $name=strtolower($name);
  801. if(isset($this->_e[$name]))
  802. {
  803. foreach($this->_e[$name] as $handler)
  804. {
  805. if(is_string($handler))
  806. call_user_func($handler,$event);
  807. else if(is_callable($handler,true))
  808. {
  809. if(is_array($handler))
  810. {
  811. // an array: 0 - object, 1 - method name
  812. list($object,$method)=$handler;
  813. if(is_string($object)) // static method call
  814. call_user_func($handler,$event);
  815. else if(method_exists($object,$method))
  816. $object->$method($event);
  817. else
  818. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  819. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  820. }
  821. else // PHP 5.3: anonymous function
  822. call_user_func($handler,$event);
  823. }
  824. else
  825. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  826. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  827. // stop further handling if param.handled is set true
  828. if(($event instanceof CEvent) && $event->handled)
  829. return;
  830. }
  831. }
  832. else if(YII_DEBUG && !$this->hasEvent($name))
  833. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  834. array('{class}'=>get_class($this), '{event}'=>$name)));
  835. }
  836. public function evaluateExpression($_expression_,$_data_=array())
  837. {
  838. if(is_string($_expression_) && !function_exists($_expression_))
  839. {
  840. extract($_data_);
  841. return eval('return '.$_expression_.';');
  842. }
  843. else
  844. {
  845. $_data_[]=$this;
  846. return call_user_func_array($_expression_, $_data_);
  847. }
  848. }
  849. }
  850. class CEvent extends CComponent
  851. {
  852. public $sender;
  853. public $handled=false;
  854. public $params;
  855. public function __construct($sender=null,$params=null)
  856. {
  857. $this->sender=$sender;
  858. $this->params=$params;
  859. }
  860. }
  861. class CEnumerable
  862. {
  863. }
  864. abstract class CModule extends CComponent
  865. {
  866. public $preload=array();
  867. public $behaviors=array();
  868. private $_id;
  869. private $_parentModule;
  870. private $_basePath;
  871. private $_modulePath;
  872. private $_params;
  873. private $_modules=array();
  874. private $_moduleConfig=array();
  875. private $_components=array();
  876. private $_componentConfig=array();
  877. public function __construct($id,$parent,$config=null)
  878. {
  879. $this->_id=$id;
  880. $this->_parentModule=$parent;
  881. // set basePath at early as possible to avoid trouble
  882. if(is_string($config))
  883. $config=require($config);
  884. if(isset($config['basePath']))
  885. {
  886. $this->setBasePath($config['basePath']);
  887. unset($config['basePath']);
  888. }
  889. Yii::setPathOfAlias($id,$this->getBasePath());
  890. $this->preinit();
  891. $this->configure($config);
  892. $this->attachBehaviors($this->behaviors);
  893. $this->preloadComponents();
  894. $this->init();
  895. }
  896. public function __get($name)
  897. {
  898. if($this->hasComponent($name))
  899. return $this->getComponent($name);
  900. else
  901. return parent::__get($name);
  902. }
  903. public function __isset($name)
  904. {
  905. if($this->hasComponent($name))
  906. return $this->getComponent($name)!==null;
  907. else
  908. return parent::__isset($name);
  909. }
  910. public function getId()
  911. {
  912. return $this->_id;
  913. }
  914. public function setId($id)
  915. {
  916. $this->_id=$id;
  917. }
  918. public function getBasePath()
  919. {
  920. if($this->_basePath===null)
  921. {
  922. $class=new ReflectionClass(get_class($this));
  923. $this->_basePath=dirname($class->getFileName());
  924. }
  925. return $this->_basePath;
  926. }
  927. public function setBasePath($path)
  928. {
  929. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  930. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  931. array('{path}'=>$path)));
  932. }
  933. public function getParams()
  934. {
  935. if($this->_params!==null)
  936. return $this->_params;
  937. else
  938. {
  939. $this->_params=new CAttributeCollection;
  940. $this->_params->caseSensitive=true;
  941. return $this->_params;
  942. }
  943. }
  944. public function setParams($value)
  945. {
  946. $params=$this->getParams();
  947. foreach($value as $k=>$v)
  948. $params->add($k,$v);
  949. }
  950. public function getModulePath()
  951. {
  952. if($this->_modulePath!==null)
  953. return $this->_modulePath;
  954. else
  955. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  956. }
  957. public function setModulePath($value)
  958. {
  959. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  960. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  961. array('{path}'=>$value)));
  962. }
  963. public function setImport($aliases)
  964. {
  965. foreach($aliases as $alias)
  966. Yii::import($alias);
  967. }
  968. public function setAliases($mappings)
  969. {
  970. foreach($mappings as $name=>$alias)
  971. {
  972. if(($path=Yii::getPathOfAlias($alias))!==false)
  973. Yii::setPathOfAlias($name,$path);
  974. else
  975. Yii::setPathOfAlias($name,$alias);
  976. }
  977. }
  978. public function getParentModule()
  979. {
  980. return $this->_parentModule;
  981. }
  982. public function getModule($id)
  983. {
  984. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  985. return $this->_modules[$id];
  986. else if(isset($this->_moduleConfig[$id]))
  987. {
  988. $config=$this->_moduleConfig[$id];
  989. if(!isset($config['enabled']) || $config['enabled'])
  990. {
  991. $class=$config['class'];
  992. unset($config['class'], $config['enabled']);
  993. if($this===Yii::app())
  994. $module=Yii::createComponent($class,$id,null,$config);
  995. else
  996. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  997. return $this->_modules[$id]=$module;
  998. }
  999. }
  1000. }
  1001. public function hasModule($id)
  1002. {
  1003. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  1004. }
  1005. public function getModules()
  1006. {
  1007. return $this->_moduleConfig;
  1008. }
  1009. public function setModules($modules)
  1010. {
  1011. foreach($modules as $id=>$module)
  1012. {
  1013. if(is_int($id))
  1014. {
  1015. $id=$module;
  1016. $module=array();
  1017. }
  1018. if(!isset($module['class']))
  1019. {
  1020. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1021. $module['class']=$id.'.'.ucfirst($id).'Module';
  1022. }
  1023. if(isset($this->_moduleConfig[$id]))
  1024. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1025. else
  1026. $this->_moduleConfig[$id]=$module;
  1027. }
  1028. }
  1029. public function hasComponent($id)
  1030. {
  1031. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1032. }
  1033. public function getComponent($id,$createIfNull=true)
  1034. {
  1035. if(isset($this->_components[$id]))
  1036. return $this->_components[$id];
  1037. else if(isset($this->_componentConfig[$id]) && $createIfNull)
  1038. {
  1039. $config=$this->_componentConfig[$id];
  1040. if(!isset($config['enabled']) || $config['enabled'])
  1041. {
  1042. unset($config['enabled']);
  1043. $component=Yii::createComponent($config);
  1044. $component->init();
  1045. return $this->_components[$id]=$component;
  1046. }
  1047. }
  1048. }
  1049. public function setComponent($id,$component)
  1050. {
  1051. if($component===null)
  1052. unset($this->_components[$id]);
  1053. else
  1054. {
  1055. $this->_components[$id]=$component;
  1056. if(!$component->getIsInitialized())
  1057. $component->init();
  1058. }
  1059. }
  1060. public function getComponents($loadedOnly=true)
  1061. {
  1062. if($loadedOnly)
  1063. return $this->_components;
  1064. else
  1065. return array_merge($this->_componentConfig, $this->_components);
  1066. }
  1067. public function setComponents($components,$merge=true)
  1068. {
  1069. foreach($components as $id=>$component)
  1070. {
  1071. if($component instanceof IApplicationComponent)
  1072. $this->setComponent($id,$component);
  1073. else if(isset($this->_componentConfig[$id]) && $merge)
  1074. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1075. else
  1076. $this->_componentConfig[$id]=$component;
  1077. }
  1078. }
  1079. public function configure($config)
  1080. {
  1081. if(is_array($config))
  1082. {
  1083. foreach($config as $key=>$value)
  1084. $this->$key=$value;
  1085. }
  1086. }
  1087. protected function preloadComponents()
  1088. {
  1089. foreach($this->preload as $id)
  1090. $this->getComponent($id);
  1091. }
  1092. protected function preinit()
  1093. {
  1094. }
  1095. protected function init()
  1096. {
  1097. }
  1098. }
  1099. abstract class CApplication extends CModule
  1100. {
  1101. public $name='My Application';
  1102. public $charset='UTF-8';
  1103. public $sourceLanguage='en_us';
  1104. private $_id;
  1105. private $_basePath;
  1106. private $_runtimePath;
  1107. private $_extensionPath;
  1108. private $_globalState;
  1109. private $_stateChanged;
  1110. private $_ended=false;
  1111. private $_language;
  1112. private $_homeUrl;
  1113. abstract public function processRequest();
  1114. public function __construct($config=null)
  1115. {
  1116. Yii::setApplication($this);
  1117. // set basePath at early as possible to avoid trouble
  1118. if(is_string($config))
  1119. $config=require($config);
  1120. if(isset($config['basePath']))
  1121. {
  1122. $this->setBasePath($config['basePath']);
  1123. unset($config['basePath']);
  1124. }
  1125. else
  1126. $this->setBasePath('protected');
  1127. Yii::setPathOfAlias('application',$this->getBasePath());
  1128. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1129. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1130. $this->preinit();
  1131. $this->initSystemHandlers();
  1132. $this->registerCoreComponents();
  1133. $this->configure($config);
  1134. $this->attachBehaviors($this->behaviors);
  1135. $this->preloadComponents();
  1136. $this->init();
  1137. }
  1138. public function run()
  1139. {
  1140. if($this->hasEventHandler('onBeginRequest'))
  1141. $this->onBeginRequest(new CEvent($this));
  1142. $this->processRequest();
  1143. if($this->hasEventHandler('onEndRequest'))
  1144. $this->onEndRequest(new CEvent($this));
  1145. }
  1146. public function end($status=0, $exit=true)
  1147. {
  1148. if($this->hasEventHandler('onEndRequest'))
  1149. $this->onEndRequest(new CEvent($this));
  1150. if($exit)
  1151. exit($status);
  1152. }
  1153. public function onBeginRequest($event)
  1154. {
  1155. $this->raiseEvent('onBeginRequest',$event);
  1156. }
  1157. public function onEndRequest($event)
  1158. {
  1159. if(!$this->_ended)
  1160. {
  1161. $this->_ended=true;
  1162. $this->raiseEvent('onEndRequest',$event);
  1163. }
  1164. }
  1165. public function getId()
  1166. {
  1167. if($this->_id!==null)
  1168. return $this->_id;
  1169. else
  1170. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1171. }
  1172. public function setId($id)
  1173. {
  1174. $this->_id=$id;
  1175. }
  1176. public function getBasePath()
  1177. {
  1178. return $this->_basePath;
  1179. }
  1180. public function setBasePath($path)
  1181. {
  1182. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1183. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1184. array('{path}'=>$path)));
  1185. }
  1186. public function getRuntimePath()
  1187. {
  1188. if($this->_runtimePath!==null)
  1189. return $this->_runtimePath;
  1190. else
  1191. {
  1192. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1193. return $this->_runtimePath;
  1194. }
  1195. }
  1196. public function setRuntimePath($path)
  1197. {
  1198. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1199. 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.',
  1200. array('{path}'=>$path)));
  1201. $this->_runtimePath=$runtimePath;
  1202. }
  1203. public function getExtensionPath()
  1204. {
  1205. return Yii::getPathOfAlias('ext');
  1206. }
  1207. public function setExtensionPath($path)
  1208. {
  1209. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1210. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1211. array('{path}'=>$path)));
  1212. Yii::setPathOfAlias('ext',$extensionPath);
  1213. }
  1214. public function getLanguage()
  1215. {
  1216. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1217. }
  1218. public function setLanguage($language)
  1219. {
  1220. $this->_language=$language;
  1221. }
  1222. public function getTimeZone()
  1223. {
  1224. return date_default_timezone_get();
  1225. }
  1226. public function setTimeZone($value)
  1227. {
  1228. date_default_timezone_set($value);
  1229. }
  1230. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1231. {
  1232. if($srcLanguage===null)
  1233. $srcLanguage=$this->sourceLanguage;
  1234. if($language===null)
  1235. $language=$this->getLanguage();
  1236. if($language===$srcLanguage)
  1237. return $srcFile;
  1238. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1239. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1240. }
  1241. public function getLocale($localeID=null)
  1242. {
  1243. return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID);
  1244. }
  1245. public function getLocaleDataPath()
  1246. {
  1247. return CLocale::$dataPath===null ? Yii::getPathOfAlias('system.i18n.data') : CLocale::$dataPath;
  1248. }
  1249. public function setLocaleDataPath($value)
  1250. {
  1251. CLocale::$dataPath=$value;
  1252. }
  1253. public function getNumberFormatter()
  1254. {
  1255. return $this->getLocale()->getNumberFormatter();
  1256. }
  1257. public function getDateFormatter()
  1258. {
  1259. return $this->getLocale()->getDateFormatter();
  1260. }
  1261. public function getDb()
  1262. {
  1263. return $this->getComponent('db');
  1264. }
  1265. public function getErrorHandler()
  1266. {
  1267. return $this->getComponent('errorHandler');
  1268. }
  1269. public function getSecurityManager()
  1270. {
  1271. return $this->getComponent('securityManager');
  1272. }
  1273. public function getStatePersister()
  1274. {
  1275. return $this->getComponent('statePersister');
  1276. }
  1277. public function getCache()
  1278. {
  1279. return $this->getComponent('cache');
  1280. }
  1281. public function getCoreMessages()
  1282. {
  1283. return $this->getComponent('coreMessages');
  1284. }
  1285. public function getMessages()
  1286. {
  1287. return $this->getComponent('messages');
  1288. }
  1289. public function getRequest()
  1290. {
  1291. return $this->getComponent('request');
  1292. }
  1293. public function getUrlManager()
  1294. {
  1295. return $this->getComponent('urlManager');
  1296. }
  1297. public function getController()
  1298. {
  1299. return null;
  1300. }
  1301. public function createUrl($route,$params=array(),$ampersand='&')
  1302. {
  1303. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1304. }
  1305. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1306. {
  1307. $url=$this->createUrl($route,$params,$ampersand);
  1308. if(strpos($url,'http')===0)
  1309. return $url;
  1310. else
  1311. return $this->getRequest()->getHostInfo($schema).$url;
  1312. }
  1313. public function getBaseUrl($absolute=false)
  1314. {
  1315. return $this->getRequest()->getBaseUrl($absolute);
  1316. }
  1317. public function getHomeUrl()
  1318. {
  1319. if($this->_homeUrl===null)
  1320. {
  1321. if($this->getUrlManager()->showScriptName)
  1322. return $this->getRequest()->getScriptUrl();
  1323. else
  1324. return $this->getRequest()->getBaseUrl().'/';
  1325. }
  1326. else
  1327. return $this->_homeUrl;
  1328. }
  1329. public function setHomeUrl($value)
  1330. {
  1331. $this->_homeUrl=$value;
  1332. }
  1333. public function getGlobalState($key,$defaultValue=null)
  1334. {
  1335. if($this->_globalState===null)
  1336. $this->loadGlobalState();
  1337. if(isset($this->_globalState[$key]))
  1338. return $this->_globalState[$key];
  1339. else
  1340. return $defaultValue;
  1341. }
  1342. public function setGlobalState($key,$value,$defaultValue=null)
  1343. {
  1344. if($this->_globalState===null)
  1345. $this->loadGlobalState();
  1346. $changed=$this->_stateChanged;
  1347. if($value===$defaultValue)
  1348. {
  1349. if(isset($this->_globalState[$key]))
  1350. {
  1351. unset($this->_globalState[$key]);
  1352. $this->_stateChanged=true;
  1353. }
  1354. }
  1355. else if(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1356. {
  1357. $this->_globalState[$key]=$value;
  1358. $this->_stateChanged=true;
  1359. }
  1360. if($this->_stateChanged!==$changed)
  1361. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1362. }
  1363. public function clearGlobalState($key)
  1364. {
  1365. $this->setGlobalState($key,true,true);
  1366. }
  1367. public function loadGlobalState()
  1368. {
  1369. $persister=$this->getStatePersister();
  1370. if(($this->_globalState=$persister->load())===null)
  1371. $this->_globalState=array();
  1372. $this->_stateChanged=false;
  1373. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1374. }
  1375. public function saveGlobalState()
  1376. {
  1377. if($this->_stateChanged)
  1378. {
  1379. $this->_stateChanged=false;
  1380. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1381. $this->getStatePersister()->save($this->_globalState);
  1382. }
  1383. }
  1384. public function handleException($exception)
  1385. {
  1386. // disable error capturing to avoid recursive errors
  1387. restore_error_handler();
  1388. restore_exception_handler();
  1389. $category='exception.'.get_class($exception);
  1390. if($exception instanceof CHttpException)
  1391. $category.='.'.$exception->statusCode;
  1392. // php <5.2 doesn't support string conversion auto-magically
  1393. $message=$exception->__toString();
  1394. if(isset($_SERVER['REQUEST_URI']))
  1395. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  1396. if(isset($_SERVER['HTTP_REFERER']))
  1397. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  1398. $message.="\n---";
  1399. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1400. try
  1401. {
  1402. $event=new CExceptionEvent($this,$exception);
  1403. $this->onException($event);
  1404. if(!$event->handled)
  1405. {
  1406. // try an error handler
  1407. if(($handler=$this->getErrorHandler())!==null)
  1408. $handler->handle($event);
  1409. else
  1410. $this->displayException($exception);
  1411. }
  1412. }
  1413. catch(Exception $e)
  1414. {
  1415. $this->displayException($e);
  1416. }
  1417. try
  1418. {
  1419. $this->end(1);
  1420. }
  1421. catch(Exception $e)
  1422. {
  1423. // use the most primitive way to log error
  1424. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1425. $msg .= $e->getTraceAsString()."\n";
  1426. $msg .= "Previous exception:\n";
  1427. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1428. $msg .= $exception->getTraceAsString()."\n";
  1429. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1430. error_log($msg);
  1431. exit(1);
  1432. }
  1433. }
  1434. public function handleError($code,$message,$file,$line)
  1435. {
  1436. if($code & error_reporting())
  1437. {
  1438. // disable error capturing to avoid recursive errors
  1439. restore_error_handler();
  1440. restore_exception_handler();
  1441. $log="$message ($file:$line)\nStack trace:\n";
  1442. $trace=debug_backtrace();
  1443. // skip the first 3 stacks as they do not tell the error position
  1444. if(count($trace)>3)
  1445. $trace=array_slice($trace,3);
  1446. foreach($trace as $i=>$t)
  1447. {
  1448. if(!isset($t['file']))
  1449. $t['file']='unknown';
  1450. if(!isset($t['line']))
  1451. $t['line']=0;
  1452. if(!isset($t['function']))
  1453. $t['function']='unknown';
  1454. $log.="#$i {$t['file']}({$t['line']}): ";
  1455. if(isset($t['object']) && is_object($t['object']))
  1456. $log.=get_class($t['object']).'->';
  1457. $log.="{$t['function']}()\n";
  1458. }
  1459. if(isset($_SERVER['REQUEST_URI']))
  1460. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1461. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1462. try
  1463. {
  1464. Yii::import('CErrorEvent',true);
  1465. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1466. $this->onError($event);
  1467. if(!$event->handled)
  1468. {
  1469. // try an error handler
  1470. if(($handler=$this->getErrorHandler())!==null)
  1471. $handler->handle($event);
  1472. else
  1473. $this->displayError($code,$message,$file,$line);
  1474. }
  1475. }
  1476. catch(Exception $e)
  1477. {
  1478. $this->displayException($e);
  1479. }
  1480. try
  1481. {
  1482. $this->end(1);
  1483. }
  1484. catch(Exception $e)
  1485. {
  1486. // use the most primitive way to log error
  1487. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1488. $msg .= $e->getTraceAsString()."\n";
  1489. $msg .= "Previous error:\n";
  1490. $msg .= $log."\n";
  1491. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1492. error_log($msg);
  1493. exit(1);
  1494. }
  1495. }
  1496. }
  1497. public function onException($event)
  1498. {
  1499. $this->raiseEvent('onException',$event);
  1500. }
  1501. public function onError($event)
  1502. {
  1503. $this->raiseEvent('onError',$event);
  1504. }
  1505. public function displayError($code,$message,$file,$line)
  1506. {
  1507. if(YII_DEBUG)
  1508. {
  1509. echo "<h1>PHP Error [$code]</h1>\n";
  1510. echo "<p>$message ($file:$line)</p>\n";
  1511. echo '<pre>';
  1512. $trace=debug_backtrace();
  1513. // skip the first 3 stacks as they do not tell the error position
  1514. if(count($trace)>3)
  1515. $trace=array_slice($trace,3);
  1516. foreach($trace as $i=>$t)
  1517. {
  1518. if(!isset($t['file']))
  1519. $t['file']='unknown';
  1520. if(!isset($t['line']))
  1521. $t['line']=0;
  1522. if(!isset($t['function']))
  1523. $t['function']='unknown';
  1524. echo "#$i {$t['file']}({$t['line']}): ";
  1525. if(isset($t['object']) && is_object($t['object']))
  1526. echo get_class($t['object']).'->';
  1527. echo "{$t['function']}()\n";
  1528. }
  1529. echo '</pre>';
  1530. }
  1531. else
  1532. {
  1533. echo "<h1>PHP Error [$code]</h1>\n";
  1534. echo "<p>$message</p>\n";
  1535. }
  1536. }
  1537. public function displayException($exception)
  1538. {
  1539. if(YII_DEBUG)
  1540. {
  1541. echo '<h1>'.get_class($exception)."</h1>\n";
  1542. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1543. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1544. }
  1545. else
  1546. {
  1547. echo '<h1>'.get_class($exception)."</h1>\n";
  1548. echo '<p>'.$exception->getMessage().'</p>';
  1549. }
  1550. }
  1551. protected function initSystemHandlers()
  1552. {
  1553. if(YII_ENABLE_EXCEPTION_HANDLER)
  1554. set_exception_handler(array($this,'handleException'));
  1555. if(YII_ENABLE_ERROR_HANDLER)
  1556. set_error_handler(array($this,'handleError'),error_reporting());
  1557. }
  1558. protected function registerCoreComponents()
  1559. {
  1560. $components=array(
  1561. 'coreMessages'=>array(
  1562. 'class'=>'CPhpMessageSource',
  1563. 'language'=>'en_us',
  1564. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1565. ),
  1566. 'db'=>array(
  1567. 'class'=>'CDbConnection',
  1568. ),
  1569. 'messages'=>array(
  1570. 'class'=>'CPhpMessageSource',
  1571. ),
  1572. 'errorHandler'=>array(
  1573. 'class'=>'CErrorHandler',
  1574. ),
  1575. 'securityManager'=>array(
  1576. 'class'=>'CSecurityManager',
  1577. ),
  1578. 'statePersister'=>array(
  1579. 'class'=>'CStatePersister',
  1580. ),
  1581. 'urlManager'=>array(
  1582. 'class'=>'CUrlManager',
  1583. ),
  1584. 'request'=>array(
  1585. 'class'=>'CHttpRequest',
  1586. ),
  1587. 'format'=>array(
  1588. 'class'=>'CFormatter',
  1589. ),
  1590. );
  1591. $this->setComponents($components);
  1592. }
  1593. }
  1594. class CWebApplication extends CApplication
  1595. {
  1596. public $defaultController='site';
  1597. public $layout='main';
  1598. public $controllerMap=array();
  1599. public $catchAllRequest;
  1600. public $controllerNamespace;
  1601. private $_controllerPath;
  1602. private $_viewPath;
  1603. private $_systemViewPath;
  1604. private $_layoutPath;
  1605. private $_controller;
  1606. private $_theme;
  1607. public function processRequest()
  1608. {
  1609. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1610. {
  1611. $route=$this->catchAllRequest[0];
  1612. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1613. $_GET[$name]=$value;
  1614. }
  1615. else
  1616. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1617. $this->runController($route);
  1618. }
  1619. protected function registerCoreComponents()
  1620. {
  1621. parent::registerCoreComponents();
  1622. $components=array(
  1623. 'session'=>array(
  1624. 'class'=>'CHttpSession',
  1625. ),
  1626. 'assetManager'=>array(
  1627. 'class'=>'CAssetManager',
  1628. ),
  1629. 'user'=>array(
  1630. 'class'=>'CWebUser',
  1631. ),
  1632. 'themeManager'=>array(
  1633. 'class'=>'CThemeManager',
  1634. ),
  1635. 'authManager'=>array(
  1636. 'class'=>'CPhpAuthManager',
  1637. ),
  1638. 'clientScript'=>array(
  1639. 'class'=>'CClientScript',
  1640. ),
  1641. 'widgetFactory'=>array(
  1642. 'class'=>'CWidgetFactory',
  1643. ),
  1644. );
  1645. $this->setComponents($components);
  1646. }
  1647. public function getAuthManager()
  1648. {
  1649. return $this->getComponent('authManager');
  1650. }
  1651. public function getAssetManager()
  1652. {
  1653. return $this->getComponent('assetManager');
  1654. }
  1655. public function getSession()
  1656. {
  1657. return $this->getComponent('session');
  1658. }
  1659. public function getUser()
  1660. {
  1661. return $this->getComponent('user');
  1662. }
  1663. public function getViewRenderer()
  1664. {
  1665. return $this->getComponent('viewRenderer');
  1666. }
  1667. public function getClientScript()
  1668. {
  1669. return $this->getComponent('clientScript');
  1670. }
  1671. public function getWidgetFactory()
  1672. {
  1673. return $this->getComponent('widgetFactory');
  1674. }
  1675. public function getThemeManager()
  1676. {
  1677. return $this->getComponent('themeManager');
  1678. }
  1679. public function getTheme()
  1680. {
  1681. if(is_string($this->_theme))
  1682. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1683. return $this->_theme;
  1684. }
  1685. public function setTheme($value)
  1686. {
  1687. $this->_theme=$value;
  1688. }
  1689. public function runController($route)
  1690. {
  1691. if(($ca=$this->createController($route))!==null)
  1692. {
  1693. list($controller,$actionID)=$ca;
  1694. $oldController=$this->_controller;
  1695. $this->_controller=$controller;
  1696. $controller->init();
  1697. $controller->run($actionID);
  1698. $this->_controller=$oldController;
  1699. }
  1700. else
  1701. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1702. array('{route}'=>$route===''?$this->defaultController:$route)));
  1703. }
  1704. public function createController($route,$owner=null)
  1705. {
  1706. if($owner===null)
  1707. $owner=$this;
  1708. if(($route=trim($route,'/'))==='')
  1709. $route=$owner->defaultController;
  1710. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1711. $route.='/';
  1712. while(($pos=strpos($route,'/'))!==false)
  1713. {
  1714. $id=substr($route,0,$pos);
  1715. if(!preg_match('/^\w+$/',$id))
  1716. return null;
  1717. if(!$caseSensitive)
  1718. $id=strtolower($id);
  1719. $route=(string)substr($route,$pos+1);
  1720. if(!isset($basePath)) // first segment
  1721. {
  1722. if(isset($owner->controllerMap[$id]))
  1723. {
  1724. return array(
  1725. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1726. $this->parseActionParams($route),
  1727. );
  1728. }
  1729. if(($module=$owner->getModule($id))!==null)
  1730. return $this->createController($route,$module);
  1731. $basePath=$owner->getControllerPath();
  1732. $controllerID='';
  1733. }
  1734. else
  1735. $controllerID.='/';
  1736. $className=ucfirst($id).'Controller';
  1737. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1738. if($owner->controllerNamespace!==null)
  1739. $className=$owner->controllerNamespace.'\\'.$className;
  1740. if(is_file($classFile))
  1741. {
  1742. if(!class_exists($className,false))
  1743. require($classFile);
  1744. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1745. {
  1746. $id[0]=strtolower($id[0]);
  1747. return array(
  1748. new $className($controllerID.$id,$owner===$this?null:$owner),
  1749. $this->parseActionParams($route),
  1750. );
  1751. }
  1752. return null;
  1753. }
  1754. $controllerID.=$id;
  1755. $basePath.=DIRECTORY_SEPARATOR.$id;
  1756. }
  1757. }
  1758. protected function parseActionParams($pathInfo)
  1759. {
  1760. if(($pos=strpos($pathInfo,'/'))!==false)
  1761. {
  1762. $manager=$this->getUrlManager();
  1763. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1764. $actionID=substr($pathInfo,0,$pos);
  1765. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1766. }
  1767. else
  1768. return $pathInfo;
  1769. }
  1770. public function getController()
  1771. {
  1772. return $this->_controller;
  1773. }
  1774. public function setController($value)
  1775. {
  1776. $this->_controller=$value;
  1777. }
  1778. public function getControllerPath()
  1779. {
  1780. if($this->_controllerPath!==null)
  1781. return $this->_controllerPath;
  1782. else
  1783. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1784. }
  1785. public function setControllerPath($value)
  1786. {
  1787. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1788. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1789. array('{path}'=>$value)));
  1790. }
  1791. public function getViewPath()
  1792. {
  1793. if($this->_viewPath!==null)
  1794. return $this->_viewPath;
  1795. else
  1796. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1797. }
  1798. public function setViewPath($path)
  1799. {
  1800. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1801. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1802. array('{path}'=>$path)));
  1803. }
  1804. public function getSystemViewPath()
  1805. {
  1806. if($this->_systemViewPath!==null)
  1807. return $this->_systemViewPath;
  1808. else
  1809. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1810. }
  1811. public function setSystemViewPath($path)
  1812. {
  1813. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1814. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1815. array('{path}'=>$path)));
  1816. }
  1817. public function getLayoutPath()
  1818. {
  1819. if($this->_layoutPath!==null)
  1820. return $this->_layoutPath;
  1821. else
  1822. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1823. }
  1824. public function setLayoutPath($path)
  1825. {
  1826. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1827. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1828. array('{path}'=>$path)));
  1829. }
  1830. public function beforeControllerAction($controller,$action)
  1831. {
  1832. return true;
  1833. }
  1834. public function afterControllerAction($controller,$action)
  1835. {
  1836. }
  1837. public function findModule($id)
  1838. {
  1839. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1840. {
  1841. do
  1842. {
  1843. if(($m=$module->getModule($id))!==null)
  1844. return $m;
  1845. } while(($module=$module->getParentModule())!==null);
  1846. }
  1847. if(($m=$this->getModule($id))!==null)
  1848. return $m;
  1849. }
  1850. protected function init()
  1851. {
  1852. parent::init();
  1853. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1854. $this->getRequest();
  1855. }
  1856. }
  1857. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1858. {
  1859. private $_d=array();
  1860. private $_r=false;
  1861. public function __construct($data=null,$readOnly=false)
  1862. {
  1863. if($data!==null)
  1864. $this->copyFrom($data);
  1865. $this->setReadOnly($readOnly);
  1866. }
  1867. public function getReadOnly()
  1868. {
  1869. return $this->_r;
  1870. }
  1871. protected function setReadOnly($value)
  1872. {
  1873. $this->_r=$value;
  1874. }
  1875. public function getIterator()
  1876. {
  1877. return new CMapIterator($this->_d);
  1878. }
  1879. public function count()
  1880. {
  1881. return $this->getCount();
  1882. }
  1883. public function getCount()
  1884. {
  1885. return count($this->_d);
  1886. }
  1887. public function getKeys()
  1888. {
  1889. return array_keys($this->_d);
  1890. }
  1891. public function itemAt($key)
  1892. {
  1893. if(isset($this->_d[$key]))
  1894. return $this->_d[$key];
  1895. else
  1896. return null;
  1897. }
  1898. public function add($key,$value)
  1899. {
  1900. if(!$this->_r)
  1901. {
  1902. if($key===null)
  1903. $this->_d[]=$value;
  1904. else
  1905. $this->_d[$key]=$value;
  1906. }
  1907. else
  1908. throw new CException(Yii::t('yii','The map is read only.'));
  1909. }
  1910. public function remove($key)
  1911. {
  1912. if(!$this->_r)
  1913. {
  1914. if(isset($this->_d[$key]))
  1915. {
  1916. $value=$this->_d[$key];
  1917. unset($this->_d[$key]);
  1918. return $value;
  1919. }
  1920. else
  1921. {
  1922. // it is possible the value is null, which is not detected by isset
  1923. unset($this->_d[$key]);
  1924. return null;
  1925. }
  1926. }
  1927. else
  1928. throw new CException(Yii::t('yii','The map is read only.'));
  1929. }
  1930. public function clear()
  1931. {
  1932. foreach(array_keys($this->_d) as $key)
  1933. $this->remove($key);
  1934. }
  1935. public function contains($key)
  1936. {
  1937. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  1938. }
  1939. public function toArray()
  1940. {
  1941. return $this->_d;
  1942. }
  1943. public function copyFrom($data)
  1944. {
  1945. if(is_array($data) || $data instanceof Traversable)
  1946. {
  1947. if($this->getCount()>0)
  1948. $this->clear();
  1949. if($data instanceof CMap)
  1950. $data=$data->_d;
  1951. foreach($data as $key=>$value)
  1952. $this->add($key,$value);
  1953. }
  1954. else if($data!==null)
  1955. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1956. }
  1957. public function mergeWith($data,$recursive=true)
  1958. {
  1959. if(is_array($data) || $data instanceof Traversable)
  1960. {
  1961. if($data instanceof CMap)
  1962. $data=$data->_d;
  1963. if($recursive)
  1964. {
  1965. if($data instanceof Traversable)
  1966. {
  1967. $d=array();
  1968. foreach($data as $key=>$value)
  1969. $d[$key]=$value;
  1970. $this->_d=self::mergeArray($this->_d,$d);
  1971. }
  1972. else
  1973. $this->_d=self::mergeArray($this->_d,$data);
  1974. }
  1975. else
  1976. {
  1977. foreach($data as $key=>$value)
  1978. $this->add($key,$value);
  1979. }
  1980. }
  1981. else if($data!==null)
  1982. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1983. }
  1984. public static function mergeArray($a,$b)
  1985. {
  1986. $args=func_get_args();
  1987. $res=array_shift($args);
  1988. while(!empty($args))
  1989. {
  1990. $next=array_shift($args);
  1991. foreach($next as $k => $v)
  1992. {
  1993. if(is_integer($k))
  1994. isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
  1995. else if(is_array($v) && isset($res[$k]) && is_array($res[$k]))
  1996. $res[$k]=self::mergeArray($res[$k],$v);
  1997. else
  1998. $res[$k]=$v;
  1999. }
  2000. }
  2001. return $res;
  2002. }
  2003. public function offsetExists($offset)
  2004. {
  2005. return $this->contains($offset);
  2006. }
  2007. public function offsetGet($offset)
  2008. {
  2009. return $this->itemAt($offset);
  2010. }
  2011. public function offsetSet($offset,$item)
  2012. {
  2013. $this->add($offset,$item);
  2014. }
  2015. public function offsetUnset($offset)
  2016. {
  2017. $this->remove($offset);
  2018. }
  2019. }
  2020. class CLogger extends CComponent
  2021. {
  2022. const LEVEL_TRACE='trace';
  2023. const LEVEL_WARNING='warning';
  2024. const LEVEL_ERROR='error';
  2025. const LEVEL_INFO='info';
  2026. const LEVEL_PROFILE='profile';
  2027. public $autoFlush=10000;
  2028. public $autoDump=false;
  2029. private $_logs=array();
  2030. private $_logCount=0;
  2031. private $_levels;
  2032. private $_categories;
  2033. private $_timings;
  2034. private $_processing=false;
  2035. public function log($message,$level='info',$category='application')
  2036. {
  2037. $this->_logs[]=array($message,$level,$category,microtime(true));
  2038. $this->_logCount++;
  2039. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
  2040. {
  2041. $this->_processing=true;
  2042. $this->flush($this->autoDump);
  2043. $this->_processing=false;
  2044. }
  2045. }
  2046. public function getLogs($levels='',$categories='')
  2047. {
  2048. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2049. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2050. if(empty($levels) && empty($categories))
  2051. return $this->_logs;
  2052. else if(empty($levels))
  2053. return array_values(array_filter($this->_logs,array($this,'filterByCategory')));
  2054. else if(empty($categories))
  2055. return array_values(array_filter($this->_logs,array($this,'filterByLevel')));
  2056. else
  2057. {
  2058. $ret=array_filter($this->_logs,array($this,'filterByLevel'));
  2059. return array_values(array_filter($ret,array($this,'filterByCategory')));
  2060. }
  2061. }
  2062. private function filterByCategory($value)
  2063. {
  2064. foreach($this->_categories as $category)
  2065. {
  2066. $cat=strtolower($value[2]);
  2067. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2068. return true;
  2069. }
  2070. return false;
  2071. }
  2072. private function filterTimingByCategory($value)
  2073. {
  2074. foreach($this->_categories as $category)
  2075. {
  2076. $cat=strtolower($value[1]);
  2077. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2078. return true;
  2079. }
  2080. return false;
  2081. }
  2082. private function filterByLevel($value)
  2083. {
  2084. return in_array(strtolower($value[1]),$this->_levels);
  2085. }
  2086. public function getExecutionTime()
  2087. {
  2088. return microtime(true)-YII_BEGIN_TIME;
  2089. }
  2090. public function getMemoryUsage()
  2091. {
  2092. if(function_exists('memory_get_usage'))
  2093. return memory_get_usage();
  2094. else
  2095. {
  2096. $output=array();
  2097. if(strncmp(PHP_OS,'WIN',3)===0)
  2098. {
  2099. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2100. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2101. }
  2102. else
  2103. {
  2104. $pid=getmypid();
  2105. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2106. $output=explode(" ",$output[0]);
  2107. return isset($output[1]) ? $output[1]*1024 : 0;
  2108. }
  2109. }
  2110. }
  2111. public function getProfilingResults($token=null,$categories=null,$refresh=false)
  2112. {
  2113. if($this->_timings===null || $refresh)
  2114. $this->calculateTimings();
  2115. if($token===null && $categories===null)
  2116. return $this->_timings;
  2117. $timings = $this->_timings;
  2118. if($categories!==null) {
  2119. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2120. $timings=array_filter($timings,array($this,'filterTimingByCategory'));
  2121. }
  2122. $results=array();
  2123. foreach($timings as $timing)
  2124. {
  2125. if($token===null || $timing[0]===$token)
  2126. $results[]=$timing[2];
  2127. }
  2128. return $results;
  2129. }
  2130. private function calculateTimings()
  2131. {
  2132. $this->_timings=array();
  2133. $stack=array();
  2134. foreach($this->_logs as $log)
  2135. {
  2136. if($log[1]!==CLogger::LEVEL_PROFILE)
  2137. continue;
  2138. list($message,$level,$category,$timestamp)=$log;
  2139. if(!strncasecmp($message,'begin:',6))
  2140. {
  2141. $log[0]=substr($message,6);
  2142. $stack[]=$log;
  2143. }
  2144. else if(!strncasecmp($message,'end:',4))
  2145. {
  2146. $token=substr($message,4);
  2147. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2148. {
  2149. $delta=$log[3]-$last[3];
  2150. $this->_timings[]=array($message,$category,$delta);
  2151. }
  2152. else
  2153. 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.',
  2154. array('{token}'=>$token)));
  2155. }
  2156. }
  2157. $now=microtime(true);
  2158. while(($last=array_pop($stack))!==null)
  2159. {
  2160. $delta=$now-$last[3];
  2161. $this->_timings[]=array($last[0],$last[2],$delta);
  2162. }
  2163. }
  2164. public function flush($dumpLogs=false)
  2165. {
  2166. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2167. $this->_logs=array();
  2168. $this->_logCount=0;
  2169. }
  2170. public function onFlush($event)
  2171. {
  2172. $this->raiseEvent('onFlush', $event);
  2173. }
  2174. }
  2175. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2176. {
  2177. public $behaviors=array();
  2178. private $_initialized=false;
  2179. public function init()
  2180. {
  2181. $this->attachBehaviors($this->behaviors);
  2182. $this->_initialized=true;
  2183. }
  2184. public function getIsInitialized()
  2185. {
  2186. return $this->_initialized;
  2187. }
  2188. }
  2189. class CHttpRequest extends CApplicationComponent
  2190. {
  2191. public $enableCookieValidation=false;
  2192. public $enableCsrfValidation=false;
  2193. public $csrfTokenName='YII_CSRF_TOKEN';
  2194. public $csrfCookie;
  2195. private $_requestUri;
  2196. private $_pathInfo;
  2197. private $_scriptFile;
  2198. private $_scriptUrl;
  2199. private $_hostInfo;
  2200. private $_baseUrl;
  2201. private $_cookies;
  2202. private $_preferredLanguage;
  2203. private $_csrfToken;
  2204. private $_deleteParams;
  2205. private $_putParams;
  2206. public function init()
  2207. {
  2208. parent::init();
  2209. $this->normalizeRequest();
  2210. }
  2211. protected function normalizeRequest()
  2212. {
  2213. // normalize request
  2214. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2215. {
  2216. if(isset($_GET))
  2217. $_GET=$this->stripSlashes($_GET);
  2218. if(isset($_POST))
  2219. $_POST=$this->stripSlashes($_POST);
  2220. if(isset($_REQUEST))
  2221. $_REQUEST=$this->stripSlashes($_REQUEST);
  2222. if(isset($_COOKIE))
  2223. $_COOKIE=$this->stripSlashes($_COOKIE);
  2224. }
  2225. if($this->enableCsrfValidation)
  2226. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2227. }
  2228. public function stripSlashes(&$data)
  2229. {
  2230. return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
  2231. }
  2232. public function getParam($name,$defaultValue=null)
  2233. {
  2234. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2235. }
  2236. public function getQuery($name,$defaultValue=null)
  2237. {
  2238. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2239. }
  2240. public function getPost($name,$defaultValue=null)
  2241. {
  2242. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2243. }
  2244. public function getDelete($name,$defaultValue=null)
  2245. {
  2246. if($this->getIsDeleteViaPostRequest())
  2247. return $this->getPost($name, $defaultValue);
  2248. if($this->_deleteParams===null)
  2249. $this->_deleteParams=$this->getIsDeleteRequest() ? $this->getRestParams() : array();
  2250. return isset($this->_deleteParams[$name]) ? $this->_deleteParams[$name] : $defaultValue;
  2251. }
  2252. public function getPut($name,$defaultValue=null)
  2253. {
  2254. if($this->getIsPutViaPostRequest())
  2255. return $this->getPost($name, $defaultValue);
  2256. if($this->_putParams===null)
  2257. $this->_putParams=$this->getIsPutRequest() ? $this->getRestParams() : array();
  2258. return isset($this->_putParams[$name]) ? $this->_putParams[$name] : $defaultValue;
  2259. }
  2260. protected function getRestParams()
  2261. {
  2262. $result=array();
  2263. if(function_exists('mb_parse_str'))
  2264. mb_parse_str(file_get_contents('php://input'), $result);
  2265. else
  2266. parse_str(file_get_contents('php://input'), $result);
  2267. return $result;
  2268. }
  2269. public function getUrl()
  2270. {
  2271. return $this->getRequestUri();
  2272. }
  2273. public function getHostInfo($schema='')
  2274. {
  2275. if($this->_hostInfo===null)
  2276. {
  2277. if($secure=$this->getIsSecureConnection())
  2278. $http='https';
  2279. else
  2280. $http='http';
  2281. if(isset($_SERVER['HTTP_HOST']))
  2282. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2283. else
  2284. {
  2285. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2286. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2287. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2288. $this->_hostInfo.=':'.$port;
  2289. }
  2290. }
  2291. if($schema!=='')
  2292. {
  2293. $secure=$this->getIsSecureConnection();
  2294. if($secure && $schema==='https' || !$secure && $schema==='http')
  2295. return $this->_hostInfo;
  2296. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2297. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2298. $port=':'.$port;
  2299. else
  2300. $port='';
  2301. $pos=strpos($this->_hostInfo,':');
  2302. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2303. }
  2304. else
  2305. return $this->_hostInfo;
  2306. }
  2307. public function setHostInfo($value)
  2308. {
  2309. $this->_hostInfo=rtrim($value,'/');
  2310. }
  2311. public function getBaseUrl($absolute=false)
  2312. {
  2313. if($this->_baseUrl===null)
  2314. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2315. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2316. }
  2317. public function setBaseUrl($value)
  2318. {
  2319. $this->_baseUrl=$value;
  2320. }
  2321. public function getScriptUrl()
  2322. {
  2323. if($this->_scriptUrl===null)
  2324. {
  2325. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2326. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2327. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2328. else if(basename($_SERVER['PHP_SELF'])===$scriptName)
  2329. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2330. else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2331. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2332. else if(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2333. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2334. else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2335. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2336. else
  2337. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2338. }
  2339. return $this->_scriptUrl;
  2340. }
  2341. public function setScriptUrl($value)
  2342. {
  2343. $this->_scriptUrl='/'.trim($value,'/');
  2344. }
  2345. public function getPathInfo()
  2346. {
  2347. if($this->_pathInfo===null)
  2348. {
  2349. $pathInfo=$this->getRequestUri();
  2350. if(($pos=strpos($pathInfo,'?'))!==false)
  2351. $pathInfo=substr($pathInfo,0,$pos);
  2352. $pathInfo=$this->decodePathInfo($pathInfo);
  2353. $scriptUrl=$this->getScriptUrl();
  2354. $baseUrl=$this->getBaseUrl();
  2355. if(strpos($pathInfo,$scriptUrl)===0)
  2356. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2357. else if($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2358. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2359. else if(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2360. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2361. else
  2362. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2363. $this->_pathInfo=trim($pathInfo,'/');
  2364. }
  2365. return $this->_pathInfo;
  2366. }
  2367. protected function decodePathInfo($pathInfo)
  2368. {
  2369. $pathInfo = urldecode($pathInfo);
  2370. // is it UTF-8?
  2371. // http://w3.org/International/questions/qa-forms-utf-8.html
  2372. if(preg_match('%^(?:
  2373. [\x09\x0A\x0D\x20-\x7E] # ASCII
  2374. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  2375. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  2376. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  2377. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  2378. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  2379. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  2380. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  2381. )*$%xs', $pathInfo))
  2382. {
  2383. return $pathInfo;
  2384. }
  2385. else
  2386. {
  2387. return utf8_encode($pathInfo);
  2388. }
  2389. }
  2390. public function getRequestUri()
  2391. {
  2392. if($this->_requestUri===null)
  2393. {
  2394. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2395. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2396. else if(isset($_SERVER['REQUEST_URI']))
  2397. {
  2398. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2399. if(!empty($_SERVER['HTTP_HOST']))
  2400. {
  2401. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2402. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2403. }
  2404. else
  2405. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2406. }
  2407. else if(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2408. {
  2409. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2410. if(!empty($_SERVER['QUERY_STRING']))
  2411. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2412. }
  2413. else
  2414. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2415. }
  2416. return $this->_requestUri;
  2417. }
  2418. public function getQueryString()
  2419. {
  2420. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2421. }
  2422. public function getIsSecureConnection()
  2423. {
  2424. return !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'],'off');
  2425. }
  2426. public function getRequestType()
  2427. {
  2428. if(isset($_POST['_method']))
  2429. return strtoupper($_POST['_method']);
  2430. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2431. }
  2432. public function getIsPostRequest()
  2433. {
  2434. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2435. }
  2436. public function getIsDeleteRequest()
  2437. {
  2438. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE')) || $this->getIsDeleteViaPostRequest();
  2439. }
  2440. protected function getIsDeleteViaPostRequest()
  2441. {
  2442. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'DELETE');
  2443. }
  2444. public function getIsPutRequest()
  2445. {
  2446. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT')) || $this->getIsPutViaPostRequest();
  2447. }
  2448. protected function getIsPutViaPostRequest()
  2449. {
  2450. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PUT');
  2451. }
  2452. public function getIsAjaxRequest()
  2453. {
  2454. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2455. }
  2456. public function getIsFlashRequest()
  2457. {
  2458. return isset($_SERVER['HTTP_USER_AGENT']) && (stripos($_SERVER['HTTP_USER_AGENT'],'Shockwave')!==false || stripos($_SERVER['HTTP_USER_AGENT'],'Flash')!==false);
  2459. }
  2460. public function getServerName()
  2461. {
  2462. return $_SERVER['SERVER_NAME'];
  2463. }
  2464. public function getServerPort()
  2465. {
  2466. return $_SERVER['SERVER_PORT'];
  2467. }
  2468. public function getUrlReferrer()
  2469. {
  2470. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2471. }
  2472. public function getUserAgent()
  2473. {
  2474. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2475. }
  2476. public function getUserHostAddress()
  2477. {
  2478. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2479. }
  2480. public function getUserHost()
  2481. {
  2482. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2483. }
  2484. public function getScriptFile()
  2485. {
  2486. if($this->_scriptFile!==null)
  2487. return $this->_scriptFile;
  2488. else
  2489. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2490. }
  2491. public function getBrowser($userAgent=null)
  2492. {
  2493. return get_browser($userAgent,true);
  2494. }
  2495. public function getAcceptTypes()
  2496. {
  2497. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2498. }
  2499. private $_port;
  2500. public function getPort()
  2501. {
  2502. if($this->_port===null)
  2503. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2504. return $this->_port;
  2505. }
  2506. public function setPort($value)
  2507. {
  2508. $this->_port=(int)$value;
  2509. $this->_hostInfo=null;
  2510. }
  2511. private $_securePort;
  2512. public function getSecurePort()
  2513. {
  2514. if($this->_securePort===null)
  2515. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2516. return $this->_securePort;
  2517. }
  2518. public function setSecurePort($value)
  2519. {
  2520. $this->_securePort=(int)$value;
  2521. $this->_hostInfo=null;
  2522. }
  2523. public function getCookies()
  2524. {
  2525. if($this->_cookies!==null)
  2526. return $this->_cookies;
  2527. else
  2528. return $this->_cookies=new CCookieCollection($this);
  2529. }
  2530. public function redirect($url,$terminate=true,$statusCode=302)
  2531. {
  2532. if(strpos($url,'/')===0)
  2533. $url=$this->getHostInfo().$url;
  2534. header('Location: '.$url, true, $statusCode);
  2535. if($terminate)
  2536. Yii::app()->end();
  2537. }
  2538. public function getPreferredLanguage()
  2539. {
  2540. if($this->_preferredLanguage===null)
  2541. {
  2542. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && ($n=preg_match_all('/([\w\-_]+)\s*(;\s*q\s*=\s*(\d*\.\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))>0)
  2543. {
  2544. $languages=array();
  2545. for($i=0;$i<$n;++$i)
  2546. $languages[$matches[1][$i]]=empty($matches[3][$i]) ? 1.0 : floatval($matches[3][$i]);
  2547. arsort($languages);
  2548. foreach($languages as $language=>$pref)
  2549. return $this->_preferredLanguage=CLocale::getCanonicalID($language);
  2550. }
  2551. return $this->_preferredLanguage=false;
  2552. }
  2553. return $this->_preferredLanguage;
  2554. }
  2555. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2556. {
  2557. if($mimeType===null)
  2558. {
  2559. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2560. $mimeType='text/plain';
  2561. }
  2562. header('Pragma: public');
  2563. header('Expires: 0');
  2564. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2565. header("Content-type: $mimeType");
  2566. if(ob_get_length()===false)
  2567. header('Content-Length: '.(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content)));
  2568. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2569. header('Content-Transfer-Encoding: binary');
  2570. if($terminate)
  2571. {
  2572. // clean up the application first because the file downloading could take long time
  2573. // which may cause timeout of some resources (such as DB connection)
  2574. Yii::app()->end(0,false);
  2575. echo $content;
  2576. exit(0);
  2577. }
  2578. else
  2579. echo $content;
  2580. }
  2581. public function xSendFile($filePath, $options=array())
  2582. {
  2583. if(!isset($options['forceDownload']) || $options['forceDownload'])
  2584. $disposition='attachment';
  2585. else
  2586. $disposition='inline';
  2587. if(!isset($options['saveName']))
  2588. $options['saveName']=basename($filePath);
  2589. if(!isset($options['mimeType']))
  2590. {
  2591. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2592. $options['mimeType']='text/plain';
  2593. }
  2594. if(!isset($options['xHeader']))
  2595. $options['xHeader']='X-Sendfile';
  2596. if($options['mimeType'] !== null)
  2597. header('Content-type: '.$options['mimeType']);
  2598. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  2599. if(isset($options['addHeaders']))
  2600. {
  2601. foreach($options['addHeaders'] as $header=>$value)
  2602. header($header.': '.$value);
  2603. }
  2604. header(trim($options['xHeader']).': '.$filePath);
  2605. if(!isset($options['terminate']) || $options['terminate'])
  2606. Yii::app()->end();
  2607. }
  2608. public function getCsrfToken()
  2609. {
  2610. if($this->_csrfToken===null)
  2611. {
  2612. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2613. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2614. {
  2615. $cookie=$this->createCsrfCookie();
  2616. $this->_csrfToken=$cookie->value;
  2617. $this->getCookies()->add($cookie->name,$cookie);
  2618. }
  2619. }
  2620. return $this->_csrfToken;
  2621. }
  2622. protected function createCsrfCookie()
  2623. {
  2624. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2625. if(is_array($this->csrfCookie))
  2626. {
  2627. foreach($this->csrfCookie as $name=>$value)
  2628. $cookie->$name=$value;
  2629. }
  2630. return $cookie;
  2631. }
  2632. public function validateCsrfToken($event)
  2633. {
  2634. if($this->getIsPostRequest())
  2635. {
  2636. // only validate POST requests
  2637. $cookies=$this->getCookies();
  2638. if($cookies->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName]))
  2639. {
  2640. $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value;
  2641. $tokenFromPost=$_POST[$this->csrfTokenName];
  2642. $valid=$tokenFromCookie===$tokenFromPost;
  2643. }
  2644. else
  2645. $valid=false;
  2646. if(!$valid)
  2647. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2648. }
  2649. }
  2650. }
  2651. class CCookieCollection extends CMap
  2652. {
  2653. private $_request;
  2654. private $_initialized=false;
  2655. public function __construct(CHttpRequest $request)
  2656. {
  2657. $this->_request=$request;
  2658. $this->copyfrom($this->getCookies());
  2659. $this->_initialized=true;
  2660. }
  2661. public function getRequest()
  2662. {
  2663. return $this->_request;
  2664. }
  2665. protected function getCookies()
  2666. {
  2667. $cookies=array();
  2668. if($this->_request->enableCookieValidation)
  2669. {
  2670. $sm=Yii::app()->getSecurityManager();
  2671. foreach($_COOKIE as $name=>$value)
  2672. {
  2673. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  2674. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  2675. }
  2676. }
  2677. else
  2678. {
  2679. foreach($_COOKIE as $name=>$value)
  2680. $cookies[$name]=new CHttpCookie($name,$value);
  2681. }
  2682. return $cookies;
  2683. }
  2684. public function add($name,$cookie=null)
  2685. {
  2686. if($name instanceof CHttpCookie)
  2687. {
  2688. $cookieName=$name->name;
  2689. $cookieObject=$name;
  2690. }
  2691. else
  2692. {
  2693. $cookieName=(string)$name;
  2694. $cookieObject=$cookie;
  2695. }
  2696. if($cookieObject instanceof CHttpCookie)
  2697. {
  2698. $this->remove($cookieName);
  2699. parent::add($cookieName,$cookieObject);
  2700. if($this->_initialized)
  2701. $this->addCookie($cookieObject);
  2702. }
  2703. else
  2704. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  2705. }
  2706. public function remove($name,$options=array())
  2707. {
  2708. if(($cookie=parent::remove($name))!==null)
  2709. {
  2710. if($this->_initialized)
  2711. {
  2712. $cookie->configure($options);
  2713. $this->removeCookie($cookie);
  2714. }
  2715. }
  2716. return $cookie;
  2717. }
  2718. protected function addCookie($cookie)
  2719. {
  2720. $value=$cookie->value;
  2721. if($this->_request->enableCookieValidation)
  2722. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  2723. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2724. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2725. else
  2726. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  2727. }
  2728. protected function removeCookie($cookie)
  2729. {
  2730. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2731. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2732. else
  2733. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure);
  2734. }
  2735. }
  2736. class CUrlManager extends CApplicationComponent
  2737. {
  2738. const CACHE_KEY='Yii.CUrlManager.rules';
  2739. const GET_FORMAT='get';
  2740. const PATH_FORMAT='path';
  2741. public $rules=array();
  2742. public $urlSuffix='';
  2743. public $showScriptName=true;
  2744. public $appendParams=true;
  2745. public $routeVar='r';
  2746. public $caseSensitive=true;
  2747. public $matchValue=false;
  2748. public $cacheID='cache';
  2749. public $useStrictParsing=false;
  2750. public $urlRuleClass='CUrlRule';
  2751. private $_urlFormat=self::GET_FORMAT;
  2752. private $_rules=array();
  2753. private $_baseUrl;
  2754. public function init()
  2755. {
  2756. parent::init();
  2757. $this->processRules();
  2758. }
  2759. protected function processRules()
  2760. {
  2761. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  2762. return;
  2763. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  2764. {
  2765. $hash=md5(serialize($this->rules));
  2766. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  2767. {
  2768. $this->_rules=$data[0];
  2769. return;
  2770. }
  2771. }
  2772. foreach($this->rules as $pattern=>$route)
  2773. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2774. if(isset($cache))
  2775. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  2776. }
  2777. public function addRules($rules, $append=true)
  2778. {
  2779. if ($append)
  2780. {
  2781. foreach($rules as $pattern=>$route)
  2782. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2783. }
  2784. else
  2785. {
  2786. foreach($rules as $pattern=>$route)
  2787. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  2788. }
  2789. }
  2790. protected function createUrlRule($route,$pattern)
  2791. {
  2792. if(is_array($route) && isset($route['class']))
  2793. return $route;
  2794. else
  2795. return new $this->urlRuleClass($route,$pattern);
  2796. }
  2797. public function createUrl($route,$params=array(),$ampersand='&')
  2798. {
  2799. unset($params[$this->routeVar]);
  2800. foreach($params as $i=>$param)
  2801. if($param===null)
  2802. $params[$i]='';
  2803. if(isset($params['#']))
  2804. {
  2805. $anchor='#'.$params['#'];
  2806. unset($params['#']);
  2807. }
  2808. else
  2809. $anchor='';
  2810. $route=trim($route,'/');
  2811. foreach($this->_rules as $i=>$rule)
  2812. {
  2813. if(is_array($rule))
  2814. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2815. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  2816. {
  2817. if($rule->hasHostInfo)
  2818. return $url==='' ? '/'.$anchor : $url.$anchor;
  2819. else
  2820. return $this->getBaseUrl().'/'.$url.$anchor;
  2821. }
  2822. }
  2823. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  2824. }
  2825. protected function createUrlDefault($route,$params,$ampersand)
  2826. {
  2827. if($this->getUrlFormat()===self::PATH_FORMAT)
  2828. {
  2829. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  2830. if($this->appendParams)
  2831. {
  2832. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  2833. return $route==='' ? $url : $url.$this->urlSuffix;
  2834. }
  2835. else
  2836. {
  2837. if($route!=='')
  2838. $url.=$this->urlSuffix;
  2839. $query=$this->createPathInfo($params,'=',$ampersand);
  2840. return $query==='' ? $url : $url.'?'.$query;
  2841. }
  2842. }
  2843. else
  2844. {
  2845. $url=$this->getBaseUrl();
  2846. if(!$this->showScriptName)
  2847. $url.='/';
  2848. if($route!=='')
  2849. {
  2850. $url.='?'.$this->routeVar.'='.$route;
  2851. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2852. $url.=$ampersand.$query;
  2853. }
  2854. else if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2855. $url.='?'.$query;
  2856. return $url;
  2857. }
  2858. }
  2859. public function parseUrl($request)
  2860. {
  2861. if($this->getUrlFormat()===self::PATH_FORMAT)
  2862. {
  2863. $rawPathInfo=$request->getPathInfo();
  2864. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  2865. foreach($this->_rules as $i=>$rule)
  2866. {
  2867. if(is_array($rule))
  2868. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2869. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  2870. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  2871. }
  2872. if($this->useStrictParsing)
  2873. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  2874. array('{route}'=>$pathInfo)));
  2875. else
  2876. return $pathInfo;
  2877. }
  2878. else if(isset($_GET[$this->routeVar]))
  2879. return $_GET[$this->routeVar];
  2880. else if(isset($_POST[$this->routeVar]))
  2881. return $_POST[$this->routeVar];
  2882. else
  2883. return '';
  2884. }
  2885. public function parsePathInfo($pathInfo)
  2886. {
  2887. if($pathInfo==='')
  2888. return;
  2889. $segs=explode('/',$pathInfo.'/');
  2890. $n=count($segs);
  2891. for($i=0;$i<$n-1;$i+=2)
  2892. {
  2893. $key=$segs[$i];
  2894. if($key==='') continue;
  2895. $value=$segs[$i+1];
  2896. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  2897. {
  2898. $name=substr($key,0,$pos);
  2899. for($j=$m-1;$j>=0;--$j)
  2900. {
  2901. if($matches[1][$j]==='')
  2902. $value=array($value);
  2903. else
  2904. $value=array($matches[1][$j]=>$value);
  2905. }
  2906. if(isset($_GET[$name]) && is_array($_GET[$name]))
  2907. $value=CMap::mergeArray($_GET[$name],$value);
  2908. $_REQUEST[$name]=$_GET[$name]=$value;
  2909. }
  2910. else
  2911. $_REQUEST[$key]=$_GET[$key]=$value;
  2912. }
  2913. }
  2914. public function createPathInfo($params,$equal,$ampersand, $key=null)
  2915. {
  2916. $pairs = array();
  2917. foreach($params as $k => $v)
  2918. {
  2919. if ($key!==null)
  2920. $k = $key.'['.$k.']';
  2921. if (is_array($v))
  2922. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  2923. else
  2924. $pairs[]=urlencode($k).$equal.urlencode($v);
  2925. }
  2926. return implode($ampersand,$pairs);
  2927. }
  2928. public function removeUrlSuffix($pathInfo,$urlSuffix)
  2929. {
  2930. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  2931. return substr($pathInfo,0,-strlen($urlSuffix));
  2932. else
  2933. return $pathInfo;
  2934. }
  2935. public function getBaseUrl()
  2936. {
  2937. if($this->_baseUrl!==null)
  2938. return $this->_baseUrl;
  2939. else
  2940. {
  2941. if($this->showScriptName)
  2942. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  2943. else
  2944. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  2945. return $this->_baseUrl;
  2946. }
  2947. }
  2948. public function setBaseUrl($value)
  2949. {
  2950. $this->_baseUrl=$value;
  2951. }
  2952. public function getUrlFormat()
  2953. {
  2954. return $this->_urlFormat;
  2955. }
  2956. public function setUrlFormat($value)
  2957. {
  2958. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  2959. $this->_urlFormat=$value;
  2960. else
  2961. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  2962. }
  2963. }
  2964. abstract class CBaseUrlRule extends CComponent
  2965. {
  2966. public $hasHostInfo=false;
  2967. abstract public function createUrl($manager,$route,$params,$ampersand);
  2968. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  2969. }
  2970. class CUrlRule extends CBaseUrlRule
  2971. {
  2972. public $urlSuffix;
  2973. public $caseSensitive;
  2974. public $defaultParams=array();
  2975. public $matchValue;
  2976. public $verb;
  2977. public $parsingOnly=false;
  2978. public $route;
  2979. public $references=array();
  2980. public $routePattern;
  2981. public $pattern;
  2982. public $template;
  2983. public $params=array();
  2984. public $append;
  2985. public $hasHostInfo;
  2986. public function __construct($route,$pattern)
  2987. {
  2988. if(is_array($route))
  2989. {
  2990. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  2991. {
  2992. if(isset($route[$name]))
  2993. $this->$name=$route[$name];
  2994. }
  2995. if(isset($route['pattern']))
  2996. $pattern=$route['pattern'];
  2997. $route=$route[0];
  2998. }
  2999. $this->route=trim($route,'/');
  3000. $tr2['/']=$tr['/']='\\/';
  3001. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  3002. {
  3003. foreach($matches2[1] as $name)
  3004. $this->references[$name]="<$name>";
  3005. }
  3006. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  3007. if($this->verb!==null)
  3008. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  3009. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  3010. {
  3011. $tokens=array_combine($matches[1],$matches[2]);
  3012. foreach($tokens as $name=>$value)
  3013. {
  3014. if($value==='')
  3015. $value='[^\/]+';
  3016. $tr["<$name>"]="(?P<$name>$value)";
  3017. if(isset($this->references[$name]))
  3018. $tr2["<$name>"]=$tr["<$name>"];
  3019. else
  3020. $this->params[$name]=$value;
  3021. }
  3022. }
  3023. $p=rtrim($pattern,'*');
  3024. $this->append=$p!==$pattern;
  3025. $p=trim($p,'/');
  3026. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  3027. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  3028. if($this->append)
  3029. $this->pattern.='/u';
  3030. else
  3031. $this->pattern.='$/u';
  3032. if($this->references!==array())
  3033. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  3034. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  3035. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  3036. array('{route}'=>$route,'{pattern}'=>$pattern)));
  3037. }
  3038. public function createUrl($manager,$route,$params,$ampersand)
  3039. {
  3040. if($this->parsingOnly)
  3041. return false;
  3042. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3043. $case='';
  3044. else
  3045. $case='i';
  3046. $tr=array();
  3047. if($route!==$this->route)
  3048. {
  3049. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  3050. {
  3051. foreach($this->references as $key=>$name)
  3052. $tr[$name]=$matches[$key];
  3053. }
  3054. else
  3055. return false;
  3056. }
  3057. foreach($this->defaultParams as $key=>$value)
  3058. {
  3059. if(isset($params[$key]))
  3060. {
  3061. if($params[$key]==$value)
  3062. unset($params[$key]);
  3063. else
  3064. return false;
  3065. }
  3066. }
  3067. foreach($this->params as $key=>$value)
  3068. if(!isset($params[$key]))
  3069. return false;
  3070. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  3071. {
  3072. foreach($this->params as $key=>$value)
  3073. {
  3074. if(!preg_match('/\A'.$value.'\z/u'.$case,$params[$key]))
  3075. return false;
  3076. }
  3077. }
  3078. foreach($this->params as $key=>$value)
  3079. {
  3080. $tr["<$key>"]=urlencode($params[$key]);
  3081. unset($params[$key]);
  3082. }
  3083. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3084. $url=strtr($this->template,$tr);
  3085. if($this->hasHostInfo)
  3086. {
  3087. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  3088. if(stripos($url,$hostInfo)===0)
  3089. $url=substr($url,strlen($hostInfo));
  3090. }
  3091. if(empty($params))
  3092. return $url!=='' ? $url.$suffix : $url;
  3093. if($this->append)
  3094. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  3095. else
  3096. {
  3097. if($url!=='')
  3098. $url.=$suffix;
  3099. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  3100. }
  3101. return $url;
  3102. }
  3103. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  3104. {
  3105. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  3106. return false;
  3107. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3108. $case='';
  3109. else
  3110. $case='i';
  3111. if($this->urlSuffix!==null)
  3112. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3113. // URL suffix required, but not found in the requested URL
  3114. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3115. {
  3116. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3117. if($urlSuffix!='' && $urlSuffix!=='/')
  3118. return false;
  3119. }
  3120. if($this->hasHostInfo)
  3121. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3122. $pathInfo.='/';
  3123. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3124. {
  3125. foreach($this->defaultParams as $name=>$value)
  3126. {
  3127. if(!isset($_GET[$name]))
  3128. $_REQUEST[$name]=$_GET[$name]=$value;
  3129. }
  3130. $tr=array();
  3131. foreach($matches as $key=>$value)
  3132. {
  3133. if(isset($this->references[$key]))
  3134. $tr[$this->references[$key]]=$value;
  3135. else if(isset($this->params[$key]))
  3136. $_REQUEST[$key]=$_GET[$key]=$value;
  3137. }
  3138. if($pathInfo!==$matches[0]) // there're additional GET params
  3139. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3140. if($this->routePattern!==null)
  3141. return strtr($this->route,$tr);
  3142. else
  3143. return $this->route;
  3144. }
  3145. else
  3146. return false;
  3147. }
  3148. }
  3149. abstract class CBaseController extends CComponent
  3150. {
  3151. private $_widgetStack=array();
  3152. abstract public function getViewFile($viewName);
  3153. public function renderFile($viewFile,$data=null,$return=false)
  3154. {
  3155. $widgetCount=count($this->_widgetStack);
  3156. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3157. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3158. else
  3159. $content=$this->renderInternal($viewFile,$data,$return);
  3160. if(count($this->_widgetStack)===$widgetCount)
  3161. return $content;
  3162. else
  3163. {
  3164. $widget=end($this->_widgetStack);
  3165. 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.',
  3166. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3167. }
  3168. }
  3169. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3170. {
  3171. // we use special variable names here to avoid conflict when extracting data
  3172. if(is_array($_data_))
  3173. extract($_data_,EXTR_PREFIX_SAME,'data');
  3174. else
  3175. $data=$_data_;
  3176. if($_return_)
  3177. {
  3178. ob_start();
  3179. ob_implicit_flush(false);
  3180. require($_viewFile_);
  3181. return ob_get_clean();
  3182. }
  3183. else
  3184. require($_viewFile_);
  3185. }
  3186. public function createWidget($className,$properties=array())
  3187. {
  3188. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3189. $widget->init();
  3190. return $widget;
  3191. }
  3192. public function widget($className,$properties=array(),$captureOutput=false)
  3193. {
  3194. if($captureOutput)
  3195. {
  3196. ob_start();
  3197. ob_implicit_flush(false);
  3198. $widget=$this->createWidget($className,$properties);
  3199. $widget->run();
  3200. return ob_get_clean();
  3201. }
  3202. else
  3203. {
  3204. $widget=$this->createWidget($className,$properties);
  3205. $widget->run();
  3206. return $widget;
  3207. }
  3208. }
  3209. public function beginWidget($className,$properties=array())
  3210. {
  3211. $widget=$this->createWidget($className,$properties);
  3212. $this->_widgetStack[]=$widget;
  3213. return $widget;
  3214. }
  3215. public function endWidget($id='')
  3216. {
  3217. if(($widget=array_pop($this->_widgetStack))!==null)
  3218. {
  3219. $widget->run();
  3220. return $widget;
  3221. }
  3222. else
  3223. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3224. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3225. }
  3226. public function beginClip($id,$properties=array())
  3227. {
  3228. $properties['id']=$id;
  3229. $this->beginWidget('CClipWidget',$properties);
  3230. }
  3231. public function endClip()
  3232. {
  3233. $this->endWidget('CClipWidget');
  3234. }
  3235. public function beginCache($id,$properties=array())
  3236. {
  3237. $properties['id']=$id;
  3238. $cache=$this->beginWidget('COutputCache',$properties);
  3239. if($cache->getIsContentCached())
  3240. {
  3241. $this->endCache();
  3242. return false;
  3243. }
  3244. else
  3245. return true;
  3246. }
  3247. public function endCache()
  3248. {
  3249. $this->endWidget('COutputCache');
  3250. }
  3251. public function beginContent($view=null,$data=array())
  3252. {
  3253. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3254. }
  3255. public function endContent()
  3256. {
  3257. $this->endWidget('CContentDecorator');
  3258. }
  3259. }
  3260. class CController extends CBaseController
  3261. {
  3262. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3263. public $layout;
  3264. public $defaultAction='index';
  3265. private $_id;
  3266. private $_action;
  3267. private $_pageTitle;
  3268. private $_cachingStack;
  3269. private $_clips;
  3270. private $_dynamicOutput;
  3271. private $_pageStates;
  3272. private $_module;
  3273. public function __construct($id,$module=null)
  3274. {
  3275. $this->_id=$id;
  3276. $this->_module=$module;
  3277. $this->attachBehaviors($this->behaviors());
  3278. }
  3279. public function init()
  3280. {
  3281. }
  3282. public function filters()
  3283. {
  3284. return array();
  3285. }
  3286. public function actions()
  3287. {
  3288. return array();
  3289. }
  3290. public function behaviors()
  3291. {
  3292. return array();
  3293. }
  3294. public function accessRules()
  3295. {
  3296. return array();
  3297. }
  3298. public function run($actionID)
  3299. {
  3300. if(($action=$this->createAction($actionID))!==null)
  3301. {
  3302. if(($parent=$this->getModule())===null)
  3303. $parent=Yii::app();
  3304. if($parent->beforeControllerAction($this,$action))
  3305. {
  3306. $this->runActionWithFilters($action,$this->filters());
  3307. $parent->afterControllerAction($this,$action);
  3308. }
  3309. }
  3310. else
  3311. $this->missingAction($actionID);
  3312. }
  3313. public function runActionWithFilters($action,$filters)
  3314. {
  3315. if(empty($filters))
  3316. $this->runAction($action);
  3317. else
  3318. {
  3319. $priorAction=$this->_action;
  3320. $this->_action=$action;
  3321. CFilterChain::create($this,$action,$filters)->run();
  3322. $this->_action=$priorAction;
  3323. }
  3324. }
  3325. public function runAction($action)
  3326. {
  3327. $priorAction=$this->_action;
  3328. $this->_action=$action;
  3329. if($this->beforeAction($action))
  3330. {
  3331. if($action->runWithParams($this->getActionParams())===false)
  3332. $this->invalidActionParams($action);
  3333. else
  3334. $this->afterAction($action);
  3335. }
  3336. $this->_action=$priorAction;
  3337. }
  3338. public function getActionParams()
  3339. {
  3340. return $_GET;
  3341. }
  3342. public function invalidActionParams($action)
  3343. {
  3344. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3345. }
  3346. public function processOutput($output)
  3347. {
  3348. Yii::app()->getClientScript()->render($output);
  3349. // if using page caching, we should delay dynamic output replacement
  3350. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3351. {
  3352. $output=$this->processDynamicOutput($output);
  3353. $this->_dynamicOutput=null;
  3354. }
  3355. if($this->_pageStates===null)
  3356. $this->_pageStates=$this->loadPageStates();
  3357. if(!empty($this->_pageStates))
  3358. $this->savePageStates($this->_pageStates,$output);
  3359. return $output;
  3360. }
  3361. public function processDynamicOutput($output)
  3362. {
  3363. if($this->_dynamicOutput)
  3364. {
  3365. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3366. }
  3367. return $output;
  3368. }
  3369. protected function replaceDynamicOutput($matches)
  3370. {
  3371. $content=$matches[0];
  3372. if(isset($this->_dynamicOutput[$matches[1]]))
  3373. {
  3374. $content=$this->_dynamicOutput[$matches[1]];
  3375. $this->_dynamicOutput[$matches[1]]=null;
  3376. }
  3377. return $content;
  3378. }
  3379. public function createAction($actionID)
  3380. {
  3381. if($actionID==='')
  3382. $actionID=$this->defaultAction;
  3383. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3384. return new CInlineAction($this,$actionID);
  3385. else
  3386. {
  3387. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3388. if($action!==null && !method_exists($action,'run'))
  3389. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3390. return $action;
  3391. }
  3392. }
  3393. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3394. {
  3395. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3396. {
  3397. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3398. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3399. }
  3400. else if($pos===false)
  3401. return null;
  3402. // the action is defined in a provider
  3403. $prefix=substr($actionID,0,$pos+1);
  3404. if(!isset($actionMap[$prefix]))
  3405. return null;
  3406. $actionID=(string)substr($actionID,$pos+1);
  3407. $provider=$actionMap[$prefix];
  3408. if(is_string($provider))
  3409. $providerType=$provider;
  3410. else if(is_array($provider) && isset($provider['class']))
  3411. {
  3412. $providerType=$provider['class'];
  3413. if(isset($provider[$actionID]))
  3414. {
  3415. if(is_string($provider[$actionID]))
  3416. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3417. else
  3418. $config=array_merge($provider[$actionID],$config);
  3419. }
  3420. }
  3421. else
  3422. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3423. $class=Yii::import($providerType,true);
  3424. $map=call_user_func(array($class,'actions'));
  3425. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3426. }
  3427. public function missingAction($actionID)
  3428. {
  3429. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3430. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3431. }
  3432. public function getAction()
  3433. {
  3434. return $this->_action;
  3435. }
  3436. public function setAction($value)
  3437. {
  3438. $this->_action=$value;
  3439. }
  3440. public function getId()
  3441. {
  3442. return $this->_id;
  3443. }
  3444. public function getUniqueId()
  3445. {
  3446. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3447. }
  3448. public function getRoute()
  3449. {
  3450. if(($action=$this->getAction())!==null)
  3451. return $this->getUniqueId().'/'.$action->getId();
  3452. else
  3453. return $this->getUniqueId();
  3454. }
  3455. public function getModule()
  3456. {
  3457. return $this->_module;
  3458. }
  3459. public function getViewPath()
  3460. {
  3461. if(($module=$this->getModule())===null)
  3462. $module=Yii::app();
  3463. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3464. }
  3465. public function getViewFile($viewName)
  3466. {
  3467. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3468. return $viewFile;
  3469. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3470. if(($module=$this->getModule())!==null)
  3471. $moduleViewPath=$module->getViewPath();
  3472. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3473. }
  3474. public function getLayoutFile($layoutName)
  3475. {
  3476. if($layoutName===false)
  3477. return false;
  3478. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3479. return $layoutFile;
  3480. if(empty($layoutName))
  3481. {
  3482. $module=$this->getModule();
  3483. while($module!==null)
  3484. {
  3485. if($module->layout===false)
  3486. return false;
  3487. if(!empty($module->layout))
  3488. break;
  3489. $module=$module->getParentModule();
  3490. }
  3491. if($module===null)
  3492. $module=Yii::app();
  3493. $layoutName=$module->layout;
  3494. }
  3495. else if(($module=$this->getModule())===null)
  3496. $module=Yii::app();
  3497. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3498. }
  3499. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3500. {
  3501. if(empty($viewName))
  3502. return false;
  3503. if($moduleViewPath===null)
  3504. $moduleViewPath=$basePath;
  3505. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3506. $extension=$renderer->fileExtension;
  3507. else
  3508. $extension='.php';
  3509. if($viewName[0]==='/')
  3510. {
  3511. if(strncmp($viewName,'//',2)===0)
  3512. $viewFile=$basePath.$viewName;
  3513. else
  3514. $viewFile=$moduleViewPath.$viewName;
  3515. }
  3516. else if(strpos($viewName,'.'))
  3517. $viewFile=Yii::getPathOfAlias($viewName);
  3518. else
  3519. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3520. if(is_file($viewFile.$extension))
  3521. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3522. else if($extension!=='.php' && is_file($viewFile.'.php'))
  3523. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3524. else
  3525. return false;
  3526. }
  3527. public function getClips()
  3528. {
  3529. if($this->_clips!==null)
  3530. return $this->_clips;
  3531. else
  3532. return $this->_clips=new CMap;
  3533. }
  3534. public function forward($route,$exit=true)
  3535. {
  3536. if(strpos($route,'/')===false)
  3537. $this->run($route);
  3538. else
  3539. {
  3540. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3541. $route=$module->getId().'/'.$route;
  3542. Yii::app()->runController($route);
  3543. }
  3544. if($exit)
  3545. Yii::app()->end();
  3546. }
  3547. public function render($view,$data=null,$return=false)
  3548. {
  3549. if($this->beforeRender($view))
  3550. {
  3551. $output=$this->renderPartial($view,$data,true);
  3552. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3553. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3554. $this->afterRender($view,$output);
  3555. $output=$this->processOutput($output);
  3556. if($return)
  3557. return $output;
  3558. else
  3559. echo $output;
  3560. }
  3561. }
  3562. protected function beforeRender($view)
  3563. {
  3564. return true;
  3565. }
  3566. protected function afterRender($view, &$output)
  3567. {
  3568. }
  3569. public function renderText($text,$return=false)
  3570. {
  3571. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3572. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3573. $text=$this->processOutput($text);
  3574. if($return)
  3575. return $text;
  3576. else
  3577. echo $text;
  3578. }
  3579. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3580. {
  3581. if(($viewFile=$this->getViewFile($view))!==false)
  3582. {
  3583. $output=$this->renderFile($viewFile,$data,true);
  3584. if($processOutput)
  3585. $output=$this->processOutput($output);
  3586. if($return)
  3587. return $output;
  3588. else
  3589. echo $output;
  3590. }
  3591. else
  3592. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3593. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3594. }
  3595. public function renderClip($name,$params=array(),$return=false)
  3596. {
  3597. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  3598. if($return)
  3599. return $text;
  3600. else
  3601. echo $text;
  3602. }
  3603. public function renderDynamic($callback)
  3604. {
  3605. $n=count($this->_dynamicOutput);
  3606. echo "<###dynamic-$n###>";
  3607. $params=func_get_args();
  3608. array_shift($params);
  3609. $this->renderDynamicInternal($callback,$params);
  3610. }
  3611. public function renderDynamicInternal($callback,$params)
  3612. {
  3613. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3614. if(is_string($callback) && method_exists($this,$callback))
  3615. $callback=array($this,$callback);
  3616. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3617. }
  3618. public function createUrl($route,$params=array(),$ampersand='&')
  3619. {
  3620. if($route==='')
  3621. $route=$this->getId().'/'.$this->getAction()->getId();
  3622. else if(strpos($route,'/')===false)
  3623. $route=$this->getId().'/'.$route;
  3624. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3625. $route=$module->getId().'/'.$route;
  3626. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3627. }
  3628. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3629. {
  3630. $url=$this->createUrl($route,$params,$ampersand);
  3631. if(strpos($url,'http')===0)
  3632. return $url;
  3633. else
  3634. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  3635. }
  3636. public function getPageTitle()
  3637. {
  3638. if($this->_pageTitle!==null)
  3639. return $this->_pageTitle;
  3640. else
  3641. {
  3642. $name=ucfirst(basename($this->getId()));
  3643. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3644. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3645. else
  3646. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3647. }
  3648. }
  3649. public function setPageTitle($value)
  3650. {
  3651. $this->_pageTitle=$value;
  3652. }
  3653. public function redirect($url,$terminate=true,$statusCode=302)
  3654. {
  3655. if(is_array($url))
  3656. {
  3657. $route=isset($url[0]) ? $url[0] : '';
  3658. $url=$this->createUrl($route,array_splice($url,1));
  3659. }
  3660. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  3661. }
  3662. public function refresh($terminate=true,$anchor='')
  3663. {
  3664. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  3665. }
  3666. public function recordCachingAction($context,$method,$params)
  3667. {
  3668. if($this->_cachingStack) // record only when there is an active output cache
  3669. {
  3670. foreach($this->_cachingStack as $cache)
  3671. $cache->recordAction($context,$method,$params);
  3672. }
  3673. }
  3674. public function getCachingStack($createIfNull=true)
  3675. {
  3676. if(!$this->_cachingStack)
  3677. $this->_cachingStack=new CStack;
  3678. return $this->_cachingStack;
  3679. }
  3680. public function isCachingStackEmpty()
  3681. {
  3682. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  3683. }
  3684. protected function beforeAction($action)
  3685. {
  3686. return true;
  3687. }
  3688. protected function afterAction($action)
  3689. {
  3690. }
  3691. public function filterPostOnly($filterChain)
  3692. {
  3693. if(Yii::app()->getRequest()->getIsPostRequest())
  3694. $filterChain->run();
  3695. else
  3696. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3697. }
  3698. public function filterAjaxOnly($filterChain)
  3699. {
  3700. if(Yii::app()->getRequest()->getIsAjaxRequest())
  3701. $filterChain->run();
  3702. else
  3703. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3704. }
  3705. public function filterAccessControl($filterChain)
  3706. {
  3707. $filter=new CAccessControlFilter;
  3708. $filter->setRules($this->accessRules());
  3709. $filter->filter($filterChain);
  3710. }
  3711. public function getPageState($name,$defaultValue=null)
  3712. {
  3713. if($this->_pageStates===null)
  3714. $this->_pageStates=$this->loadPageStates();
  3715. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  3716. }
  3717. public function setPageState($name,$value,$defaultValue=null)
  3718. {
  3719. if($this->_pageStates===null)
  3720. $this->_pageStates=$this->loadPageStates();
  3721. if($value===$defaultValue)
  3722. unset($this->_pageStates[$name]);
  3723. else
  3724. $this->_pageStates[$name]=$value;
  3725. $params=func_get_args();
  3726. $this->recordCachingAction('','setPageState',$params);
  3727. }
  3728. public function clearPageStates()
  3729. {
  3730. $this->_pageStates=array();
  3731. }
  3732. protected function loadPageStates()
  3733. {
  3734. if(!empty($_POST[self::STATE_INPUT_NAME]))
  3735. {
  3736. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  3737. {
  3738. if(extension_loaded('zlib'))
  3739. $data=@gzuncompress($data);
  3740. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  3741. return unserialize($data);
  3742. }
  3743. }
  3744. return array();
  3745. }
  3746. protected function savePageStates($states,&$output)
  3747. {
  3748. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  3749. if(extension_loaded('zlib'))
  3750. $data=gzcompress($data);
  3751. $value=base64_encode($data);
  3752. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  3753. }
  3754. }
  3755. abstract class CAction extends CComponent implements IAction
  3756. {
  3757. private $_id;
  3758. private $_controller;
  3759. public function __construct($controller,$id)
  3760. {
  3761. $this->_controller=$controller;
  3762. $this->_id=$id;
  3763. }
  3764. public function getController()
  3765. {
  3766. return $this->_controller;
  3767. }
  3768. public function getId()
  3769. {
  3770. return $this->_id;
  3771. }
  3772. public function runWithParams($params)
  3773. {
  3774. $method=new ReflectionMethod($this, 'run');
  3775. if($method->getNumberOfParameters()>0)
  3776. return $this->runWithParamsInternal($this, $method, $params);
  3777. else
  3778. return $this->run();
  3779. }
  3780. protected function runWithParamsInternal($object, $method, $params)
  3781. {
  3782. $ps=array();
  3783. foreach($method->getParameters() as $i=>$param)
  3784. {
  3785. $name=$param->getName();
  3786. if(isset($params[$name]))
  3787. {
  3788. if($param->isArray())
  3789. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  3790. else if(!is_array($params[$name]))
  3791. $ps[]=$params[$name];
  3792. else
  3793. return false;
  3794. }
  3795. else if($param->isDefaultValueAvailable())
  3796. $ps[]=$param->getDefaultValue();
  3797. else
  3798. return false;
  3799. }
  3800. $method->invokeArgs($object,$ps);
  3801. return true;
  3802. }
  3803. }
  3804. class CInlineAction extends CAction
  3805. {
  3806. public function run()
  3807. {
  3808. $method='action'.$this->getId();
  3809. $this->getController()->$method();
  3810. }
  3811. public function runWithParams($params)
  3812. {
  3813. $methodName='action'.$this->getId();
  3814. $controller=$this->getController();
  3815. $method=new ReflectionMethod($controller, $methodName);
  3816. if($method->getNumberOfParameters()>0)
  3817. return $this->runWithParamsInternal($controller, $method, $params);
  3818. else
  3819. return $controller->$methodName();
  3820. }
  3821. }
  3822. class CWebUser extends CApplicationComponent implements IWebUser
  3823. {
  3824. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  3825. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  3826. const STATES_VAR='__states';
  3827. const AUTH_TIMEOUT_VAR='__timeout';
  3828. public $allowAutoLogin=false;
  3829. public $guestName='Guest';
  3830. public $loginUrl=array('/site/login');
  3831. public $identityCookie;
  3832. public $authTimeout;
  3833. public $autoRenewCookie=false;
  3834. public $autoUpdateFlash=true;
  3835. public $loginRequiredAjaxResponse;
  3836. private $_keyPrefix;
  3837. private $_access=array();
  3838. public function __get($name)
  3839. {
  3840. if($this->hasState($name))
  3841. return $this->getState($name);
  3842. else
  3843. return parent::__get($name);
  3844. }
  3845. public function __set($name,$value)
  3846. {
  3847. if($this->hasState($name))
  3848. $this->setState($name,$value);
  3849. else
  3850. parent::__set($name,$value);
  3851. }
  3852. public function __isset($name)
  3853. {
  3854. if($this->hasState($name))
  3855. return $this->getState($name)!==null;
  3856. else
  3857. return parent::__isset($name);
  3858. }
  3859. public function __unset($name)
  3860. {
  3861. if($this->hasState($name))
  3862. $this->setState($name,null);
  3863. else
  3864. parent::__unset($name);
  3865. }
  3866. public function init()
  3867. {
  3868. parent::init();
  3869. Yii::app()->getSession()->open();
  3870. if($this->getIsGuest() && $this->allowAutoLogin)
  3871. $this->restoreFromCookie();
  3872. else if($this->autoRenewCookie && $this->allowAutoLogin)
  3873. $this->renewCookie();
  3874. if($this->autoUpdateFlash)
  3875. $this->updateFlash();
  3876. $this->updateAuthStatus();
  3877. }
  3878. public function login($identity,$duration=0)
  3879. {
  3880. $id=$identity->getId();
  3881. $states=$identity->getPersistentStates();
  3882. if($this->beforeLogin($id,$states,false))
  3883. {
  3884. $this->changeIdentity($id,$identity->getName(),$states);
  3885. if($duration>0)
  3886. {
  3887. if($this->allowAutoLogin)
  3888. $this->saveToCookie($duration);
  3889. else
  3890. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  3891. array('{class}'=>get_class($this))));
  3892. }
  3893. $this->afterLogin(false);
  3894. }
  3895. return !$this->getIsGuest();
  3896. }
  3897. public function logout($destroySession=true)
  3898. {
  3899. if($this->beforeLogout())
  3900. {
  3901. if($this->allowAutoLogin)
  3902. {
  3903. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  3904. if($this->identityCookie!==null)
  3905. {
  3906. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3907. $cookie->value=null;
  3908. $cookie->expire=0;
  3909. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  3910. }
  3911. }
  3912. if($destroySession)
  3913. Yii::app()->getSession()->destroy();
  3914. else
  3915. $this->clearStates();
  3916. $this->afterLogout();
  3917. }
  3918. }
  3919. public function getIsGuest()
  3920. {
  3921. return $this->getState('__id')===null;
  3922. }
  3923. public function getId()
  3924. {
  3925. return $this->getState('__id');
  3926. }
  3927. public function setId($value)
  3928. {
  3929. $this->setState('__id',$value);
  3930. }
  3931. public function getName()
  3932. {
  3933. if(($name=$this->getState('__name'))!==null)
  3934. return $name;
  3935. else
  3936. return $this->guestName;
  3937. }
  3938. public function setName($value)
  3939. {
  3940. $this->setState('__name',$value);
  3941. }
  3942. public function getReturnUrl($defaultUrl=null)
  3943. {
  3944. return $this->getState('__returnUrl', $defaultUrl===null ? Yii::app()->getRequest()->getScriptUrl() : CHtml::normalizeUrl($defaultUrl));
  3945. }
  3946. public function setReturnUrl($value)
  3947. {
  3948. $this->setState('__returnUrl',$value);
  3949. }
  3950. public function loginRequired()
  3951. {
  3952. $app=Yii::app();
  3953. $request=$app->getRequest();
  3954. if(!$request->getIsAjaxRequest())
  3955. $this->setReturnUrl($request->getUrl());
  3956. elseif(isset($this->loginRequiredAjaxResponse))
  3957. {
  3958. echo $this->loginRequiredAjaxResponse;
  3959. Yii::app()->end();
  3960. }
  3961. if(($url=$this->loginUrl)!==null)
  3962. {
  3963. if(is_array($url))
  3964. {
  3965. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  3966. $url=$app->createUrl($route,array_splice($url,1));
  3967. }
  3968. $request->redirect($url);
  3969. }
  3970. else
  3971. throw new CHttpException(403,Yii::t('yii','Login Required'));
  3972. }
  3973. protected function beforeLogin($id,$states,$fromCookie)
  3974. {
  3975. return true;
  3976. }
  3977. protected function afterLogin($fromCookie)
  3978. {
  3979. }
  3980. protected function beforeLogout()
  3981. {
  3982. return true;
  3983. }
  3984. protected function afterLogout()
  3985. {
  3986. }
  3987. protected function restoreFromCookie()
  3988. {
  3989. $app=Yii::app();
  3990. $request=$app->getRequest();
  3991. $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  3992. if($cookie && !empty($cookie->value) && is_string($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  3993. {
  3994. $data=@unserialize($data);
  3995. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3996. {
  3997. list($id,$name,$duration,$states)=$data;
  3998. if($this->beforeLogin($id,$states,true))
  3999. {
  4000. $this->changeIdentity($id,$name,$states);
  4001. if($this->autoRenewCookie)
  4002. {
  4003. $cookie->expire=time()+$duration;
  4004. $request->getCookies()->add($cookie->name,$cookie);
  4005. }
  4006. $this->afterLogin(true);
  4007. }
  4008. }
  4009. }
  4010. }
  4011. protected function renewCookie()
  4012. {
  4013. $request=Yii::app()->getRequest();
  4014. $cookies=$request->getCookies();
  4015. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  4016. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  4017. {
  4018. $data=@unserialize($data);
  4019. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4020. {
  4021. $cookie->expire=time()+$data[2];
  4022. $cookies->add($cookie->name,$cookie);
  4023. }
  4024. }
  4025. }
  4026. protected function saveToCookie($duration)
  4027. {
  4028. $app=Yii::app();
  4029. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4030. $cookie->expire=time()+$duration;
  4031. $data=array(
  4032. $this->getId(),
  4033. $this->getName(),
  4034. $duration,
  4035. $this->saveIdentityStates(),
  4036. );
  4037. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  4038. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  4039. }
  4040. protected function createIdentityCookie($name)
  4041. {
  4042. $cookie=new CHttpCookie($name,'');
  4043. if(is_array($this->identityCookie))
  4044. {
  4045. foreach($this->identityCookie as $name=>$value)
  4046. $cookie->$name=$value;
  4047. }
  4048. return $cookie;
  4049. }
  4050. public function getStateKeyPrefix()
  4051. {
  4052. if($this->_keyPrefix!==null)
  4053. return $this->_keyPrefix;
  4054. else
  4055. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  4056. }
  4057. public function setStateKeyPrefix($value)
  4058. {
  4059. $this->_keyPrefix=$value;
  4060. }
  4061. public function getState($key,$defaultValue=null)
  4062. {
  4063. $key=$this->getStateKeyPrefix().$key;
  4064. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4065. }
  4066. public function setState($key,$value,$defaultValue=null)
  4067. {
  4068. $key=$this->getStateKeyPrefix().$key;
  4069. if($value===$defaultValue)
  4070. unset($_SESSION[$key]);
  4071. else
  4072. $_SESSION[$key]=$value;
  4073. }
  4074. public function hasState($key)
  4075. {
  4076. $key=$this->getStateKeyPrefix().$key;
  4077. return isset($_SESSION[$key]);
  4078. }
  4079. public function clearStates()
  4080. {
  4081. $keys=array_keys($_SESSION);
  4082. $prefix=$this->getStateKeyPrefix();
  4083. $n=strlen($prefix);
  4084. foreach($keys as $key)
  4085. {
  4086. if(!strncmp($key,$prefix,$n))
  4087. unset($_SESSION[$key]);
  4088. }
  4089. }
  4090. public function getFlashes($delete=true)
  4091. {
  4092. $flashes=array();
  4093. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  4094. $keys=array_keys($_SESSION);
  4095. $n=strlen($prefix);
  4096. foreach($keys as $key)
  4097. {
  4098. if(!strncmp($key,$prefix,$n))
  4099. {
  4100. $flashes[substr($key,$n)]=$_SESSION[$key];
  4101. if($delete)
  4102. unset($_SESSION[$key]);
  4103. }
  4104. }
  4105. if($delete)
  4106. $this->setState(self::FLASH_COUNTERS,array());
  4107. return $flashes;
  4108. }
  4109. public function getFlash($key,$defaultValue=null,$delete=true)
  4110. {
  4111. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4112. if($delete)
  4113. $this->setFlash($key,null);
  4114. return $value;
  4115. }
  4116. public function setFlash($key,$value,$defaultValue=null)
  4117. {
  4118. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4119. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4120. if($value===$defaultValue)
  4121. unset($counters[$key]);
  4122. else
  4123. $counters[$key]=0;
  4124. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4125. }
  4126. public function hasFlash($key)
  4127. {
  4128. return $this->getFlash($key, null, false)!==null;
  4129. }
  4130. protected function changeIdentity($id,$name,$states)
  4131. {
  4132. Yii::app()->getSession()->regenerateID(true);
  4133. $this->setId($id);
  4134. $this->setName($name);
  4135. $this->loadIdentityStates($states);
  4136. }
  4137. protected function saveIdentityStates()
  4138. {
  4139. $states=array();
  4140. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4141. $states[$name]=$this->getState($name);
  4142. return $states;
  4143. }
  4144. protected function loadIdentityStates($states)
  4145. {
  4146. $names=array();
  4147. if(is_array($states))
  4148. {
  4149. foreach($states as $name=>$value)
  4150. {
  4151. $this->setState($name,$value);
  4152. $names[$name]=true;
  4153. }
  4154. }
  4155. $this->setState(self::STATES_VAR,$names);
  4156. }
  4157. protected function updateFlash()
  4158. {
  4159. $counters=$this->getState(self::FLASH_COUNTERS);
  4160. if(!is_array($counters))
  4161. return;
  4162. foreach($counters as $key=>$count)
  4163. {
  4164. if($count)
  4165. {
  4166. unset($counters[$key]);
  4167. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4168. }
  4169. else
  4170. $counters[$key]++;
  4171. }
  4172. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4173. }
  4174. protected function updateAuthStatus()
  4175. {
  4176. if($this->authTimeout!==null && !$this->getIsGuest())
  4177. {
  4178. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4179. if ($expires!==null && $expires < time())
  4180. $this->logout(false);
  4181. else
  4182. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4183. }
  4184. }
  4185. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4186. {
  4187. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4188. return $this->_access[$operation];
  4189. $access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4190. if($allowCaching && $params===array())
  4191. $this->_access[$operation]=$access;
  4192. return $access;
  4193. }
  4194. }
  4195. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4196. {
  4197. public $autoStart=true;
  4198. public function init()
  4199. {
  4200. parent::init();
  4201. if($this->autoStart)
  4202. $this->open();
  4203. register_shutdown_function(array($this,'close'));
  4204. }
  4205. public function getUseCustomStorage()
  4206. {
  4207. return false;
  4208. }
  4209. public function open()
  4210. {
  4211. if($this->getUseCustomStorage())
  4212. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4213. @session_start();
  4214. if(YII_DEBUG && session_id()=='')
  4215. {
  4216. $message=Yii::t('yii','Failed to start session.');
  4217. if(function_exists('error_get_last'))
  4218. {
  4219. $error=error_get_last();
  4220. if(isset($error['message']))
  4221. $message=$error['message'];
  4222. }
  4223. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4224. }
  4225. }
  4226. public function close()
  4227. {
  4228. if(session_id()!=='')
  4229. @session_write_close();
  4230. }
  4231. public function destroy()
  4232. {
  4233. if(session_id()!=='')
  4234. {
  4235. @session_unset();
  4236. @session_destroy();
  4237. }
  4238. }
  4239. public function getIsStarted()
  4240. {
  4241. return session_id()!=='';
  4242. }
  4243. public function getSessionID()
  4244. {
  4245. return session_id();
  4246. }
  4247. public function setSessionID($value)
  4248. {
  4249. session_id($value);
  4250. }
  4251. public function regenerateID($deleteOldSession=false)
  4252. {
  4253. session_regenerate_id($deleteOldSession);
  4254. }
  4255. public function getSessionName()
  4256. {
  4257. return session_name();
  4258. }
  4259. public function setSessionName($value)
  4260. {
  4261. session_name($value);
  4262. }
  4263. public function getSavePath()
  4264. {
  4265. return session_save_path();
  4266. }
  4267. public function setSavePath($value)
  4268. {
  4269. if(is_dir($value))
  4270. session_save_path($value);
  4271. else
  4272. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4273. array('{path}'=>$value)));
  4274. }
  4275. public function getCookieParams()
  4276. {
  4277. return session_get_cookie_params();
  4278. }
  4279. public function setCookieParams($value)
  4280. {
  4281. $data=session_get_cookie_params();
  4282. extract($data);
  4283. extract($value);
  4284. if(isset($httponly))
  4285. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4286. else
  4287. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4288. }
  4289. public function getCookieMode()
  4290. {
  4291. if(ini_get('session.use_cookies')==='0')
  4292. return 'none';
  4293. else if(ini_get('session.use_only_cookies')==='0')
  4294. return 'allow';
  4295. else
  4296. return 'only';
  4297. }
  4298. public function setCookieMode($value)
  4299. {
  4300. if($value==='none')
  4301. {
  4302. ini_set('session.use_cookies','0');
  4303. ini_set('session.use_only_cookies','0');
  4304. }
  4305. else if($value==='allow')
  4306. {
  4307. ini_set('session.use_cookies','1');
  4308. ini_set('session.use_only_cookies','0');
  4309. }
  4310. else if($value==='only')
  4311. {
  4312. ini_set('session.use_cookies','1');
  4313. ini_set('session.use_only_cookies','1');
  4314. }
  4315. else
  4316. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4317. }
  4318. public function getGCProbability()
  4319. {
  4320. return (int)ini_get('session.gc_probability');
  4321. }
  4322. public function setGCProbability($value)
  4323. {
  4324. $value=(int)$value;
  4325. if($value>=0 && $value<=100)
  4326. {
  4327. ini_set('session.gc_probability',$value);
  4328. ini_set('session.gc_divisor','100');
  4329. }
  4330. else
  4331. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be an integer between 0 and 100.',
  4332. array('{value}'=>$value)));
  4333. }
  4334. public function getUseTransparentSessionID()
  4335. {
  4336. return ini_get('session.use_trans_sid')==1;
  4337. }
  4338. public function setUseTransparentSessionID($value)
  4339. {
  4340. ini_set('session.use_trans_sid',$value?'1':'0');
  4341. }
  4342. public function getTimeout()
  4343. {
  4344. return (int)ini_get('session.gc_maxlifetime');
  4345. }
  4346. public function setTimeout($value)
  4347. {
  4348. ini_set('session.gc_maxlifetime',$value);
  4349. }
  4350. public function openSession($savePath,$sessionName)
  4351. {
  4352. return true;
  4353. }
  4354. public function closeSession()
  4355. {
  4356. return true;
  4357. }
  4358. public function readSession($id)
  4359. {
  4360. return '';
  4361. }
  4362. public function writeSession($id,$data)
  4363. {
  4364. return true;
  4365. }
  4366. public function destroySession($id)
  4367. {
  4368. return true;
  4369. }
  4370. public function gcSession($maxLifetime)
  4371. {
  4372. return true;
  4373. }
  4374. //------ The following methods enable CHttpSession to be CMap-like -----
  4375. public function getIterator()
  4376. {
  4377. return new CHttpSessionIterator;
  4378. }
  4379. public function getCount()
  4380. {
  4381. return count($_SESSION);
  4382. }
  4383. public function count()
  4384. {
  4385. return $this->getCount();
  4386. }
  4387. public function getKeys()
  4388. {
  4389. return array_keys($_SESSION);
  4390. }
  4391. public function get($key,$defaultValue=null)
  4392. {
  4393. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4394. }
  4395. public function itemAt($key)
  4396. {
  4397. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4398. }
  4399. public function add($key,$value)
  4400. {
  4401. $_SESSION[$key]=$value;
  4402. }
  4403. public function remove($key)
  4404. {
  4405. if(isset($_SESSION[$key]))
  4406. {
  4407. $value=$_SESSION[$key];
  4408. unset($_SESSION[$key]);
  4409. return $value;
  4410. }
  4411. else
  4412. return null;
  4413. }
  4414. public function clear()
  4415. {
  4416. foreach(array_keys($_SESSION) as $key)
  4417. unset($_SESSION[$key]);
  4418. }
  4419. public function contains($key)
  4420. {
  4421. return isset($_SESSION[$key]);
  4422. }
  4423. public function toArray()
  4424. {
  4425. return $_SESSION;
  4426. }
  4427. public function offsetExists($offset)
  4428. {
  4429. return isset($_SESSION[$offset]);
  4430. }
  4431. public function offsetGet($offset)
  4432. {
  4433. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4434. }
  4435. public function offsetSet($offset,$item)
  4436. {
  4437. $_SESSION[$offset]=$item;
  4438. }
  4439. public function offsetUnset($offset)
  4440. {
  4441. unset($_SESSION[$offset]);
  4442. }
  4443. }
  4444. class CHtml
  4445. {
  4446. const ID_PREFIX='yt';
  4447. public static $errorSummaryCss='errorSummary';
  4448. public static $errorMessageCss='errorMessage';
  4449. public static $errorCss='error';
  4450. public static $requiredCss='required';
  4451. public static $beforeRequiredLabel='';
  4452. public static $afterRequiredLabel=' <span class="required">*</span>';
  4453. public static $count=0;
  4454. public static $liveEvents = true;
  4455. public static function encode($text)
  4456. {
  4457. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4458. }
  4459. public static function decode($text)
  4460. {
  4461. return htmlspecialchars_decode($text,ENT_QUOTES);
  4462. }
  4463. public static function encodeArray($data)
  4464. {
  4465. $d=array();
  4466. foreach($data as $key=>$value)
  4467. {
  4468. if(is_string($key))
  4469. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4470. if(is_string($value))
  4471. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4472. else if(is_array($value))
  4473. $value=self::encodeArray($value);
  4474. $d[$key]=$value;
  4475. }
  4476. return $d;
  4477. }
  4478. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4479. {
  4480. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4481. if($content===false)
  4482. return $closeTag ? $html.' />' : $html.'>';
  4483. else
  4484. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4485. }
  4486. public static function openTag($tag,$htmlOptions=array())
  4487. {
  4488. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4489. }
  4490. public static function closeTag($tag)
  4491. {
  4492. return '</'.$tag.'>';
  4493. }
  4494. public static function cdata($text)
  4495. {
  4496. return '<![CDATA[' . $text . ']]>';
  4497. }
  4498. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4499. {
  4500. if($name!==null)
  4501. $options['name']=$name;
  4502. if($httpEquiv!==null)
  4503. $options['http-equiv']=$httpEquiv;
  4504. $options['content']=$content;
  4505. return self::tag('meta',$options);
  4506. }
  4507. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4508. {
  4509. if($relation!==null)
  4510. $options['rel']=$relation;
  4511. if($type!==null)
  4512. $options['type']=$type;
  4513. if($href!==null)
  4514. $options['href']=$href;
  4515. if($media!==null)
  4516. $options['media']=$media;
  4517. return self::tag('link',$options);
  4518. }
  4519. public static function css($text,$media='')
  4520. {
  4521. if($media!=='')
  4522. $media=' media="'.$media.'"';
  4523. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4524. }
  4525. public static function refresh($seconds, $url='')
  4526. {
  4527. $content="$seconds";
  4528. if($url!=='')
  4529. $content.=';'.self::normalizeUrl($url);
  4530. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4531. }
  4532. public static function cssFile($url,$media='')
  4533. {
  4534. if($media!=='')
  4535. $media=' media="'.$media.'"';
  4536. return '<link rel="stylesheet" type="text/css" href="'.self::encode($url).'"'.$media.' />';
  4537. }
  4538. public static function script($text)
  4539. {
  4540. return "<script type=\"text/javascript\">\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</script>";
  4541. }
  4542. public static function scriptFile($url)
  4543. {
  4544. return '<script type="text/javascript" src="'.self::encode($url).'"></script>';
  4545. }
  4546. public static function form($action='',$method='post',$htmlOptions=array())
  4547. {
  4548. return self::beginForm($action,$method,$htmlOptions);
  4549. }
  4550. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4551. {
  4552. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4553. $htmlOptions['method']=$method;
  4554. $form=self::tag('form',$htmlOptions,false,false);
  4555. $hiddens=array();
  4556. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4557. {
  4558. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4559. {
  4560. if(($pos=strpos($pair,'='))!==false)
  4561. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4562. }
  4563. }
  4564. $request=Yii::app()->request;
  4565. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4566. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4567. if($hiddens!==array())
  4568. $form.="\n".self::tag('div',array('style'=>'display:none'),implode("\n",$hiddens));
  4569. return $form;
  4570. }
  4571. public static function endForm()
  4572. {
  4573. return '</form>';
  4574. }
  4575. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4576. {
  4577. return self::form($action,$method,$htmlOptions)."\n".
  4578. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4579. }
  4580. public static function pageStateField($value)
  4581. {
  4582. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4583. }
  4584. public static function link($text,$url='#',$htmlOptions=array())
  4585. {
  4586. if($url!=='')
  4587. $htmlOptions['href']=self::normalizeUrl($url);
  4588. self::clientChange('click',$htmlOptions);
  4589. return self::tag('a',$htmlOptions,$text);
  4590. }
  4591. public static function mailto($text,$email='',$htmlOptions=array())
  4592. {
  4593. if($email==='')
  4594. $email=$text;
  4595. return self::link($text,'mailto:'.$email,$htmlOptions);
  4596. }
  4597. public static function image($src,$alt='',$htmlOptions=array())
  4598. {
  4599. $htmlOptions['src']=$src;
  4600. $htmlOptions['alt']=$alt;
  4601. return self::tag('img',$htmlOptions);
  4602. }
  4603. public static function button($label='button',$htmlOptions=array())
  4604. {
  4605. if(!isset($htmlOptions['name']))
  4606. {
  4607. if(!array_key_exists('name',$htmlOptions))
  4608. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4609. }
  4610. if(!isset($htmlOptions['type']))
  4611. $htmlOptions['type']='button';
  4612. if(!isset($htmlOptions['value']))
  4613. $htmlOptions['value']=$label;
  4614. self::clientChange('click',$htmlOptions);
  4615. return self::tag('input',$htmlOptions);
  4616. }
  4617. public static function htmlButton($label='button',$htmlOptions=array())
  4618. {
  4619. if(!isset($htmlOptions['name']))
  4620. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4621. if(!isset($htmlOptions['type']))
  4622. $htmlOptions['type']='button';
  4623. self::clientChange('click',$htmlOptions);
  4624. return self::tag('button',$htmlOptions,$label);
  4625. }
  4626. public static function submitButton($label='submit',$htmlOptions=array())
  4627. {
  4628. $htmlOptions['type']='submit';
  4629. return self::button($label,$htmlOptions);
  4630. }
  4631. public static function resetButton($label='reset',$htmlOptions=array())
  4632. {
  4633. $htmlOptions['type']='reset';
  4634. return self::button($label,$htmlOptions);
  4635. }
  4636. public static function imageButton($src,$htmlOptions=array())
  4637. {
  4638. $htmlOptions['src']=$src;
  4639. $htmlOptions['type']='image';
  4640. return self::button('submit',$htmlOptions);
  4641. }
  4642. public static function linkButton($label='submit',$htmlOptions=array())
  4643. {
  4644. if(!isset($htmlOptions['submit']))
  4645. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  4646. return self::link($label,'#',$htmlOptions);
  4647. }
  4648. public static function label($label,$for,$htmlOptions=array())
  4649. {
  4650. if($for===false)
  4651. unset($htmlOptions['for']);
  4652. else
  4653. $htmlOptions['for']=$for;
  4654. if(isset($htmlOptions['required']))
  4655. {
  4656. if($htmlOptions['required'])
  4657. {
  4658. if(isset($htmlOptions['class']))
  4659. $htmlOptions['class'].=' '.self::$requiredCss;
  4660. else
  4661. $htmlOptions['class']=self::$requiredCss;
  4662. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  4663. }
  4664. unset($htmlOptions['required']);
  4665. }
  4666. return self::tag('label',$htmlOptions,$label);
  4667. }
  4668. public static function textField($name,$value='',$htmlOptions=array())
  4669. {
  4670. self::clientChange('change',$htmlOptions);
  4671. return self::inputField('text',$name,$value,$htmlOptions);
  4672. }
  4673. public static function hiddenField($name,$value='',$htmlOptions=array())
  4674. {
  4675. return self::inputField('hidden',$name,$value,$htmlOptions);
  4676. }
  4677. public static function passwordField($name,$value='',$htmlOptions=array())
  4678. {
  4679. self::clientChange('change',$htmlOptions);
  4680. return self::inputField('password',$name,$value,$htmlOptions);
  4681. }
  4682. public static function fileField($name,$value='',$htmlOptions=array())
  4683. {
  4684. return self::inputField('file',$name,$value,$htmlOptions);
  4685. }
  4686. public static function textArea($name,$value='',$htmlOptions=array())
  4687. {
  4688. $htmlOptions['name']=$name;
  4689. if(!isset($htmlOptions['id']))
  4690. $htmlOptions['id']=self::getIdByName($name);
  4691. else if($htmlOptions['id']===false)
  4692. unset($htmlOptions['id']);
  4693. self::clientChange('change',$htmlOptions);
  4694. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  4695. }
  4696. public static function radioButton($name,$checked=false,$htmlOptions=array())
  4697. {
  4698. if($checked)
  4699. $htmlOptions['checked']='checked';
  4700. else
  4701. unset($htmlOptions['checked']);
  4702. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4703. self::clientChange('click',$htmlOptions);
  4704. if(array_key_exists('uncheckValue',$htmlOptions))
  4705. {
  4706. $uncheck=$htmlOptions['uncheckValue'];
  4707. unset($htmlOptions['uncheckValue']);
  4708. }
  4709. else
  4710. $uncheck=null;
  4711. if($uncheck!==null)
  4712. {
  4713. // add a hidden field so that if the radio button is not selected, it still submits a value
  4714. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4715. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4716. else
  4717. $uncheckOptions=array('id'=>false);
  4718. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4719. }
  4720. else
  4721. $hidden='';
  4722. // add a hidden field so that if the radio button is not selected, it still submits a value
  4723. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  4724. }
  4725. public static function checkBox($name,$checked=false,$htmlOptions=array())
  4726. {
  4727. if($checked)
  4728. $htmlOptions['checked']='checked';
  4729. else
  4730. unset($htmlOptions['checked']);
  4731. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4732. self::clientChange('click',$htmlOptions);
  4733. if(array_key_exists('uncheckValue',$htmlOptions))
  4734. {
  4735. $uncheck=$htmlOptions['uncheckValue'];
  4736. unset($htmlOptions['uncheckValue']);
  4737. }
  4738. else
  4739. $uncheck=null;
  4740. if($uncheck!==null)
  4741. {
  4742. // add a hidden field so that if the radio button is not selected, it still submits a value
  4743. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4744. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4745. else
  4746. $uncheckOptions=array('id'=>false);
  4747. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4748. }
  4749. else
  4750. $hidden='';
  4751. // add a hidden field so that if the checkbox is not selected, it still submits a value
  4752. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  4753. }
  4754. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  4755. {
  4756. $htmlOptions['name']=$name;
  4757. if(!isset($htmlOptions['id']))
  4758. $htmlOptions['id']=self::getIdByName($name);
  4759. else if($htmlOptions['id']===false)
  4760. unset($htmlOptions['id']);
  4761. self::clientChange('change',$htmlOptions);
  4762. $options="\n".self::listOptions($select,$data,$htmlOptions);
  4763. return self::tag('select',$htmlOptions,$options);
  4764. }
  4765. public static function listBox($name,$select,$data,$htmlOptions=array())
  4766. {
  4767. if(!isset($htmlOptions['size']))
  4768. $htmlOptions['size']=4;
  4769. if(isset($htmlOptions['multiple']))
  4770. {
  4771. if(substr($name,-2)!=='[]')
  4772. $name.='[]';
  4773. }
  4774. return self::dropDownList($name,$select,$data,$htmlOptions);
  4775. }
  4776. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  4777. {
  4778. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4779. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4780. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  4781. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  4782. if(substr($name,-2)!=='[]')
  4783. $name.='[]';
  4784. if(isset($htmlOptions['checkAll']))
  4785. {
  4786. $checkAllLabel=$htmlOptions['checkAll'];
  4787. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  4788. }
  4789. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  4790. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4791. unset($htmlOptions['labelOptions']);
  4792. $items=array();
  4793. $baseID=self::getIdByName($name);
  4794. $id=0;
  4795. $checkAll=true;
  4796. foreach($data as $value=>$label)
  4797. {
  4798. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  4799. $checkAll=$checkAll && $checked;
  4800. $htmlOptions['value']=$value;
  4801. $htmlOptions['id']=$baseID.'_'.$id++;
  4802. $option=self::checkBox($name,$checked,$htmlOptions);
  4803. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4804. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4805. }
  4806. if(isset($checkAllLabel))
  4807. {
  4808. $htmlOptions['value']=1;
  4809. $htmlOptions['id']=$id=$baseID.'_all';
  4810. $option=self::checkBox($id,$checkAll,$htmlOptions);
  4811. $label=self::label($checkAllLabel,$id,$labelOptions);
  4812. $item=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4813. if($checkAllLast)
  4814. $items[]=$item;
  4815. else
  4816. array_unshift($items,$item);
  4817. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  4818. $js=<<<EOD
  4819. $('#$id').click(function() {
  4820. $("input[name='$name']").prop('checked', this.checked);
  4821. });
  4822. $("input[name='$name']").click(function() {
  4823. $('#$id').prop('checked', !$("input[name='$name']:not(:checked)").length);
  4824. });
  4825. $('#$id').prop('checked', !$("input[name='$name']:not(:checked)").length);
  4826. EOD;
  4827. $cs=Yii::app()->getClientScript();
  4828. $cs->registerCoreScript('jquery');
  4829. $cs->registerScript($id,$js);
  4830. }
  4831. if(empty($container))
  4832. return implode($separator,$items);
  4833. else
  4834. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  4835. }
  4836. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  4837. {
  4838. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4839. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4840. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  4841. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  4842. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4843. unset($htmlOptions['labelOptions']);
  4844. $items=array();
  4845. $baseID=self::getIdByName($name);
  4846. $id=0;
  4847. foreach($data as $value=>$label)
  4848. {
  4849. $checked=!strcmp($value,$select);
  4850. $htmlOptions['value']=$value;
  4851. $htmlOptions['id']=$baseID.'_'.$id++;
  4852. $option=self::radioButton($name,$checked,$htmlOptions);
  4853. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4854. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4855. }
  4856. if(empty($container))
  4857. return implode($separator,$items);
  4858. else
  4859. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  4860. }
  4861. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  4862. {
  4863. if(!isset($htmlOptions['href']))
  4864. $htmlOptions['href']='#';
  4865. $ajaxOptions['url']=$url;
  4866. $htmlOptions['ajax']=$ajaxOptions;
  4867. self::clientChange('click',$htmlOptions);
  4868. return self::tag('a',$htmlOptions,$text);
  4869. }
  4870. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4871. {
  4872. $ajaxOptions['url']=$url;
  4873. $htmlOptions['ajax']=$ajaxOptions;
  4874. return self::button($label,$htmlOptions);
  4875. }
  4876. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4877. {
  4878. $ajaxOptions['type']='POST';
  4879. $htmlOptions['type']='submit';
  4880. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  4881. }
  4882. public static function ajax($options)
  4883. {
  4884. Yii::app()->getClientScript()->registerCoreScript('jquery');
  4885. if(!isset($options['url']))
  4886. $options['url']=new CJavaScriptExpression('location.href');
  4887. else
  4888. $options['url']=self::normalizeUrl($options['url']);
  4889. if(!isset($options['cache']))
  4890. $options['cache']=false;
  4891. if(!isset($options['data']) && isset($options['type']))
  4892. $options['data']=new CJavaScriptExpression('jQuery(this).parents("form").serialize()');
  4893. foreach(array('beforeSend','complete','error','success') as $name)
  4894. {
  4895. if(isset($options[$name]) && (!($options[$name] instanceof CJavaScriptExpression) || strpos($options[$name],'js:')!==0))
  4896. $options[$name]=new CJavaScriptExpression($options[$name]);
  4897. }
  4898. if(isset($options['update']))
  4899. {
  4900. if(!isset($options['success']))
  4901. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['update'].'").html(html)}');
  4902. unset($options['update']);
  4903. }
  4904. if(isset($options['replace']))
  4905. {
  4906. if(!isset($options['success']))
  4907. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['replace'].'").replaceWith(html)}');
  4908. unset($options['replace']);
  4909. }
  4910. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  4911. }
  4912. public static function asset($path,$hashByName=false)
  4913. {
  4914. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  4915. }
  4916. public static function normalizeUrl($url)
  4917. {
  4918. if(is_array($url))
  4919. {
  4920. if(isset($url[0]))
  4921. {
  4922. if(($c=Yii::app()->getController())!==null)
  4923. $url=$c->createUrl($url[0],array_splice($url,1));
  4924. else
  4925. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  4926. }
  4927. else
  4928. $url='';
  4929. }
  4930. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  4931. }
  4932. protected static function inputField($type,$name,$value,$htmlOptions)
  4933. {
  4934. $htmlOptions['type']=$type;
  4935. $htmlOptions['value']=$value;
  4936. $htmlOptions['name']=$name;
  4937. if(!isset($htmlOptions['id']))
  4938. $htmlOptions['id']=self::getIdByName($name);
  4939. else if($htmlOptions['id']===false)
  4940. unset($htmlOptions['id']);
  4941. return self::tag('input',$htmlOptions);
  4942. }
  4943. public static function activeLabel($model,$attribute,$htmlOptions=array())
  4944. {
  4945. if(isset($htmlOptions['for']))
  4946. {
  4947. $for=$htmlOptions['for'];
  4948. unset($htmlOptions['for']);
  4949. }
  4950. else
  4951. $for=self::getIdByName(self::resolveName($model,$attribute));
  4952. if(isset($htmlOptions['label']))
  4953. {
  4954. if(($label=$htmlOptions['label'])===false)
  4955. return '';
  4956. unset($htmlOptions['label']);
  4957. }
  4958. else
  4959. $label=$model->getAttributeLabel($attribute);
  4960. if($model->hasErrors($attribute))
  4961. self::addErrorCss($htmlOptions);
  4962. return self::label($label,$for,$htmlOptions);
  4963. }
  4964. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  4965. {
  4966. $realAttribute=$attribute;
  4967. self::resolveName($model,$attribute); // strip off square brackets if any
  4968. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  4969. return self::activeLabel($model,$realAttribute,$htmlOptions);
  4970. }
  4971. public static function activeTextField($model,$attribute,$htmlOptions=array())
  4972. {
  4973. self::resolveNameID($model,$attribute,$htmlOptions);
  4974. self::clientChange('change',$htmlOptions);
  4975. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  4976. }
  4977. public static function activeUrlField($model,$attribute,$htmlOptions=array())
  4978. {
  4979. self::resolveNameID($model,$attribute,$htmlOptions);
  4980. self::clientChange('change',$htmlOptions);
  4981. return self::activeInputField('url',$model,$attribute,$htmlOptions);
  4982. }
  4983. public static function activeEmailField($model,$attribute,$htmlOptions=array())
  4984. {
  4985. self::resolveNameID($model,$attribute,$htmlOptions);
  4986. self::clientChange('change',$htmlOptions);
  4987. return self::activeInputField('email',$model,$attribute,$htmlOptions);
  4988. }
  4989. public static function activeNumberField($model,$attribute,$htmlOptions=array())
  4990. {
  4991. self::resolveNameID($model,$attribute,$htmlOptions);
  4992. self::clientChange('change',$htmlOptions);
  4993. return self::activeInputField('number',$model,$attribute,$htmlOptions);
  4994. }
  4995. public static function activeRangeField($model,$attribute,$htmlOptions=array())
  4996. {
  4997. self::resolveNameID($model,$attribute,$htmlOptions);
  4998. self::clientChange('change',$htmlOptions);
  4999. return self::activeInputField('range',$model,$attribute,$htmlOptions);
  5000. }
  5001. public static function activeDateField($model,$attribute,$htmlOptions=array())
  5002. {
  5003. self::resolveNameID($model,$attribute,$htmlOptions);
  5004. self::clientChange('change',$htmlOptions);
  5005. return self::activeInputField('date',$model,$attribute,$htmlOptions);
  5006. }
  5007. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  5008. {
  5009. self::resolveNameID($model,$attribute,$htmlOptions);
  5010. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  5011. }
  5012. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  5013. {
  5014. self::resolveNameID($model,$attribute,$htmlOptions);
  5015. self::clientChange('change',$htmlOptions);
  5016. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  5017. }
  5018. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  5019. {
  5020. self::resolveNameID($model,$attribute,$htmlOptions);
  5021. self::clientChange('change',$htmlOptions);
  5022. if($model->hasErrors($attribute))
  5023. self::addErrorCss($htmlOptions);
  5024. $text=self::resolveValue($model,$attribute);
  5025. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  5026. }
  5027. public static function activeFileField($model,$attribute,$htmlOptions=array())
  5028. {
  5029. self::resolveNameID($model,$attribute,$htmlOptions);
  5030. // add a hidden field so that if a model only has a file field, we can
  5031. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  5032. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5033. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  5034. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  5035. }
  5036. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  5037. {
  5038. self::resolveNameID($model,$attribute,$htmlOptions);
  5039. if(!isset($htmlOptions['value']))
  5040. $htmlOptions['value']=1;
  5041. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5042. $htmlOptions['checked']='checked';
  5043. self::clientChange('click',$htmlOptions);
  5044. if(array_key_exists('uncheckValue',$htmlOptions))
  5045. {
  5046. $uncheck=$htmlOptions['uncheckValue'];
  5047. unset($htmlOptions['uncheckValue']);
  5048. }
  5049. else
  5050. $uncheck='0';
  5051. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5052. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5053. // add a hidden field so that if the radio button is not selected, it still submits a value
  5054. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  5055. }
  5056. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  5057. {
  5058. self::resolveNameID($model,$attribute,$htmlOptions);
  5059. if(!isset($htmlOptions['value']))
  5060. $htmlOptions['value']=1;
  5061. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5062. $htmlOptions['checked']='checked';
  5063. self::clientChange('click',$htmlOptions);
  5064. if(array_key_exists('uncheckValue',$htmlOptions))
  5065. {
  5066. $uncheck=$htmlOptions['uncheckValue'];
  5067. unset($htmlOptions['uncheckValue']);
  5068. }
  5069. else
  5070. $uncheck='0';
  5071. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5072. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5073. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  5074. }
  5075. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  5076. {
  5077. self::resolveNameID($model,$attribute,$htmlOptions);
  5078. $selection=self::resolveValue($model,$attribute);
  5079. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  5080. self::clientChange('change',$htmlOptions);
  5081. if($model->hasErrors($attribute))
  5082. self::addErrorCss($htmlOptions);
  5083. if(isset($htmlOptions['multiple']))
  5084. {
  5085. if(substr($htmlOptions['name'],-2)!=='[]')
  5086. $htmlOptions['name'].='[]';
  5087. }
  5088. return self::tag('select',$htmlOptions,$options);
  5089. }
  5090. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  5091. {
  5092. if(!isset($htmlOptions['size']))
  5093. $htmlOptions['size']=4;
  5094. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  5095. }
  5096. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  5097. {
  5098. self::resolveNameID($model,$attribute,$htmlOptions);
  5099. $selection=self::resolveValue($model,$attribute);
  5100. if($model->hasErrors($attribute))
  5101. self::addErrorCss($htmlOptions);
  5102. $name=$htmlOptions['name'];
  5103. unset($htmlOptions['name']);
  5104. if(array_key_exists('uncheckValue',$htmlOptions))
  5105. {
  5106. $uncheck=$htmlOptions['uncheckValue'];
  5107. unset($htmlOptions['uncheckValue']);
  5108. }
  5109. else
  5110. $uncheck='';
  5111. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5112. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5113. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  5114. }
  5115. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  5116. {
  5117. self::resolveNameID($model,$attribute,$htmlOptions);
  5118. $selection=self::resolveValue($model,$attribute);
  5119. if($model->hasErrors($attribute))
  5120. self::addErrorCss($htmlOptions);
  5121. $name=$htmlOptions['name'];
  5122. unset($htmlOptions['name']);
  5123. if(array_key_exists('uncheckValue',$htmlOptions))
  5124. {
  5125. $uncheck=$htmlOptions['uncheckValue'];
  5126. unset($htmlOptions['uncheckValue']);
  5127. }
  5128. else
  5129. $uncheck='';
  5130. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5131. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5132. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  5133. }
  5134. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  5135. {
  5136. $content='';
  5137. if(!is_array($model))
  5138. $model=array($model);
  5139. if(isset($htmlOptions['firstError']))
  5140. {
  5141. $firstError=$htmlOptions['firstError'];
  5142. unset($htmlOptions['firstError']);
  5143. }
  5144. else
  5145. $firstError=false;
  5146. foreach($model as $m)
  5147. {
  5148. foreach($m->getErrors() as $errors)
  5149. {
  5150. foreach($errors as $error)
  5151. {
  5152. if($error!='')
  5153. $content.="<li>$error</li>\n";
  5154. if($firstError)
  5155. break;
  5156. }
  5157. }
  5158. }
  5159. if($content!=='')
  5160. {
  5161. if($header===null)
  5162. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5163. if(!isset($htmlOptions['class']))
  5164. $htmlOptions['class']=self::$errorSummaryCss;
  5165. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5166. }
  5167. else
  5168. return '';
  5169. }
  5170. public static function error($model,$attribute,$htmlOptions=array())
  5171. {
  5172. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5173. $error=$model->getError($attribute);
  5174. if($error!='')
  5175. {
  5176. if(!isset($htmlOptions['class']))
  5177. $htmlOptions['class']=self::$errorMessageCss;
  5178. return self::tag('div',$htmlOptions,$error);
  5179. }
  5180. else
  5181. return '';
  5182. }
  5183. public static function listData($models,$valueField,$textField,$groupField='')
  5184. {
  5185. $listData=array();
  5186. if($groupField==='')
  5187. {
  5188. foreach($models as $model)
  5189. {
  5190. $value=self::value($model,$valueField);
  5191. $text=self::value($model,$textField);
  5192. $listData[$value]=$text;
  5193. }
  5194. }
  5195. else
  5196. {
  5197. foreach($models as $model)
  5198. {
  5199. $group=self::value($model,$groupField);
  5200. $value=self::value($model,$valueField);
  5201. $text=self::value($model,$textField);
  5202. $listData[$group][$value]=$text;
  5203. }
  5204. }
  5205. return $listData;
  5206. }
  5207. public static function value($model,$attribute,$defaultValue=null)
  5208. {
  5209. foreach(explode('.',$attribute) as $name)
  5210. {
  5211. if(is_object($model))
  5212. $model=$model->$name;
  5213. else if(is_array($model) && isset($model[$name]))
  5214. $model=$model[$name];
  5215. else
  5216. return $defaultValue;
  5217. }
  5218. return $model;
  5219. }
  5220. public static function getIdByName($name)
  5221. {
  5222. return str_replace(array('[]', '][', '[', ']', ' '), array('', '_', '_', '', '_'), $name);
  5223. }
  5224. public static function activeId($model,$attribute)
  5225. {
  5226. return self::getIdByName(self::activeName($model,$attribute));
  5227. }
  5228. public static function activeName($model,$attribute)
  5229. {
  5230. $a=$attribute; // because the attribute name may be changed by resolveName
  5231. return self::resolveName($model,$a);
  5232. }
  5233. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5234. {
  5235. $htmlOptions['type']=$type;
  5236. if($type==='text' || $type==='password')
  5237. {
  5238. if(!isset($htmlOptions['maxlength']))
  5239. {
  5240. foreach($model->getValidators($attribute) as $validator)
  5241. {
  5242. if($validator instanceof CStringValidator && $validator->max!==null)
  5243. {
  5244. $htmlOptions['maxlength']=$validator->max;
  5245. break;
  5246. }
  5247. }
  5248. }
  5249. else if($htmlOptions['maxlength']===false)
  5250. unset($htmlOptions['maxlength']);
  5251. }
  5252. if($type==='file')
  5253. unset($htmlOptions['value']);
  5254. else if(!isset($htmlOptions['value']))
  5255. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5256. if($model->hasErrors($attribute))
  5257. self::addErrorCss($htmlOptions);
  5258. return self::tag('input',$htmlOptions);
  5259. }
  5260. public static function listOptions($selection,$listData,&$htmlOptions)
  5261. {
  5262. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5263. $content='';
  5264. if(isset($htmlOptions['prompt']))
  5265. {
  5266. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5267. unset($htmlOptions['prompt']);
  5268. }
  5269. if(isset($htmlOptions['empty']))
  5270. {
  5271. if(!is_array($htmlOptions['empty']))
  5272. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5273. foreach($htmlOptions['empty'] as $value=>$label)
  5274. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5275. unset($htmlOptions['empty']);
  5276. }
  5277. if(isset($htmlOptions['options']))
  5278. {
  5279. $options=$htmlOptions['options'];
  5280. unset($htmlOptions['options']);
  5281. }
  5282. else
  5283. $options=array();
  5284. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  5285. if(is_array($selection))
  5286. {
  5287. foreach($selection as $i=>$item)
  5288. {
  5289. if(is_object($item))
  5290. $selection[$i]=$item->$key;
  5291. }
  5292. }
  5293. else if(is_object($selection))
  5294. $selection=$selection->$key;
  5295. foreach($listData as $key=>$value)
  5296. {
  5297. if(is_array($value))
  5298. {
  5299. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  5300. $dummy=array('options'=>$options);
  5301. if(isset($htmlOptions['encode']))
  5302. $dummy['encode']=$htmlOptions['encode'];
  5303. $content.=self::listOptions($selection,$value,$dummy);
  5304. $content.='</optgroup>'."\n";
  5305. }
  5306. else
  5307. {
  5308. $attributes=array('value'=>(string)$key, 'encode'=>!$raw);
  5309. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  5310. $attributes['selected']='selected';
  5311. if(isset($options[$key]))
  5312. $attributes=array_merge($attributes,$options[$key]);
  5313. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  5314. }
  5315. }
  5316. unset($htmlOptions['key']);
  5317. return $content;
  5318. }
  5319. protected static function clientChange($event,&$htmlOptions)
  5320. {
  5321. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  5322. return;
  5323. if(isset($htmlOptions['live']))
  5324. {
  5325. $live=$htmlOptions['live'];
  5326. unset($htmlOptions['live']);
  5327. }
  5328. else
  5329. $live = self::$liveEvents;
  5330. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  5331. $return='return true';
  5332. else
  5333. $return='return false';
  5334. if(isset($htmlOptions['on'.$event]))
  5335. {
  5336. $handler=trim($htmlOptions['on'.$event],';').';';
  5337. unset($htmlOptions['on'.$event]);
  5338. }
  5339. else
  5340. $handler='';
  5341. if(isset($htmlOptions['id']))
  5342. $id=$htmlOptions['id'];
  5343. else
  5344. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  5345. $cs=Yii::app()->getClientScript();
  5346. $cs->registerCoreScript('jquery');
  5347. if(isset($htmlOptions['submit']))
  5348. {
  5349. $cs->registerCoreScript('yii');
  5350. $request=Yii::app()->getRequest();
  5351. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  5352. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  5353. if(isset($htmlOptions['params']))
  5354. $params=CJavaScript::encode($htmlOptions['params']);
  5355. else
  5356. $params='{}';
  5357. if($htmlOptions['submit']!=='')
  5358. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  5359. else
  5360. $url='';
  5361. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  5362. }
  5363. if(isset($htmlOptions['ajax']))
  5364. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  5365. if(isset($htmlOptions['confirm']))
  5366. {
  5367. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  5368. if($handler!=='')
  5369. $handler="if($confirm) {".$handler."} else return false;";
  5370. else
  5371. $handler="return $confirm;";
  5372. }
  5373. if($live)
  5374. $cs->registerScript('Yii.CHtml.#' . $id, "$('body').on('$event','#$id',function(){{$handler}});");
  5375. else
  5376. $cs->registerScript('Yii.CHtml.#' . $id, "$('#$id').on('$event', function(){{$handler}});");
  5377. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  5378. }
  5379. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  5380. {
  5381. if(!isset($htmlOptions['name']))
  5382. $htmlOptions['name']=self::resolveName($model,$attribute);
  5383. if(!isset($htmlOptions['id']))
  5384. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  5385. else if($htmlOptions['id']===false)
  5386. unset($htmlOptions['id']);
  5387. }
  5388. public static function resolveName($model,&$attribute)
  5389. {
  5390. if(($pos=strpos($attribute,'['))!==false)
  5391. {
  5392. if($pos!==0) // e.g. name[a][b]
  5393. return get_class($model).'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5394. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5395. {
  5396. $sub=substr($attribute,0,$pos+1);
  5397. $attribute=substr($attribute,$pos+1);
  5398. return get_class($model).$sub.'['.$attribute.']';
  5399. }
  5400. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5401. {
  5402. $name=get_class($model).'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5403. $attribute=$matches[1];
  5404. return $name;
  5405. }
  5406. }
  5407. return get_class($model).'['.$attribute.']';
  5408. }
  5409. public static function resolveValue($model,$attribute)
  5410. {
  5411. if(($pos=strpos($attribute,'['))!==false)
  5412. {
  5413. if($pos===0) // [a]name[b][c], should ignore [a]
  5414. {
  5415. if(preg_match('/\](.*)/',$attribute,$matches))
  5416. $attribute=$matches[1];
  5417. if(($pos=strpos($attribute,'['))===false)
  5418. return $model->$attribute;
  5419. }
  5420. $name=substr($attribute,0,$pos);
  5421. $value=$model->$name;
  5422. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5423. {
  5424. if((is_array($value) || $value instanceof ArrayAccess) && isset($value[$id]))
  5425. $value=$value[$id];
  5426. else
  5427. return null;
  5428. }
  5429. return $value;
  5430. }
  5431. else
  5432. return $model->$attribute;
  5433. }
  5434. protected static function addErrorCss(&$htmlOptions)
  5435. {
  5436. if(isset($htmlOptions['class']))
  5437. $htmlOptions['class'].=' '.self::$errorCss;
  5438. else
  5439. $htmlOptions['class']=self::$errorCss;
  5440. }
  5441. public static function renderAttributes($htmlOptions)
  5442. {
  5443. static $specialAttributes=array(
  5444. 'checked'=>1,
  5445. 'declare'=>1,
  5446. 'defer'=>1,
  5447. 'disabled'=>1,
  5448. 'ismap'=>1,
  5449. 'multiple'=>1,
  5450. 'nohref'=>1,
  5451. 'noresize'=>1,
  5452. 'readonly'=>1,
  5453. 'selected'=>1,
  5454. );
  5455. if($htmlOptions===array())
  5456. return '';
  5457. $html='';
  5458. if(isset($htmlOptions['encode']))
  5459. {
  5460. $raw=!$htmlOptions['encode'];
  5461. unset($htmlOptions['encode']);
  5462. }
  5463. else
  5464. $raw=false;
  5465. foreach($htmlOptions as $name=>$value)
  5466. {
  5467. if(isset($specialAttributes[$name]))
  5468. {
  5469. if($value)
  5470. $html .= ' ' . $name . '="' . $name . '"';
  5471. }
  5472. else if($value!==null)
  5473. $html .= ' ' . $name . '="' . ($raw ? $value : self::encode($value)) . '"';
  5474. }
  5475. return $html;
  5476. }
  5477. }
  5478. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  5479. {
  5480. public $enableSkin=false;
  5481. public $widgets=array();
  5482. public $skinnableWidgets;
  5483. public $skinPath;
  5484. private $_skins=array(); // class name, skin name, property name => value
  5485. public function init()
  5486. {
  5487. parent::init();
  5488. if($this->enableSkin && $this->skinPath===null)
  5489. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  5490. }
  5491. public function createWidget($owner,$className,$properties=array())
  5492. {
  5493. $className=Yii::import($className,true);
  5494. $widget=new $className($owner);
  5495. if(isset($this->widgets[$className]))
  5496. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  5497. if($this->enableSkin)
  5498. {
  5499. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  5500. {
  5501. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  5502. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  5503. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  5504. }
  5505. }
  5506. foreach($properties as $name=>$value)
  5507. $widget->$name=$value;
  5508. return $widget;
  5509. }
  5510. protected function getSkin($className,$skinName)
  5511. {
  5512. if(!isset($this->_skins[$className][$skinName]))
  5513. {
  5514. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  5515. if(is_file($skinFile))
  5516. $this->_skins[$className]=require($skinFile);
  5517. else
  5518. $this->_skins[$className]=array();
  5519. if(($theme=Yii::app()->getTheme())!==null)
  5520. {
  5521. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  5522. if(is_file($skinFile))
  5523. {
  5524. $skins=require($skinFile);
  5525. foreach($skins as $name=>$skin)
  5526. $this->_skins[$className][$name]=$skin;
  5527. }
  5528. }
  5529. if(!isset($this->_skins[$className][$skinName]))
  5530. $this->_skins[$className][$skinName]=array();
  5531. }
  5532. return $this->_skins[$className][$skinName];
  5533. }
  5534. }
  5535. class CWidget extends CBaseController
  5536. {
  5537. public $actionPrefix;
  5538. public $skin='default';
  5539. private static $_viewPaths;
  5540. private static $_counter=0;
  5541. private $_id;
  5542. private $_owner;
  5543. public static function actions()
  5544. {
  5545. return array();
  5546. }
  5547. public function __construct($owner=null)
  5548. {
  5549. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  5550. }
  5551. public function getOwner()
  5552. {
  5553. return $this->_owner;
  5554. }
  5555. public function getId($autoGenerate=true)
  5556. {
  5557. if($this->_id!==null)
  5558. return $this->_id;
  5559. else if($autoGenerate)
  5560. return $this->_id='yw'.self::$_counter++;
  5561. }
  5562. public function setId($value)
  5563. {
  5564. $this->_id=$value;
  5565. }
  5566. public function getController()
  5567. {
  5568. if($this->_owner instanceof CController)
  5569. return $this->_owner;
  5570. else
  5571. return Yii::app()->getController();
  5572. }
  5573. public function init()
  5574. {
  5575. }
  5576. public function run()
  5577. {
  5578. }
  5579. public function getViewPath($checkTheme=false)
  5580. {
  5581. $className=get_class($this);
  5582. if(isset(self::$_viewPaths[$className]))
  5583. return self::$_viewPaths[$className];
  5584. else
  5585. {
  5586. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  5587. {
  5588. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  5589. if(strpos($className,'\\')!==false) // namespaced class
  5590. $path.=str_replace('\\','_',ltrim($className,'\\'));
  5591. else
  5592. $path.=$className;
  5593. if(is_dir($path))
  5594. return self::$_viewPaths[$className]=$path;
  5595. }
  5596. $class=new ReflectionClass($className);
  5597. return self::$_viewPaths[$className]=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  5598. }
  5599. }
  5600. public function getViewFile($viewName)
  5601. {
  5602. if(($renderer=Yii::app()->getViewRenderer())!==null)
  5603. $extension=$renderer->fileExtension;
  5604. else
  5605. $extension='.php';
  5606. if(strpos($viewName,'.')) // a path alias
  5607. $viewFile=Yii::getPathOfAlias($viewName);
  5608. else
  5609. {
  5610. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  5611. if(is_file($viewFile.$extension))
  5612. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5613. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5614. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5615. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  5616. }
  5617. if(is_file($viewFile.$extension))
  5618. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5619. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5620. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5621. else
  5622. return false;
  5623. }
  5624. public function render($view,$data=null,$return=false)
  5625. {
  5626. if(($viewFile=$this->getViewFile($view))!==false)
  5627. return $this->renderFile($viewFile,$data,$return);
  5628. else
  5629. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  5630. array('{widget}'=>get_class($this), '{view}'=>$view)));
  5631. }
  5632. }
  5633. class CClientScript extends CApplicationComponent
  5634. {
  5635. const POS_HEAD=0;
  5636. const POS_BEGIN=1;
  5637. const POS_END=2;
  5638. const POS_LOAD=3;
  5639. const POS_READY=4;
  5640. public $enableJavaScript=true;
  5641. public $scriptMap=array();
  5642. public $packages=array();
  5643. public $corePackages;
  5644. public $scripts=array();
  5645. protected $cssFiles=array();
  5646. protected $scriptFiles=array();
  5647. protected $metaTags=array();
  5648. protected $linkTags=array();
  5649. protected $css=array();
  5650. protected $hasScripts=false;
  5651. protected $coreScripts=array();
  5652. public $coreScriptPosition=self::POS_HEAD;
  5653. public $defaultScriptFilePosition=self::POS_HEAD;
  5654. public $defaultScriptPosition=self::POS_READY;
  5655. private $_baseUrl;
  5656. public function reset()
  5657. {
  5658. $this->hasScripts=false;
  5659. $this->coreScripts=array();
  5660. $this->cssFiles=array();
  5661. $this->css=array();
  5662. $this->scriptFiles=array();
  5663. $this->scripts=array();
  5664. $this->metaTags=array();
  5665. $this->linkTags=array();
  5666. $this->recordCachingAction('clientScript','reset',array());
  5667. }
  5668. public function render(&$output)
  5669. {
  5670. if(!$this->hasScripts)
  5671. return;
  5672. $this->renderCoreScripts();
  5673. if(!empty($this->scriptMap))
  5674. $this->remapScripts();
  5675. $this->unifyScripts();
  5676. $this->renderHead($output);
  5677. if($this->enableJavaScript)
  5678. {
  5679. $this->renderBodyBegin($output);
  5680. $this->renderBodyEnd($output);
  5681. }
  5682. }
  5683. protected function unifyScripts()
  5684. {
  5685. if(!$this->enableJavaScript)
  5686. return;
  5687. $map=array();
  5688. if(isset($this->scriptFiles[self::POS_HEAD]))
  5689. $map=$this->scriptFiles[self::POS_HEAD];
  5690. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5691. {
  5692. foreach($this->scriptFiles[self::POS_BEGIN] as $key=>$scriptFile)
  5693. {
  5694. if(isset($map[$scriptFile]))
  5695. unset($this->scriptFiles[self::POS_BEGIN][$key]);
  5696. else
  5697. $map[$scriptFile]=true;
  5698. }
  5699. }
  5700. if(isset($this->scriptFiles[self::POS_END]))
  5701. {
  5702. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  5703. {
  5704. if(isset($map[$scriptFile]))
  5705. unset($this->scriptFiles[self::POS_END][$key]);
  5706. }
  5707. }
  5708. }
  5709. protected function remapScripts()
  5710. {
  5711. $cssFiles=array();
  5712. foreach($this->cssFiles as $url=>$media)
  5713. {
  5714. $name=basename($url);
  5715. if(isset($this->scriptMap[$name]))
  5716. {
  5717. if($this->scriptMap[$name]!==false)
  5718. $cssFiles[$this->scriptMap[$name]]=$media;
  5719. }
  5720. else if(isset($this->scriptMap['*.css']))
  5721. {
  5722. if($this->scriptMap['*.css']!==false)
  5723. $cssFiles[$this->scriptMap['*.css']]=$media;
  5724. }
  5725. else
  5726. $cssFiles[$url]=$media;
  5727. }
  5728. $this->cssFiles=$cssFiles;
  5729. $jsFiles=array();
  5730. foreach($this->scriptFiles as $position=>$scripts)
  5731. {
  5732. $jsFiles[$position]=array();
  5733. foreach($scripts as $key=>$script)
  5734. {
  5735. $name=basename($script);
  5736. if(isset($this->scriptMap[$name]))
  5737. {
  5738. if($this->scriptMap[$name]!==false)
  5739. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  5740. }
  5741. else if(isset($this->scriptMap['*.js']))
  5742. {
  5743. if($this->scriptMap['*.js']!==false)
  5744. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  5745. }
  5746. else
  5747. $jsFiles[$position][$key]=$script;
  5748. }
  5749. }
  5750. $this->scriptFiles=$jsFiles;
  5751. }
  5752. public function renderCoreScripts()
  5753. {
  5754. if($this->coreScripts===null)
  5755. return;
  5756. $cssFiles=array();
  5757. $jsFiles=array();
  5758. foreach($this->coreScripts as $name=>$package)
  5759. {
  5760. $baseUrl=$this->getPackageBaseUrl($name);
  5761. if(!empty($package['js']))
  5762. {
  5763. foreach($package['js'] as $js)
  5764. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  5765. }
  5766. if(!empty($package['css']))
  5767. {
  5768. foreach($package['css'] as $css)
  5769. $cssFiles[$baseUrl.'/'.$css]='';
  5770. }
  5771. }
  5772. // merge in place
  5773. if($cssFiles!==array())
  5774. {
  5775. foreach($this->cssFiles as $cssFile=>$media)
  5776. $cssFiles[$cssFile]=$media;
  5777. $this->cssFiles=$cssFiles;
  5778. }
  5779. if($jsFiles!==array())
  5780. {
  5781. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  5782. {
  5783. foreach($this->scriptFiles[$this->coreScriptPosition] as $url)
  5784. $jsFiles[$url]=$url;
  5785. }
  5786. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  5787. }
  5788. }
  5789. public function renderHead(&$output)
  5790. {
  5791. $html='';
  5792. foreach($this->metaTags as $meta)
  5793. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  5794. foreach($this->linkTags as $link)
  5795. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  5796. foreach($this->cssFiles as $url=>$media)
  5797. $html.=CHtml::cssFile($url,$media)."\n";
  5798. foreach($this->css as $css)
  5799. $html.=CHtml::css($css[0],$css[1])."\n";
  5800. if($this->enableJavaScript)
  5801. {
  5802. if(isset($this->scriptFiles[self::POS_HEAD]))
  5803. {
  5804. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFile)
  5805. $html.=CHtml::scriptFile($scriptFile)."\n";
  5806. }
  5807. if(isset($this->scripts[self::POS_HEAD]))
  5808. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_HEAD]))."\n";
  5809. }
  5810. if($html!=='')
  5811. {
  5812. $count=0;
  5813. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  5814. if($count)
  5815. $output=str_replace('<###head###>',$html,$output);
  5816. else
  5817. $output=$html.$output;
  5818. }
  5819. }
  5820. public function renderBodyBegin(&$output)
  5821. {
  5822. $html='';
  5823. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5824. {
  5825. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile)
  5826. $html.=CHtml::scriptFile($scriptFile)."\n";
  5827. }
  5828. if(isset($this->scripts[self::POS_BEGIN]))
  5829. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_BEGIN]))."\n";
  5830. if($html!=='')
  5831. {
  5832. $count=0;
  5833. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  5834. if($count)
  5835. $output=str_replace('<###begin###>',$html,$output);
  5836. else
  5837. $output=$html.$output;
  5838. }
  5839. }
  5840. public function renderBodyEnd(&$output)
  5841. {
  5842. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  5843. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  5844. return;
  5845. $fullPage=0;
  5846. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  5847. $html='';
  5848. if(isset($this->scriptFiles[self::POS_END]))
  5849. {
  5850. foreach($this->scriptFiles[self::POS_END] as $scriptFile)
  5851. $html.=CHtml::scriptFile($scriptFile)."\n";
  5852. }
  5853. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  5854. if(isset($this->scripts[self::POS_READY]))
  5855. {
  5856. if($fullPage)
  5857. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  5858. else
  5859. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  5860. }
  5861. if(isset($this->scripts[self::POS_LOAD]))
  5862. {
  5863. if($fullPage)
  5864. $scripts[]="jQuery(window).load(function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  5865. else
  5866. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  5867. }
  5868. if(!empty($scripts))
  5869. $html.=CHtml::script(implode("\n",$scripts))."\n";
  5870. if($fullPage)
  5871. $output=str_replace('<###end###>',$html,$output);
  5872. else
  5873. $output=$output.$html;
  5874. }
  5875. public function getCoreScriptUrl()
  5876. {
  5877. if($this->_baseUrl!==null)
  5878. return $this->_baseUrl;
  5879. else
  5880. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  5881. }
  5882. public function setCoreScriptUrl($value)
  5883. {
  5884. $this->_baseUrl=$value;
  5885. }
  5886. public function getPackageBaseUrl($name)
  5887. {
  5888. if(!isset($this->coreScripts[$name]))
  5889. return false;
  5890. $package=$this->coreScripts[$name];
  5891. if(isset($package['baseUrl']))
  5892. {
  5893. $baseUrl=$package['baseUrl'];
  5894. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  5895. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  5896. $baseUrl=rtrim($baseUrl,'/');
  5897. }
  5898. else if(isset($package['basePath']))
  5899. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  5900. else
  5901. $baseUrl=$this->getCoreScriptUrl();
  5902. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  5903. }
  5904. public function registerPackage($name)
  5905. {
  5906. return $this->registerCoreScript($name);
  5907. }
  5908. public function registerCoreScript($name)
  5909. {
  5910. if(isset($this->coreScripts[$name]))
  5911. return $this;
  5912. if(isset($this->packages[$name]))
  5913. $package=$this->packages[$name];
  5914. else
  5915. {
  5916. if($this->corePackages===null)
  5917. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  5918. if(isset($this->corePackages[$name]))
  5919. $package=$this->corePackages[$name];
  5920. }
  5921. if(isset($package))
  5922. {
  5923. if(!empty($package['depends']))
  5924. {
  5925. foreach($package['depends'] as $p)
  5926. $this->registerCoreScript($p);
  5927. }
  5928. $this->coreScripts[$name]=$package;
  5929. $this->hasScripts=true;
  5930. $params=func_get_args();
  5931. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  5932. }
  5933. return $this;
  5934. }
  5935. public function registerCssFile($url,$media='')
  5936. {
  5937. $this->hasScripts=true;
  5938. $this->cssFiles[$url]=$media;
  5939. $params=func_get_args();
  5940. $this->recordCachingAction('clientScript','registerCssFile',$params);
  5941. return $this;
  5942. }
  5943. public function registerCss($id,$css,$media='')
  5944. {
  5945. $this->hasScripts=true;
  5946. $this->css[$id]=array($css,$media);
  5947. $params=func_get_args();
  5948. $this->recordCachingAction('clientScript','registerCss',$params);
  5949. return $this;
  5950. }
  5951. public function registerScriptFile($url,$position=null)
  5952. {
  5953. if($position===null)
  5954. $position=$this->defaultScriptFilePosition;
  5955. $this->hasScripts=true;
  5956. $this->scriptFiles[$position][$url]=$url;
  5957. $params=func_get_args();
  5958. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  5959. return $this;
  5960. }
  5961. public function registerScript($id,$script,$position=null)
  5962. {
  5963. if($position===null)
  5964. $position=$this->defaultScriptPosition;
  5965. $this->hasScripts=true;
  5966. $this->scripts[$position][$id]=$script;
  5967. if($position===self::POS_READY || $position===self::POS_LOAD)
  5968. $this->registerCoreScript('jquery');
  5969. $params=func_get_args();
  5970. $this->recordCachingAction('clientScript','registerScript',$params);
  5971. return $this;
  5972. }
  5973. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array())
  5974. {
  5975. $this->hasScripts=true;
  5976. if($name!==null)
  5977. $options['name']=$name;
  5978. if($httpEquiv!==null)
  5979. $options['http-equiv']=$httpEquiv;
  5980. $options['content']=$content;
  5981. $this->metaTags[serialize($options)]=$options;
  5982. $params=func_get_args();
  5983. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  5984. return $this;
  5985. }
  5986. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  5987. {
  5988. $this->hasScripts=true;
  5989. if($relation!==null)
  5990. $options['rel']=$relation;
  5991. if($type!==null)
  5992. $options['type']=$type;
  5993. if($href!==null)
  5994. $options['href']=$href;
  5995. if($media!==null)
  5996. $options['media']=$media;
  5997. $this->linkTags[serialize($options)]=$options;
  5998. $params=func_get_args();
  5999. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  6000. return $this;
  6001. }
  6002. public function isCssFileRegistered($url)
  6003. {
  6004. return isset($this->cssFiles[$url]);
  6005. }
  6006. public function isCssRegistered($id)
  6007. {
  6008. return isset($this->css[$id]);
  6009. }
  6010. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  6011. {
  6012. return isset($this->scriptFiles[$position][$url]);
  6013. }
  6014. public function isScriptRegistered($id,$position=self::POS_READY)
  6015. {
  6016. return isset($this->scripts[$position][$id]);
  6017. }
  6018. protected function recordCachingAction($context,$method,$params)
  6019. {
  6020. if(($controller=Yii::app()->getController())!==null)
  6021. $controller->recordCachingAction($context,$method,$params);
  6022. }
  6023. public function addPackage($name,$definition)
  6024. {
  6025. $this->packages[$name]=$definition;
  6026. return $this;
  6027. }
  6028. }
  6029. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  6030. {
  6031. private $_d=array();
  6032. private $_c=0;
  6033. private $_r=false;
  6034. public function __construct($data=null,$readOnly=false)
  6035. {
  6036. if($data!==null)
  6037. $this->copyFrom($data);
  6038. $this->setReadOnly($readOnly);
  6039. }
  6040. public function getReadOnly()
  6041. {
  6042. return $this->_r;
  6043. }
  6044. protected function setReadOnly($value)
  6045. {
  6046. $this->_r=$value;
  6047. }
  6048. public function getIterator()
  6049. {
  6050. return new CListIterator($this->_d);
  6051. }
  6052. public function count()
  6053. {
  6054. return $this->getCount();
  6055. }
  6056. public function getCount()
  6057. {
  6058. return $this->_c;
  6059. }
  6060. public function itemAt($index)
  6061. {
  6062. if(isset($this->_d[$index]))
  6063. return $this->_d[$index];
  6064. else if($index>=0 && $index<$this->_c) // in case the value is null
  6065. return $this->_d[$index];
  6066. else
  6067. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6068. array('{index}'=>$index)));
  6069. }
  6070. public function add($item)
  6071. {
  6072. $this->insertAt($this->_c,$item);
  6073. return $this->_c-1;
  6074. }
  6075. public function insertAt($index,$item)
  6076. {
  6077. if(!$this->_r)
  6078. {
  6079. if($index===$this->_c)
  6080. $this->_d[$this->_c++]=$item;
  6081. else if($index>=0 && $index<$this->_c)
  6082. {
  6083. array_splice($this->_d,$index,0,array($item));
  6084. $this->_c++;
  6085. }
  6086. else
  6087. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6088. array('{index}'=>$index)));
  6089. }
  6090. else
  6091. throw new CException(Yii::t('yii','The list is read only.'));
  6092. }
  6093. public function remove($item)
  6094. {
  6095. if(($index=$this->indexOf($item))>=0)
  6096. {
  6097. $this->removeAt($index);
  6098. return $index;
  6099. }
  6100. else
  6101. return false;
  6102. }
  6103. public function removeAt($index)
  6104. {
  6105. if(!$this->_r)
  6106. {
  6107. if($index>=0 && $index<$this->_c)
  6108. {
  6109. $this->_c--;
  6110. if($index===$this->_c)
  6111. return array_pop($this->_d);
  6112. else
  6113. {
  6114. $item=$this->_d[$index];
  6115. array_splice($this->_d,$index,1);
  6116. return $item;
  6117. }
  6118. }
  6119. else
  6120. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6121. array('{index}'=>$index)));
  6122. }
  6123. else
  6124. throw new CException(Yii::t('yii','The list is read only.'));
  6125. }
  6126. public function clear()
  6127. {
  6128. for($i=$this->_c-1;$i>=0;--$i)
  6129. $this->removeAt($i);
  6130. }
  6131. public function contains($item)
  6132. {
  6133. return $this->indexOf($item)>=0;
  6134. }
  6135. public function indexOf($item)
  6136. {
  6137. if(($index=array_search($item,$this->_d,true))!==false)
  6138. return $index;
  6139. else
  6140. return -1;
  6141. }
  6142. public function toArray()
  6143. {
  6144. return $this->_d;
  6145. }
  6146. public function copyFrom($data)
  6147. {
  6148. if(is_array($data) || ($data instanceof Traversable))
  6149. {
  6150. if($this->_c>0)
  6151. $this->clear();
  6152. if($data instanceof CList)
  6153. $data=$data->_d;
  6154. foreach($data as $item)
  6155. $this->add($item);
  6156. }
  6157. else if($data!==null)
  6158. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6159. }
  6160. public function mergeWith($data)
  6161. {
  6162. if(is_array($data) || ($data instanceof Traversable))
  6163. {
  6164. if($data instanceof CList)
  6165. $data=$data->_d;
  6166. foreach($data as $item)
  6167. $this->add($item);
  6168. }
  6169. else if($data!==null)
  6170. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6171. }
  6172. public function offsetExists($offset)
  6173. {
  6174. return ($offset>=0 && $offset<$this->_c);
  6175. }
  6176. public function offsetGet($offset)
  6177. {
  6178. return $this->itemAt($offset);
  6179. }
  6180. public function offsetSet($offset,$item)
  6181. {
  6182. if($offset===null || $offset===$this->_c)
  6183. $this->insertAt($this->_c,$item);
  6184. else
  6185. {
  6186. $this->removeAt($offset);
  6187. $this->insertAt($offset,$item);
  6188. }
  6189. }
  6190. public function offsetUnset($offset)
  6191. {
  6192. $this->removeAt($offset);
  6193. }
  6194. }
  6195. class CFilterChain extends CList
  6196. {
  6197. public $controller;
  6198. public $action;
  6199. public $filterIndex=0;
  6200. public function __construct($controller,$action)
  6201. {
  6202. $this->controller=$controller;
  6203. $this->action=$action;
  6204. }
  6205. public static function create($controller,$action,$filters)
  6206. {
  6207. $chain=new CFilterChain($controller,$action);
  6208. $actionID=$action->getId();
  6209. foreach($filters as $filter)
  6210. {
  6211. if(is_string($filter)) // filterName [+|- action1 action2]
  6212. {
  6213. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  6214. {
  6215. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  6216. if(($filter[$pos]==='+')===$matched)
  6217. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  6218. }
  6219. else
  6220. $filter=CInlineFilter::create($controller,$filter);
  6221. }
  6222. else if(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  6223. {
  6224. if(!isset($filter[0]))
  6225. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  6226. $filterClass=$filter[0];
  6227. unset($filter[0]);
  6228. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  6229. {
  6230. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  6231. if(($filterClass[$pos]==='+')===$matched)
  6232. $filterClass=trim(substr($filterClass,0,$pos));
  6233. else
  6234. continue;
  6235. }
  6236. $filter['class']=$filterClass;
  6237. $filter=Yii::createComponent($filter);
  6238. }
  6239. if(is_object($filter))
  6240. {
  6241. $filter->init();
  6242. $chain->add($filter);
  6243. }
  6244. }
  6245. return $chain;
  6246. }
  6247. public function insertAt($index,$item)
  6248. {
  6249. if($item instanceof IFilter)
  6250. parent::insertAt($index,$item);
  6251. else
  6252. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  6253. }
  6254. public function run()
  6255. {
  6256. if($this->offsetExists($this->filterIndex))
  6257. {
  6258. $filter=$this->itemAt($this->filterIndex++);
  6259. $filter->filter($this);
  6260. }
  6261. else
  6262. $this->controller->runAction($this->action);
  6263. }
  6264. }
  6265. class CFilter extends CComponent implements IFilter
  6266. {
  6267. public function filter($filterChain)
  6268. {
  6269. if($this->preFilter($filterChain))
  6270. {
  6271. $filterChain->run();
  6272. $this->postFilter($filterChain);
  6273. }
  6274. }
  6275. public function init()
  6276. {
  6277. }
  6278. protected function preFilter($filterChain)
  6279. {
  6280. return true;
  6281. }
  6282. protected function postFilter($filterChain)
  6283. {
  6284. }
  6285. }
  6286. class CInlineFilter extends CFilter
  6287. {
  6288. public $name;
  6289. public static function create($controller,$filterName)
  6290. {
  6291. if(method_exists($controller,'filter'.$filterName))
  6292. {
  6293. $filter=new CInlineFilter;
  6294. $filter->name=$filterName;
  6295. return $filter;
  6296. }
  6297. else
  6298. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  6299. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  6300. }
  6301. public function filter($filterChain)
  6302. {
  6303. $method='filter'.$this->name;
  6304. $filterChain->controller->$method($filterChain);
  6305. }
  6306. }
  6307. class CAccessControlFilter extends CFilter
  6308. {
  6309. public $message;
  6310. private $_rules=array();
  6311. public function getRules()
  6312. {
  6313. return $this->_rules;
  6314. }
  6315. public function setRules($rules)
  6316. {
  6317. foreach($rules as $rule)
  6318. {
  6319. if(is_array($rule) && isset($rule[0]))
  6320. {
  6321. $r=new CAccessRule;
  6322. $r->allow=$rule[0]==='allow';
  6323. foreach(array_slice($rule,1) as $name=>$value)
  6324. {
  6325. if($name==='expression' || $name==='roles' || $name==='message' || $name==='deniedCallback')
  6326. $r->$name=$value;
  6327. else
  6328. $r->$name=array_map('strtolower',$value);
  6329. }
  6330. $this->_rules[]=$r;
  6331. }
  6332. }
  6333. }
  6334. protected function preFilter($filterChain)
  6335. {
  6336. $app=Yii::app();
  6337. $request=$app->getRequest();
  6338. $user=$app->getUser();
  6339. $verb=$request->getRequestType();
  6340. $ip=$request->getUserHostAddress();
  6341. foreach($this->getRules() as $rule)
  6342. {
  6343. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  6344. break;
  6345. else if($allow<0) // denied
  6346. {
  6347. if(isset($rule->deniedCallback))
  6348. call_user_func($rule->deniedCallback, $rule);
  6349. else
  6350. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  6351. return false;
  6352. }
  6353. }
  6354. return true;
  6355. }
  6356. protected function resolveErrorMessage($rule)
  6357. {
  6358. if($rule->message!==null)
  6359. return $rule->message;
  6360. else if($this->message!==null)
  6361. return $this->message;
  6362. else
  6363. return Yii::t('yii','You are not authorized to perform this action.');
  6364. }
  6365. protected function accessDenied($user,$message)
  6366. {
  6367. if($user->getIsGuest())
  6368. $user->loginRequired();
  6369. else
  6370. throw new CHttpException(403,$message);
  6371. }
  6372. }
  6373. class CAccessRule extends CComponent
  6374. {
  6375. public $allow;
  6376. public $actions;
  6377. public $controllers;
  6378. public $users;
  6379. public $roles;
  6380. public $ips;
  6381. public $verbs;
  6382. public $expression;
  6383. public $message;
  6384. public $deniedCallback;
  6385. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  6386. {
  6387. if($this->isActionMatched($action)
  6388. && $this->isUserMatched($user)
  6389. && $this->isRoleMatched($user)
  6390. && $this->isIpMatched($ip)
  6391. && $this->isVerbMatched($verb)
  6392. && $this->isControllerMatched($controller)
  6393. && $this->isExpressionMatched($user))
  6394. return $this->allow ? 1 : -1;
  6395. else
  6396. return 0;
  6397. }
  6398. protected function isActionMatched($action)
  6399. {
  6400. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  6401. }
  6402. protected function isControllerMatched($controller)
  6403. {
  6404. return empty($this->controllers) || in_array(strtolower($controller->getId()),$this->controllers);
  6405. }
  6406. protected function isUserMatched($user)
  6407. {
  6408. if(empty($this->users))
  6409. return true;
  6410. foreach($this->users as $u)
  6411. {
  6412. if($u==='*')
  6413. return true;
  6414. else if($u==='?' && $user->getIsGuest())
  6415. return true;
  6416. else if($u==='@' && !$user->getIsGuest())
  6417. return true;
  6418. else if(!strcasecmp($u,$user->getName()))
  6419. return true;
  6420. }
  6421. return false;
  6422. }
  6423. protected function isRoleMatched($user)
  6424. {
  6425. if(empty($this->roles))
  6426. return true;
  6427. foreach($this->roles as $key=>$role)
  6428. {
  6429. if(is_numeric($key))
  6430. {
  6431. if($user->checkAccess($role))
  6432. return true;
  6433. }
  6434. else
  6435. {
  6436. if($user->checkAccess($key,$role))
  6437. return true;
  6438. }
  6439. }
  6440. return false;
  6441. }
  6442. protected function isIpMatched($ip)
  6443. {
  6444. if(empty($this->ips))
  6445. return true;
  6446. foreach($this->ips as $rule)
  6447. {
  6448. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  6449. return true;
  6450. }
  6451. return false;
  6452. }
  6453. protected function isVerbMatched($verb)
  6454. {
  6455. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  6456. }
  6457. protected function isExpressionMatched($user)
  6458. {
  6459. if($this->expression===null)
  6460. return true;
  6461. else
  6462. return $this->evaluateExpression($this->expression, array('user'=>$user));
  6463. }
  6464. }
  6465. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  6466. {
  6467. private $_errors=array(); // attribute name => array of errors
  6468. private $_validators; // validators
  6469. private $_scenario=''; // scenario
  6470. abstract public function attributeNames();
  6471. public function rules()
  6472. {
  6473. return array();
  6474. }
  6475. public function behaviors()
  6476. {
  6477. return array();
  6478. }
  6479. public function attributeLabels()
  6480. {
  6481. return array();
  6482. }
  6483. public function validate($attributes=null, $clearErrors=true)
  6484. {
  6485. if($clearErrors)
  6486. $this->clearErrors();
  6487. if($this->beforeValidate())
  6488. {
  6489. foreach($this->getValidators() as $validator)
  6490. $validator->validate($this,$attributes);
  6491. $this->afterValidate();
  6492. return !$this->hasErrors();
  6493. }
  6494. else
  6495. return false;
  6496. }
  6497. protected function afterConstruct()
  6498. {
  6499. if($this->hasEventHandler('onAfterConstruct'))
  6500. $this->onAfterConstruct(new CEvent($this));
  6501. }
  6502. protected function beforeValidate()
  6503. {
  6504. $event=new CModelEvent($this);
  6505. $this->onBeforeValidate($event);
  6506. return $event->isValid;
  6507. }
  6508. protected function afterValidate()
  6509. {
  6510. $this->onAfterValidate(new CEvent($this));
  6511. }
  6512. public function onAfterConstruct($event)
  6513. {
  6514. $this->raiseEvent('onAfterConstruct',$event);
  6515. }
  6516. public function onBeforeValidate($event)
  6517. {
  6518. $this->raiseEvent('onBeforeValidate',$event);
  6519. }
  6520. public function onAfterValidate($event)
  6521. {
  6522. $this->raiseEvent('onAfterValidate',$event);
  6523. }
  6524. public function getValidatorList()
  6525. {
  6526. if($this->_validators===null)
  6527. $this->_validators=$this->createValidators();
  6528. return $this->_validators;
  6529. }
  6530. public function getValidators($attribute=null)
  6531. {
  6532. if($this->_validators===null)
  6533. $this->_validators=$this->createValidators();
  6534. $validators=array();
  6535. $scenario=$this->getScenario();
  6536. foreach($this->_validators as $validator)
  6537. {
  6538. if($validator->applyTo($scenario))
  6539. {
  6540. if($attribute===null || in_array($attribute,$validator->attributes,true))
  6541. $validators[]=$validator;
  6542. }
  6543. }
  6544. return $validators;
  6545. }
  6546. public function createValidators()
  6547. {
  6548. $validators=new CList;
  6549. foreach($this->rules() as $rule)
  6550. {
  6551. if(isset($rule[0],$rule[1])) // attributes, validator name
  6552. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  6553. else
  6554. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  6555. array('{class}'=>get_class($this))));
  6556. }
  6557. return $validators;
  6558. }
  6559. public function isAttributeRequired($attribute)
  6560. {
  6561. foreach($this->getValidators($attribute) as $validator)
  6562. {
  6563. if($validator instanceof CRequiredValidator)
  6564. return true;
  6565. }
  6566. return false;
  6567. }
  6568. public function isAttributeSafe($attribute)
  6569. {
  6570. $attributes=$this->getSafeAttributeNames();
  6571. return in_array($attribute,$attributes);
  6572. }
  6573. public function getAttributeLabel($attribute)
  6574. {
  6575. $labels=$this->attributeLabels();
  6576. if(isset($labels[$attribute]))
  6577. return $labels[$attribute];
  6578. else
  6579. return $this->generateAttributeLabel($attribute);
  6580. }
  6581. public function hasErrors($attribute=null)
  6582. {
  6583. if($attribute===null)
  6584. return $this->_errors!==array();
  6585. else
  6586. return isset($this->_errors[$attribute]);
  6587. }
  6588. public function getErrors($attribute=null)
  6589. {
  6590. if($attribute===null)
  6591. return $this->_errors;
  6592. else
  6593. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  6594. }
  6595. public function getError($attribute)
  6596. {
  6597. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  6598. }
  6599. public function addError($attribute,$error)
  6600. {
  6601. $this->_errors[$attribute][]=$error;
  6602. }
  6603. public function addErrors($errors)
  6604. {
  6605. foreach($errors as $attribute=>$error)
  6606. {
  6607. if(is_array($error))
  6608. {
  6609. foreach($error as $e)
  6610. $this->addError($attribute, $e);
  6611. }
  6612. else
  6613. $this->addError($attribute, $error);
  6614. }
  6615. }
  6616. public function clearErrors($attribute=null)
  6617. {
  6618. if($attribute===null)
  6619. $this->_errors=array();
  6620. else
  6621. unset($this->_errors[$attribute]);
  6622. }
  6623. public function generateAttributeLabel($name)
  6624. {
  6625. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  6626. }
  6627. public function getAttributes($names=null)
  6628. {
  6629. $values=array();
  6630. foreach($this->attributeNames() as $name)
  6631. $values[$name]=$this->$name;
  6632. if(is_array($names))
  6633. {
  6634. $values2=array();
  6635. foreach($names as $name)
  6636. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  6637. return $values2;
  6638. }
  6639. else
  6640. return $values;
  6641. }
  6642. public function setAttributes($values,$safeOnly=true)
  6643. {
  6644. if(!is_array($values))
  6645. return;
  6646. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  6647. foreach($values as $name=>$value)
  6648. {
  6649. if(isset($attributes[$name]))
  6650. $this->$name=$value;
  6651. else if($safeOnly)
  6652. $this->onUnsafeAttribute($name,$value);
  6653. }
  6654. }
  6655. public function unsetAttributes($names=null)
  6656. {
  6657. if($names===null)
  6658. $names=$this->attributeNames();
  6659. foreach($names as $name)
  6660. $this->$name=null;
  6661. }
  6662. public function onUnsafeAttribute($name,$value)
  6663. {
  6664. if(YII_DEBUG)
  6665. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  6666. }
  6667. public function getScenario()
  6668. {
  6669. return $this->_scenario;
  6670. }
  6671. public function setScenario($value)
  6672. {
  6673. $this->_scenario=$value;
  6674. }
  6675. public function getSafeAttributeNames()
  6676. {
  6677. $attributes=array();
  6678. $unsafe=array();
  6679. foreach($this->getValidators() as $validator)
  6680. {
  6681. if(!$validator->safe)
  6682. {
  6683. foreach($validator->attributes as $name)
  6684. $unsafe[]=$name;
  6685. }
  6686. else
  6687. {
  6688. foreach($validator->attributes as $name)
  6689. $attributes[$name]=true;
  6690. }
  6691. }
  6692. foreach($unsafe as $name)
  6693. unset($attributes[$name]);
  6694. return array_keys($attributes);
  6695. }
  6696. public function getIterator()
  6697. {
  6698. $attributes=$this->getAttributes();
  6699. return new CMapIterator($attributes);
  6700. }
  6701. public function offsetExists($offset)
  6702. {
  6703. return property_exists($this,$offset);
  6704. }
  6705. public function offsetGet($offset)
  6706. {
  6707. return $this->$offset;
  6708. }
  6709. public function offsetSet($offset,$item)
  6710. {
  6711. $this->$offset=$item;
  6712. }
  6713. public function offsetUnset($offset)
  6714. {
  6715. unset($this->$offset);
  6716. }
  6717. }
  6718. abstract class CActiveRecord extends CModel
  6719. {
  6720. const BELONGS_TO='CBelongsToRelation';
  6721. const HAS_ONE='CHasOneRelation';
  6722. const HAS_MANY='CHasManyRelation';
  6723. const MANY_MANY='CManyManyRelation';
  6724. const STAT='CStatRelation';
  6725. public static $db;
  6726. private static $_models=array(); // class name => model
  6727. private $_md; // meta data
  6728. private $_new=false; // whether this instance is new or not
  6729. private $_attributes=array(); // attribute name => attribute value
  6730. private $_related=array(); // attribute name => related objects
  6731. private $_c; // query criteria (used by finder only)
  6732. private $_pk; // old primary key value
  6733. private $_alias='t'; // the table alias being used for query
  6734. public function __construct($scenario='insert')
  6735. {
  6736. if($scenario===null) // internally used by populateRecord() and model()
  6737. return;
  6738. $this->setScenario($scenario);
  6739. $this->setIsNewRecord(true);
  6740. $this->_attributes=$this->getMetaData()->attributeDefaults;
  6741. $this->init();
  6742. $this->attachBehaviors($this->behaviors());
  6743. $this->afterConstruct();
  6744. }
  6745. public function init()
  6746. {
  6747. }
  6748. public function cache($duration, $dependency=null, $queryCount=1)
  6749. {
  6750. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  6751. return $this;
  6752. }
  6753. public function __sleep()
  6754. {
  6755. $this->_md=null;
  6756. return array_keys((array)$this);
  6757. }
  6758. public function __get($name)
  6759. {
  6760. if(isset($this->_attributes[$name]))
  6761. return $this->_attributes[$name];
  6762. else if(isset($this->getMetaData()->columns[$name]))
  6763. return null;
  6764. else if(isset($this->_related[$name]))
  6765. return $this->_related[$name];
  6766. else if(isset($this->getMetaData()->relations[$name]))
  6767. return $this->getRelated($name);
  6768. else
  6769. return parent::__get($name);
  6770. }
  6771. public function __set($name,$value)
  6772. {
  6773. if($this->setAttribute($name,$value)===false)
  6774. {
  6775. if(isset($this->getMetaData()->relations[$name]))
  6776. $this->_related[$name]=$value;
  6777. else
  6778. parent::__set($name,$value);
  6779. }
  6780. }
  6781. public function __isset($name)
  6782. {
  6783. if(isset($this->_attributes[$name]))
  6784. return true;
  6785. else if(isset($this->getMetaData()->columns[$name]))
  6786. return false;
  6787. else if(isset($this->_related[$name]))
  6788. return true;
  6789. else if(isset($this->getMetaData()->relations[$name]))
  6790. return $this->getRelated($name)!==null;
  6791. else
  6792. return parent::__isset($name);
  6793. }
  6794. public function __unset($name)
  6795. {
  6796. if(isset($this->getMetaData()->columns[$name]))
  6797. unset($this->_attributes[$name]);
  6798. else if(isset($this->getMetaData()->relations[$name]))
  6799. unset($this->_related[$name]);
  6800. else
  6801. parent::__unset($name);
  6802. }
  6803. public function __call($name,$parameters)
  6804. {
  6805. if(isset($this->getMetaData()->relations[$name]))
  6806. {
  6807. if(empty($parameters))
  6808. return $this->getRelated($name,false);
  6809. else
  6810. return $this->getRelated($name,false,$parameters[0]);
  6811. }
  6812. $scopes=$this->scopes();
  6813. if(isset($scopes[$name]))
  6814. {
  6815. $this->getDbCriteria()->mergeWith($scopes[$name]);
  6816. return $this;
  6817. }
  6818. return parent::__call($name,$parameters);
  6819. }
  6820. public function getRelated($name,$refresh=false,$params=array())
  6821. {
  6822. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  6823. return $this->_related[$name];
  6824. $md=$this->getMetaData();
  6825. if(!isset($md->relations[$name]))
  6826. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  6827. array('{class}'=>get_class($this), '{name}'=>$name)));
  6828. $relation=$md->relations[$name];
  6829. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  6830. return $relation instanceof CHasOneRelation ? null : array();
  6831. if($params!==array()) // dynamic query
  6832. {
  6833. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6834. if($exists)
  6835. $save=$this->_related[$name];
  6836. if($params instanceof CDbCriteria)
  6837. $params = $params->toArray();
  6838. $r=array($name=>$params);
  6839. }
  6840. else
  6841. $r=$name;
  6842. unset($this->_related[$name]);
  6843. $finder=new CActiveFinder($this,$r);
  6844. $finder->lazyFind($this);
  6845. if(!isset($this->_related[$name]))
  6846. {
  6847. if($relation instanceof CHasManyRelation)
  6848. $this->_related[$name]=array();
  6849. else if($relation instanceof CStatRelation)
  6850. $this->_related[$name]=$relation->defaultValue;
  6851. else
  6852. $this->_related[$name]=null;
  6853. }
  6854. if($params!==array())
  6855. {
  6856. $results=$this->_related[$name];
  6857. if($exists)
  6858. $this->_related[$name]=$save;
  6859. else
  6860. unset($this->_related[$name]);
  6861. return $results;
  6862. }
  6863. else
  6864. return $this->_related[$name];
  6865. }
  6866. public function hasRelated($name)
  6867. {
  6868. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6869. }
  6870. public function getDbCriteria($createIfNull=true)
  6871. {
  6872. if($this->_c===null)
  6873. {
  6874. if(($c=$this->defaultScope())!==array() || $createIfNull)
  6875. $this->_c=new CDbCriteria($c);
  6876. }
  6877. return $this->_c;
  6878. }
  6879. public function setDbCriteria($criteria)
  6880. {
  6881. $this->_c=$criteria;
  6882. }
  6883. public function defaultScope()
  6884. {
  6885. return array();
  6886. }
  6887. public function resetScope()
  6888. {
  6889. $this->_c=new CDbCriteria();
  6890. return $this;
  6891. }
  6892. public static function model($className=__CLASS__)
  6893. {
  6894. if(isset(self::$_models[$className]))
  6895. return self::$_models[$className];
  6896. else
  6897. {
  6898. $model=self::$_models[$className]=new $className(null);
  6899. $model->_md=new CActiveRecordMetaData($model);
  6900. $model->attachBehaviors($model->behaviors());
  6901. return $model;
  6902. }
  6903. }
  6904. public function getMetaData()
  6905. {
  6906. if($this->_md!==null)
  6907. return $this->_md;
  6908. else
  6909. return $this->_md=self::model(get_class($this))->_md;
  6910. }
  6911. public function refreshMetaData()
  6912. {
  6913. $finder=self::model(get_class($this));
  6914. $finder->_md=new CActiveRecordMetaData($finder);
  6915. if($this!==$finder)
  6916. $this->_md=$finder->_md;
  6917. }
  6918. public function tableName()
  6919. {
  6920. return get_class($this);
  6921. }
  6922. public function primaryKey()
  6923. {
  6924. }
  6925. public function relations()
  6926. {
  6927. return array();
  6928. }
  6929. public function scopes()
  6930. {
  6931. return array();
  6932. }
  6933. public function attributeNames()
  6934. {
  6935. return array_keys($this->getMetaData()->columns);
  6936. }
  6937. public function getAttributeLabel($attribute)
  6938. {
  6939. $labels=$this->attributeLabels();
  6940. if(isset($labels[$attribute]))
  6941. return $labels[$attribute];
  6942. else if(strpos($attribute,'.')!==false)
  6943. {
  6944. $segs=explode('.',$attribute);
  6945. $name=array_pop($segs);
  6946. $model=$this;
  6947. foreach($segs as $seg)
  6948. {
  6949. $relations=$model->getMetaData()->relations;
  6950. if(isset($relations[$seg]))
  6951. $model=CActiveRecord::model($relations[$seg]->className);
  6952. else
  6953. break;
  6954. }
  6955. return $model->getAttributeLabel($name);
  6956. }
  6957. else
  6958. return $this->generateAttributeLabel($attribute);
  6959. }
  6960. public function getDbConnection()
  6961. {
  6962. if(self::$db!==null)
  6963. return self::$db;
  6964. else
  6965. {
  6966. self::$db=Yii::app()->getDb();
  6967. if(self::$db instanceof CDbConnection)
  6968. return self::$db;
  6969. else
  6970. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  6971. }
  6972. }
  6973. public function getActiveRelation($name)
  6974. {
  6975. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  6976. }
  6977. public function getTableSchema()
  6978. {
  6979. return $this->getMetaData()->tableSchema;
  6980. }
  6981. public function getCommandBuilder()
  6982. {
  6983. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  6984. }
  6985. public function hasAttribute($name)
  6986. {
  6987. return isset($this->getMetaData()->columns[$name]);
  6988. }
  6989. public function getAttribute($name)
  6990. {
  6991. if(property_exists($this,$name))
  6992. return $this->$name;
  6993. else if(isset($this->_attributes[$name]))
  6994. return $this->_attributes[$name];
  6995. }
  6996. public function setAttribute($name,$value)
  6997. {
  6998. if(property_exists($this,$name))
  6999. $this->$name=$value;
  7000. else if(isset($this->getMetaData()->columns[$name]))
  7001. $this->_attributes[$name]=$value;
  7002. else
  7003. return false;
  7004. return true;
  7005. }
  7006. public function addRelatedRecord($name,$record,$index)
  7007. {
  7008. if($index!==false)
  7009. {
  7010. if(!isset($this->_related[$name]))
  7011. $this->_related[$name]=array();
  7012. if($record instanceof CActiveRecord)
  7013. {
  7014. if($index===true)
  7015. $this->_related[$name][]=$record;
  7016. else
  7017. $this->_related[$name][$index]=$record;
  7018. }
  7019. }
  7020. else if(!isset($this->_related[$name]))
  7021. $this->_related[$name]=$record;
  7022. }
  7023. public function getAttributes($names=true)
  7024. {
  7025. $attributes=$this->_attributes;
  7026. foreach($this->getMetaData()->columns as $name=>$column)
  7027. {
  7028. if(property_exists($this,$name))
  7029. $attributes[$name]=$this->$name;
  7030. else if($names===true && !isset($attributes[$name]))
  7031. $attributes[$name]=null;
  7032. }
  7033. if(is_array($names))
  7034. {
  7035. $attrs=array();
  7036. foreach($names as $name)
  7037. {
  7038. if(property_exists($this,$name))
  7039. $attrs[$name]=$this->$name;
  7040. else
  7041. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  7042. }
  7043. return $attrs;
  7044. }
  7045. else
  7046. return $attributes;
  7047. }
  7048. public function save($runValidation=true,$attributes=null)
  7049. {
  7050. if(!$runValidation || $this->validate($attributes))
  7051. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  7052. else
  7053. return false;
  7054. }
  7055. public function getIsNewRecord()
  7056. {
  7057. return $this->_new;
  7058. }
  7059. public function setIsNewRecord($value)
  7060. {
  7061. $this->_new=$value;
  7062. }
  7063. public function onBeforeSave($event)
  7064. {
  7065. $this->raiseEvent('onBeforeSave',$event);
  7066. }
  7067. public function onAfterSave($event)
  7068. {
  7069. $this->raiseEvent('onAfterSave',$event);
  7070. }
  7071. public function onBeforeDelete($event)
  7072. {
  7073. $this->raiseEvent('onBeforeDelete',$event);
  7074. }
  7075. public function onAfterDelete($event)
  7076. {
  7077. $this->raiseEvent('onAfterDelete',$event);
  7078. }
  7079. public function onBeforeFind($event)
  7080. {
  7081. $this->raiseEvent('onBeforeFind',$event);
  7082. }
  7083. public function onAfterFind($event)
  7084. {
  7085. $this->raiseEvent('onAfterFind',$event);
  7086. }
  7087. protected function beforeSave()
  7088. {
  7089. if($this->hasEventHandler('onBeforeSave'))
  7090. {
  7091. $event=new CModelEvent($this);
  7092. $this->onBeforeSave($event);
  7093. return $event->isValid;
  7094. }
  7095. else
  7096. return true;
  7097. }
  7098. protected function afterSave()
  7099. {
  7100. if($this->hasEventHandler('onAfterSave'))
  7101. $this->onAfterSave(new CEvent($this));
  7102. }
  7103. protected function beforeDelete()
  7104. {
  7105. if($this->hasEventHandler('onBeforeDelete'))
  7106. {
  7107. $event=new CModelEvent($this);
  7108. $this->onBeforeDelete($event);
  7109. return $event->isValid;
  7110. }
  7111. else
  7112. return true;
  7113. }
  7114. protected function afterDelete()
  7115. {
  7116. if($this->hasEventHandler('onAfterDelete'))
  7117. $this->onAfterDelete(new CEvent($this));
  7118. }
  7119. protected function beforeFind()
  7120. {
  7121. if($this->hasEventHandler('onBeforeFind'))
  7122. {
  7123. $event=new CModelEvent($this);
  7124. $this->onBeforeFind($event);
  7125. }
  7126. }
  7127. protected function afterFind()
  7128. {
  7129. if($this->hasEventHandler('onAfterFind'))
  7130. $this->onAfterFind(new CEvent($this));
  7131. }
  7132. public function beforeFindInternal()
  7133. {
  7134. $this->beforeFind();
  7135. }
  7136. public function afterFindInternal()
  7137. {
  7138. $this->afterFind();
  7139. }
  7140. public function insert($attributes=null)
  7141. {
  7142. if(!$this->getIsNewRecord())
  7143. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  7144. if($this->beforeSave())
  7145. {
  7146. $builder=$this->getCommandBuilder();
  7147. $table=$this->getMetaData()->tableSchema;
  7148. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  7149. if($command->execute())
  7150. {
  7151. $primaryKey=$table->primaryKey;
  7152. if($table->sequenceName!==null)
  7153. {
  7154. if(is_string($primaryKey) && $this->$primaryKey===null)
  7155. $this->$primaryKey=$builder->getLastInsertID($table);
  7156. else if(is_array($primaryKey))
  7157. {
  7158. foreach($primaryKey as $pk)
  7159. {
  7160. if($this->$pk===null)
  7161. {
  7162. $this->$pk=$builder->getLastInsertID($table);
  7163. break;
  7164. }
  7165. }
  7166. }
  7167. }
  7168. $this->_pk=$this->getPrimaryKey();
  7169. $this->afterSave();
  7170. $this->setIsNewRecord(false);
  7171. $this->setScenario('update');
  7172. return true;
  7173. }
  7174. }
  7175. return false;
  7176. }
  7177. public function update($attributes=null)
  7178. {
  7179. if($this->getIsNewRecord())
  7180. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7181. if($this->beforeSave())
  7182. {
  7183. if($this->_pk===null)
  7184. $this->_pk=$this->getPrimaryKey();
  7185. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  7186. $this->_pk=$this->getPrimaryKey();
  7187. $this->afterSave();
  7188. return true;
  7189. }
  7190. else
  7191. return false;
  7192. }
  7193. public function saveAttributes($attributes)
  7194. {
  7195. if(!$this->getIsNewRecord())
  7196. {
  7197. $values=array();
  7198. foreach($attributes as $name=>$value)
  7199. {
  7200. if(is_integer($name))
  7201. $values[$value]=$this->$value;
  7202. else
  7203. $values[$name]=$this->$name=$value;
  7204. }
  7205. if($this->_pk===null)
  7206. $this->_pk=$this->getPrimaryKey();
  7207. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  7208. {
  7209. $this->_pk=$this->getPrimaryKey();
  7210. return true;
  7211. }
  7212. else
  7213. return false;
  7214. }
  7215. else
  7216. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7217. }
  7218. public function saveCounters($counters)
  7219. {
  7220. $builder=$this->getCommandBuilder();
  7221. $table=$this->getTableSchema();
  7222. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  7223. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7224. if($command->execute())
  7225. {
  7226. foreach($counters as $name=>$value)
  7227. $this->$name=$this->$name+$value;
  7228. return true;
  7229. }
  7230. else
  7231. return false;
  7232. }
  7233. public function delete()
  7234. {
  7235. if(!$this->getIsNewRecord())
  7236. {
  7237. if($this->beforeDelete())
  7238. {
  7239. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  7240. $this->afterDelete();
  7241. return $result;
  7242. }
  7243. else
  7244. return false;
  7245. }
  7246. else
  7247. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  7248. }
  7249. public function refresh()
  7250. {
  7251. if(($record=$this->findByPk($this->getPrimaryKey()))!==null)
  7252. {
  7253. $this->_attributes=array();
  7254. $this->_related=array();
  7255. foreach($this->getMetaData()->columns as $name=>$column)
  7256. {
  7257. if(property_exists($this,$name))
  7258. $this->$name=$record->$name;
  7259. else
  7260. $this->_attributes[$name]=$record->$name;
  7261. }
  7262. return true;
  7263. }
  7264. else
  7265. return false;
  7266. }
  7267. public function equals($record)
  7268. {
  7269. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  7270. }
  7271. public function getPrimaryKey()
  7272. {
  7273. $table=$this->getMetaData()->tableSchema;
  7274. if(is_string($table->primaryKey))
  7275. return $this->{$table->primaryKey};
  7276. else if(is_array($table->primaryKey))
  7277. {
  7278. $values=array();
  7279. foreach($table->primaryKey as $name)
  7280. $values[$name]=$this->$name;
  7281. return $values;
  7282. }
  7283. else
  7284. return null;
  7285. }
  7286. public function setPrimaryKey($value)
  7287. {
  7288. $this->_pk=$this->getPrimaryKey();
  7289. $table=$this->getMetaData()->tableSchema;
  7290. if(is_string($table->primaryKey))
  7291. $this->{$table->primaryKey}=$value;
  7292. else if(is_array($table->primaryKey))
  7293. {
  7294. foreach($table->primaryKey as $name)
  7295. $this->$name=$value[$name];
  7296. }
  7297. }
  7298. public function getOldPrimaryKey()
  7299. {
  7300. return $this->_pk;
  7301. }
  7302. public function setOldPrimaryKey($value)
  7303. {
  7304. $this->_pk=$value;
  7305. }
  7306. protected function query($criteria,$all=false)
  7307. {
  7308. $this->beforeFind();
  7309. $this->applyScopes($criteria);
  7310. if(empty($criteria->with))
  7311. {
  7312. if(!$all)
  7313. $criteria->limit=1;
  7314. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  7315. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  7316. }
  7317. else
  7318. {
  7319. $finder=new CActiveFinder($this,$criteria->with);
  7320. return $finder->query($criteria,$all);
  7321. }
  7322. }
  7323. public function applyScopes(&$criteria)
  7324. {
  7325. if(!empty($criteria->scopes))
  7326. {
  7327. $scs=$this->scopes();
  7328. $c=$this->getDbCriteria();
  7329. foreach((array)$criteria->scopes as $k=>$v)
  7330. {
  7331. if(is_integer($k))
  7332. {
  7333. if(is_string($v))
  7334. {
  7335. if(isset($scs[$v]))
  7336. {
  7337. $c->mergeWith($scs[$v],true);
  7338. continue;
  7339. }
  7340. $scope=$v;
  7341. $params=array();
  7342. }
  7343. else if(is_array($v))
  7344. {
  7345. $scope=key($v);
  7346. $params=current($v);
  7347. }
  7348. }
  7349. else if(is_string($k))
  7350. {
  7351. $scope=$k;
  7352. $params=$v;
  7353. }
  7354. call_user_func_array(array($this,$scope),(array)$params);
  7355. }
  7356. }
  7357. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  7358. {
  7359. $c->mergeWith($criteria);
  7360. $criteria=$c;
  7361. $this->_c=null;
  7362. }
  7363. }
  7364. public function getTableAlias($quote=false, $checkScopes=true)
  7365. {
  7366. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  7367. $alias=$criteria->alias;
  7368. else
  7369. $alias=$this->_alias;
  7370. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  7371. }
  7372. public function setTableAlias($alias)
  7373. {
  7374. $this->_alias=$alias;
  7375. }
  7376. public function find($condition='',$params=array())
  7377. {
  7378. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7379. return $this->query($criteria);
  7380. }
  7381. public function findAll($condition='',$params=array())
  7382. {
  7383. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7384. return $this->query($criteria,true);
  7385. }
  7386. public function findByPk($pk,$condition='',$params=array())
  7387. {
  7388. $prefix=$this->getTableAlias(true).'.';
  7389. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7390. return $this->query($criteria);
  7391. }
  7392. public function findAllByPk($pk,$condition='',$params=array())
  7393. {
  7394. $prefix=$this->getTableAlias(true).'.';
  7395. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7396. return $this->query($criteria,true);
  7397. }
  7398. public function findByAttributes($attributes,$condition='',$params=array())
  7399. {
  7400. $prefix=$this->getTableAlias(true).'.';
  7401. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7402. return $this->query($criteria);
  7403. }
  7404. public function findAllByAttributes($attributes,$condition='',$params=array())
  7405. {
  7406. $prefix=$this->getTableAlias(true).'.';
  7407. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7408. return $this->query($criteria,true);
  7409. }
  7410. public function findBySql($sql,$params=array())
  7411. {
  7412. $this->beforeFind();
  7413. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7414. {
  7415. $this->_c=null;
  7416. $finder=new CActiveFinder($this,$criteria->with);
  7417. return $finder->findBySql($sql,$params);
  7418. }
  7419. else
  7420. {
  7421. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7422. return $this->populateRecord($command->queryRow());
  7423. }
  7424. }
  7425. public function findAllBySql($sql,$params=array())
  7426. {
  7427. $this->beforeFind();
  7428. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7429. {
  7430. $this->_c=null;
  7431. $finder=new CActiveFinder($this,$criteria->with);
  7432. return $finder->findAllBySql($sql,$params);
  7433. }
  7434. else
  7435. {
  7436. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7437. return $this->populateRecords($command->queryAll());
  7438. }
  7439. }
  7440. public function count($condition='',$params=array())
  7441. {
  7442. $builder=$this->getCommandBuilder();
  7443. $criteria=$builder->createCriteria($condition,$params);
  7444. $this->applyScopes($criteria);
  7445. if(empty($criteria->with))
  7446. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7447. else
  7448. {
  7449. $finder=new CActiveFinder($this,$criteria->with);
  7450. return $finder->count($criteria);
  7451. }
  7452. }
  7453. public function countByAttributes($attributes,$condition='',$params=array())
  7454. {
  7455. $prefix=$this->getTableAlias(true).'.';
  7456. $builder=$this->getCommandBuilder();
  7457. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7458. $this->applyScopes($criteria);
  7459. if(empty($criteria->with))
  7460. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7461. else
  7462. {
  7463. $finder=new CActiveFinder($this,$criteria->with);
  7464. return $finder->count($criteria);
  7465. }
  7466. }
  7467. public function countBySql($sql,$params=array())
  7468. {
  7469. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  7470. }
  7471. public function exists($condition='',$params=array())
  7472. {
  7473. $builder=$this->getCommandBuilder();
  7474. $criteria=$builder->createCriteria($condition,$params);
  7475. $table=$this->getTableSchema();
  7476. $criteria->select='1';
  7477. $criteria->limit=1;
  7478. $this->applyScopes($criteria);
  7479. if(empty($criteria->with))
  7480. return $builder->createFindCommand($table,$criteria)->queryRow()!==false;
  7481. else
  7482. {
  7483. $criteria->select='*';
  7484. $finder=new CActiveFinder($this,$criteria->with);
  7485. return $finder->count($criteria)>0;
  7486. }
  7487. }
  7488. public function with()
  7489. {
  7490. if(func_num_args()>0)
  7491. {
  7492. $with=func_get_args();
  7493. if(is_array($with[0])) // the parameter is given as an array
  7494. $with=$with[0];
  7495. if(!empty($with))
  7496. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  7497. }
  7498. return $this;
  7499. }
  7500. public function together()
  7501. {
  7502. $this->getDbCriteria()->together=true;
  7503. return $this;
  7504. }
  7505. public function updateByPk($pk,$attributes,$condition='',$params=array())
  7506. {
  7507. $builder=$this->getCommandBuilder();
  7508. $table=$this->getTableSchema();
  7509. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  7510. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  7511. return $command->execute();
  7512. }
  7513. public function updateAll($attributes,$condition='',$params=array())
  7514. {
  7515. $builder=$this->getCommandBuilder();
  7516. $criteria=$builder->createCriteria($condition,$params);
  7517. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  7518. return $command->execute();
  7519. }
  7520. public function updateCounters($counters,$condition='',$params=array())
  7521. {
  7522. $builder=$this->getCommandBuilder();
  7523. $criteria=$builder->createCriteria($condition,$params);
  7524. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7525. return $command->execute();
  7526. }
  7527. public function deleteByPk($pk,$condition='',$params=array())
  7528. {
  7529. $builder=$this->getCommandBuilder();
  7530. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  7531. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7532. return $command->execute();
  7533. }
  7534. public function deleteAll($condition='',$params=array())
  7535. {
  7536. $builder=$this->getCommandBuilder();
  7537. $criteria=$builder->createCriteria($condition,$params);
  7538. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7539. return $command->execute();
  7540. }
  7541. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  7542. {
  7543. $builder=$this->getCommandBuilder();
  7544. $table=$this->getTableSchema();
  7545. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  7546. $command=$builder->createDeleteCommand($table,$criteria);
  7547. return $command->execute();
  7548. }
  7549. public function populateRecord($attributes,$callAfterFind=true)
  7550. {
  7551. if($attributes!==false)
  7552. {
  7553. $record=$this->instantiate($attributes);
  7554. $record->setScenario('update');
  7555. $record->init();
  7556. $md=$record->getMetaData();
  7557. foreach($attributes as $name=>$value)
  7558. {
  7559. if(property_exists($record,$name))
  7560. $record->$name=$value;
  7561. else if(isset($md->columns[$name]))
  7562. $record->_attributes[$name]=$value;
  7563. }
  7564. $record->_pk=$record->getPrimaryKey();
  7565. $record->attachBehaviors($record->behaviors());
  7566. if($callAfterFind)
  7567. $record->afterFind();
  7568. return $record;
  7569. }
  7570. else
  7571. return null;
  7572. }
  7573. public function populateRecords($data,$callAfterFind=true,$index=null)
  7574. {
  7575. $records=array();
  7576. foreach($data as $attributes)
  7577. {
  7578. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  7579. {
  7580. if($index===null)
  7581. $records[]=$record;
  7582. else
  7583. $records[$record->$index]=$record;
  7584. }
  7585. }
  7586. return $records;
  7587. }
  7588. protected function instantiate($attributes)
  7589. {
  7590. $class=get_class($this);
  7591. $model=new $class(null);
  7592. return $model;
  7593. }
  7594. public function offsetExists($offset)
  7595. {
  7596. return $this->__isset($offset);
  7597. }
  7598. }
  7599. class CBaseActiveRelation extends CComponent
  7600. {
  7601. public $name;
  7602. public $className;
  7603. public $foreignKey;
  7604. public $select='*';
  7605. public $condition='';
  7606. public $params=array();
  7607. public $group='';
  7608. public $join='';
  7609. public $having='';
  7610. public $order='';
  7611. public function __construct($name,$className,$foreignKey,$options=array())
  7612. {
  7613. $this->name=$name;
  7614. $this->className=$className;
  7615. $this->foreignKey=$foreignKey;
  7616. foreach($options as $name=>$value)
  7617. $this->$name=$value;
  7618. }
  7619. public function mergeWith($criteria,$fromScope=false)
  7620. {
  7621. if($criteria instanceof CDbCriteria)
  7622. $criteria=$criteria->toArray();
  7623. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  7624. {
  7625. if($this->select==='*')
  7626. $this->select=$criteria['select'];
  7627. else if($criteria['select']!=='*')
  7628. {
  7629. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  7630. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  7631. $this->select=array_merge($select1,array_diff($select2,$select1));
  7632. }
  7633. }
  7634. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  7635. {
  7636. if($this->condition==='')
  7637. $this->condition=$criteria['condition'];
  7638. else if($criteria['condition']!=='')
  7639. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  7640. }
  7641. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  7642. $this->params=array_merge($this->params,$criteria['params']);
  7643. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  7644. {
  7645. if($this->order==='')
  7646. $this->order=$criteria['order'];
  7647. else if($criteria['order']!=='')
  7648. $this->order=$criteria['order'].', '.$this->order;
  7649. }
  7650. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  7651. {
  7652. if($this->group==='')
  7653. $this->group=$criteria['group'];
  7654. else if($criteria['group']!=='')
  7655. $this->group.=', '.$criteria['group'];
  7656. }
  7657. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  7658. {
  7659. if($this->join==='')
  7660. $this->join=$criteria['join'];
  7661. else if($criteria['join']!=='')
  7662. $this->join.=' '.$criteria['join'];
  7663. }
  7664. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  7665. {
  7666. if($this->having==='')
  7667. $this->having=$criteria['having'];
  7668. else if($criteria['having']!=='')
  7669. $this->having="({$this->having}) AND ({$criteria['having']})";
  7670. }
  7671. }
  7672. }
  7673. class CStatRelation extends CBaseActiveRelation
  7674. {
  7675. public $select='COUNT(*)';
  7676. public $defaultValue=0;
  7677. public function mergeWith($criteria,$fromScope=false)
  7678. {
  7679. if($criteria instanceof CDbCriteria)
  7680. $criteria=$criteria->toArray();
  7681. parent::mergeWith($criteria,$fromScope);
  7682. if(isset($criteria['defaultValue']))
  7683. $this->defaultValue=$criteria['defaultValue'];
  7684. }
  7685. }
  7686. class CActiveRelation extends CBaseActiveRelation
  7687. {
  7688. public $joinType='LEFT OUTER JOIN';
  7689. public $on='';
  7690. public $alias;
  7691. public $with=array();
  7692. public $together;
  7693. public $scopes;
  7694. public function mergeWith($criteria,$fromScope=false)
  7695. {
  7696. if($criteria instanceof CDbCriteria)
  7697. $criteria=$criteria->toArray();
  7698. if($fromScope)
  7699. {
  7700. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  7701. {
  7702. if($this->on==='')
  7703. $this->on=$criteria['condition'];
  7704. else if($criteria['condition']!=='')
  7705. $this->on="({$this->on}) AND ({$criteria['condition']})";
  7706. }
  7707. unset($criteria['condition']);
  7708. }
  7709. parent::mergeWith($criteria);
  7710. if(isset($criteria['joinType']))
  7711. $this->joinType=$criteria['joinType'];
  7712. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  7713. {
  7714. if($this->on==='')
  7715. $this->on=$criteria['on'];
  7716. else if($criteria['on']!=='')
  7717. $this->on="({$this->on}) AND ({$criteria['on']})";
  7718. }
  7719. if(isset($criteria['with']))
  7720. $this->with=$criteria['with'];
  7721. if(isset($criteria['alias']))
  7722. $this->alias=$criteria['alias'];
  7723. if(isset($criteria['together']))
  7724. $this->together=$criteria['together'];
  7725. }
  7726. }
  7727. class CBelongsToRelation extends CActiveRelation
  7728. {
  7729. }
  7730. class CHasOneRelation extends CActiveRelation
  7731. {
  7732. public $through;
  7733. }
  7734. class CHasManyRelation extends CActiveRelation
  7735. {
  7736. public $limit=-1;
  7737. public $offset=-1;
  7738. public $index;
  7739. public $through;
  7740. public function mergeWith($criteria,$fromScope=false)
  7741. {
  7742. if($criteria instanceof CDbCriteria)
  7743. $criteria=$criteria->toArray();
  7744. parent::mergeWith($criteria,$fromScope);
  7745. if(isset($criteria['limit']) && $criteria['limit']>0)
  7746. $this->limit=$criteria['limit'];
  7747. if(isset($criteria['offset']) && $criteria['offset']>=0)
  7748. $this->offset=$criteria['offset'];
  7749. if(isset($criteria['index']))
  7750. $this->index=$criteria['index'];
  7751. }
  7752. }
  7753. class CManyManyRelation extends CHasManyRelation
  7754. {
  7755. }
  7756. class CActiveRecordMetaData
  7757. {
  7758. public $tableSchema;
  7759. public $columns;
  7760. public $relations=array();
  7761. public $attributeDefaults=array();
  7762. private $_model;
  7763. public function __construct($model)
  7764. {
  7765. $this->_model=$model;
  7766. $tableName=$model->tableName();
  7767. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  7768. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  7769. array('{class}'=>get_class($model),'{table}'=>$tableName)));
  7770. if($table->primaryKey===null)
  7771. {
  7772. $table->primaryKey=$model->primaryKey();
  7773. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  7774. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  7775. else if(is_array($table->primaryKey))
  7776. {
  7777. foreach($table->primaryKey as $name)
  7778. {
  7779. if(isset($table->columns[$name]))
  7780. $table->columns[$name]->isPrimaryKey=true;
  7781. }
  7782. }
  7783. }
  7784. $this->tableSchema=$table;
  7785. $this->columns=$table->columns;
  7786. foreach($table->columns as $name=>$column)
  7787. {
  7788. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  7789. $this->attributeDefaults[$name]=$column->defaultValue;
  7790. }
  7791. foreach($model->relations() as $name=>$config)
  7792. {
  7793. $this->addRelation($name,$config);
  7794. }
  7795. }
  7796. public function addRelation($name,$config)
  7797. {
  7798. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  7799. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  7800. else
  7801. 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)));
  7802. }
  7803. public function hasRelation($name)
  7804. {
  7805. return isset($this->relations[$name]);
  7806. }
  7807. public function removeRelation($name)
  7808. {
  7809. unset($this->relations[$name]);
  7810. }
  7811. }
  7812. class CDbConnection extends CApplicationComponent
  7813. {
  7814. public $connectionString;
  7815. public $username='';
  7816. public $password='';
  7817. public $schemaCachingDuration=0;
  7818. public $schemaCachingExclude=array();
  7819. public $schemaCacheID='cache';
  7820. public $queryCachingDuration=0;
  7821. public $queryCachingDependency;
  7822. public $queryCachingCount=0;
  7823. public $queryCacheID='cache';
  7824. public $autoConnect=true;
  7825. public $charset;
  7826. public $emulatePrepare;
  7827. public $enableParamLogging=false;
  7828. public $enableProfiling=false;
  7829. public $tablePrefix;
  7830. public $initSQLs;
  7831. public $driverMap=array(
  7832. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  7833. 'mysqli'=>'CMysqlSchema', // MySQL
  7834. 'mysql'=>'CMysqlSchema', // MySQL
  7835. 'sqlite'=>'CSqliteSchema', // sqlite 3
  7836. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  7837. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  7838. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  7839. 'sqlsrv'=>'CMssqlSchema', // Mssql
  7840. 'oci'=>'COciSchema', // Oracle driver
  7841. );
  7842. public $pdoClass = 'PDO';
  7843. private $_attributes=array();
  7844. private $_active=false;
  7845. private $_pdo;
  7846. private $_transaction;
  7847. private $_schema;
  7848. public function __construct($dsn='',$username='',$password='')
  7849. {
  7850. $this->connectionString=$dsn;
  7851. $this->username=$username;
  7852. $this->password=$password;
  7853. }
  7854. public function __sleep()
  7855. {
  7856. $this->close();
  7857. return array_keys(get_object_vars($this));
  7858. }
  7859. public static function getAvailableDrivers()
  7860. {
  7861. return PDO::getAvailableDrivers();
  7862. }
  7863. public function init()
  7864. {
  7865. parent::init();
  7866. if($this->autoConnect)
  7867. $this->setActive(true);
  7868. }
  7869. public function getActive()
  7870. {
  7871. return $this->_active;
  7872. }
  7873. public function setActive($value)
  7874. {
  7875. if($value!=$this->_active)
  7876. {
  7877. if($value)
  7878. $this->open();
  7879. else
  7880. $this->close();
  7881. }
  7882. }
  7883. public function cache($duration, $dependency=null, $queryCount=1)
  7884. {
  7885. $this->queryCachingDuration=$duration;
  7886. $this->queryCachingDependency=$dependency;
  7887. $this->queryCachingCount=$queryCount;
  7888. return $this;
  7889. }
  7890. protected function open()
  7891. {
  7892. if($this->_pdo===null)
  7893. {
  7894. if(empty($this->connectionString))
  7895. throw new CDbException('CDbConnection.connectionString cannot be empty.');
  7896. try
  7897. {
  7898. $this->_pdo=$this->createPdoInstance();
  7899. $this->initConnection($this->_pdo);
  7900. $this->_active=true;
  7901. }
  7902. catch(PDOException $e)
  7903. {
  7904. if(YII_DEBUG)
  7905. {
  7906. throw new CDbException('CDbConnection failed to open the DB connection: '.
  7907. $e->getMessage(),(int)$e->getCode(),$e->errorInfo);
  7908. }
  7909. else
  7910. {
  7911. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  7912. throw new CDbException('CDbConnection failed to open the DB connection.',(int)$e->getCode(),$e->errorInfo);
  7913. }
  7914. }
  7915. }
  7916. }
  7917. protected function close()
  7918. {
  7919. $this->_pdo=null;
  7920. $this->_active=false;
  7921. $this->_schema=null;
  7922. }
  7923. protected function createPdoInstance()
  7924. {
  7925. $pdoClass=$this->pdoClass;
  7926. if(($pos=strpos($this->connectionString,':'))!==false)
  7927. {
  7928. $driver=strtolower(substr($this->connectionString,0,$pos));
  7929. if($driver==='mssql' || $driver==='dblib' || $driver==='sqlsrv')
  7930. $pdoClass='CMssqlPdoAdapter';
  7931. }
  7932. return new $pdoClass($this->connectionString,$this->username,
  7933. $this->password,$this->_attributes);
  7934. }
  7935. protected function initConnection($pdo)
  7936. {
  7937. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  7938. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  7939. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  7940. if($this->charset!==null)
  7941. {
  7942. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  7943. if(in_array($driver,array('pgsql','mysql','mysqli')))
  7944. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  7945. }
  7946. if($this->initSQLs!==null)
  7947. {
  7948. foreach($this->initSQLs as $sql)
  7949. $pdo->exec($sql);
  7950. }
  7951. }
  7952. public function getPdoInstance()
  7953. {
  7954. return $this->_pdo;
  7955. }
  7956. public function createCommand($query=null)
  7957. {
  7958. $this->setActive(true);
  7959. return new CDbCommand($this,$query);
  7960. }
  7961. public function getCurrentTransaction()
  7962. {
  7963. if($this->_transaction!==null)
  7964. {
  7965. if($this->_transaction->getActive())
  7966. return $this->_transaction;
  7967. }
  7968. return null;
  7969. }
  7970. public function beginTransaction()
  7971. {
  7972. $this->setActive(true);
  7973. $this->_pdo->beginTransaction();
  7974. return $this->_transaction=new CDbTransaction($this);
  7975. }
  7976. public function getSchema()
  7977. {
  7978. if($this->_schema!==null)
  7979. return $this->_schema;
  7980. else
  7981. {
  7982. $driver=$this->getDriverName();
  7983. if(isset($this->driverMap[$driver]))
  7984. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  7985. else
  7986. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  7987. array('{driver}'=>$driver)));
  7988. }
  7989. }
  7990. public function getCommandBuilder()
  7991. {
  7992. return $this->getSchema()->getCommandBuilder();
  7993. }
  7994. public function getLastInsertID($sequenceName='')
  7995. {
  7996. $this->setActive(true);
  7997. return $this->_pdo->lastInsertId($sequenceName);
  7998. }
  7999. public function quoteValue($str)
  8000. {
  8001. if(is_int($str) || is_float($str))
  8002. return $str;
  8003. $this->setActive(true);
  8004. if(($value=$this->_pdo->quote($str))!==false)
  8005. return $value;
  8006. else // the driver doesn't support quote (e.g. oci)
  8007. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  8008. }
  8009. public function quoteTableName($name)
  8010. {
  8011. return $this->getSchema()->quoteTableName($name);
  8012. }
  8013. public function quoteColumnName($name)
  8014. {
  8015. return $this->getSchema()->quoteColumnName($name);
  8016. }
  8017. public function getPdoType($type)
  8018. {
  8019. static $map=array
  8020. (
  8021. 'boolean'=>PDO::PARAM_BOOL,
  8022. 'integer'=>PDO::PARAM_INT,
  8023. 'string'=>PDO::PARAM_STR,
  8024. 'NULL'=>PDO::PARAM_NULL,
  8025. );
  8026. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  8027. }
  8028. public function getColumnCase()
  8029. {
  8030. return $this->getAttribute(PDO::ATTR_CASE);
  8031. }
  8032. public function setColumnCase($value)
  8033. {
  8034. $this->setAttribute(PDO::ATTR_CASE,$value);
  8035. }
  8036. public function getNullConversion()
  8037. {
  8038. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  8039. }
  8040. public function setNullConversion($value)
  8041. {
  8042. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  8043. }
  8044. public function getAutoCommit()
  8045. {
  8046. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  8047. }
  8048. public function setAutoCommit($value)
  8049. {
  8050. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  8051. }
  8052. public function getPersistent()
  8053. {
  8054. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  8055. }
  8056. public function setPersistent($value)
  8057. {
  8058. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  8059. }
  8060. public function getDriverName()
  8061. {
  8062. if(($pos=strpos($this->connectionString, ':'))!==false)
  8063. return strtolower(substr($this->connectionString, 0, $pos));
  8064. // return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  8065. }
  8066. public function getClientVersion()
  8067. {
  8068. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  8069. }
  8070. public function getConnectionStatus()
  8071. {
  8072. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  8073. }
  8074. public function getPrefetch()
  8075. {
  8076. return $this->getAttribute(PDO::ATTR_PREFETCH);
  8077. }
  8078. public function getServerInfo()
  8079. {
  8080. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  8081. }
  8082. public function getServerVersion()
  8083. {
  8084. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  8085. }
  8086. public function getTimeout()
  8087. {
  8088. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  8089. }
  8090. public function getAttribute($name)
  8091. {
  8092. $this->setActive(true);
  8093. return $this->_pdo->getAttribute($name);
  8094. }
  8095. public function setAttribute($name,$value)
  8096. {
  8097. if($this->_pdo instanceof PDO)
  8098. $this->_pdo->setAttribute($name,$value);
  8099. else
  8100. $this->_attributes[$name]=$value;
  8101. }
  8102. public function getAttributes()
  8103. {
  8104. return $this->_attributes;
  8105. }
  8106. public function setAttributes($values)
  8107. {
  8108. foreach($values as $name=>$value)
  8109. $this->_attributes[$name]=$value;
  8110. }
  8111. public function getStats()
  8112. {
  8113. $logger=Yii::getLogger();
  8114. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  8115. $count=count($timings);
  8116. $time=array_sum($timings);
  8117. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  8118. $count+=count($timings);
  8119. $time+=array_sum($timings);
  8120. return array($count,$time);
  8121. }
  8122. }
  8123. abstract class CDbSchema extends CComponent
  8124. {
  8125. public $columnTypes=array();
  8126. private $_tableNames=array();
  8127. private $_tables=array();
  8128. private $_connection;
  8129. private $_builder;
  8130. private $_cacheExclude=array();
  8131. abstract protected function loadTable($name);
  8132. public function __construct($conn)
  8133. {
  8134. $this->_connection=$conn;
  8135. foreach($conn->schemaCachingExclude as $name)
  8136. $this->_cacheExclude[$name]=true;
  8137. }
  8138. public function getDbConnection()
  8139. {
  8140. return $this->_connection;
  8141. }
  8142. public function getTable($name,$refresh=false)
  8143. {
  8144. if($refresh===false && isset($this->_tables[$name]))
  8145. return $this->_tables[$name];
  8146. else
  8147. {
  8148. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  8149. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  8150. else
  8151. $realName=$name;
  8152. // temporarily disable query caching
  8153. if($this->_connection->queryCachingDuration>0)
  8154. {
  8155. $qcDuration=$this->_connection->queryCachingDuration;
  8156. $this->_connection->queryCachingDuration=0;
  8157. }
  8158. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8159. {
  8160. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8161. $table=$cache->get($key);
  8162. if($refresh===true || $table===false)
  8163. {
  8164. $table=$this->loadTable($realName);
  8165. if($table!==null)
  8166. $cache->set($key,$table,$duration);
  8167. }
  8168. $this->_tables[$name]=$table;
  8169. }
  8170. else
  8171. $this->_tables[$name]=$table=$this->loadTable($realName);
  8172. if(isset($qcDuration)) // re-enable query caching
  8173. $this->_connection->queryCachingDuration=$qcDuration;
  8174. return $table;
  8175. }
  8176. }
  8177. public function getTables($schema='')
  8178. {
  8179. $tables=array();
  8180. foreach($this->getTableNames($schema) as $name)
  8181. {
  8182. if(($table=$this->getTable($name))!==null)
  8183. $tables[$name]=$table;
  8184. }
  8185. return $tables;
  8186. }
  8187. public function getTableNames($schema='')
  8188. {
  8189. if(!isset($this->_tableNames[$schema]))
  8190. $this->_tableNames[$schema]=$this->findTableNames($schema);
  8191. return $this->_tableNames[$schema];
  8192. }
  8193. public function getCommandBuilder()
  8194. {
  8195. if($this->_builder!==null)
  8196. return $this->_builder;
  8197. else
  8198. return $this->_builder=$this->createCommandBuilder();
  8199. }
  8200. public function refresh()
  8201. {
  8202. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8203. {
  8204. foreach(array_keys($this->_tables) as $name)
  8205. {
  8206. if(!isset($this->_cacheExclude[$name]))
  8207. {
  8208. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8209. $cache->delete($key);
  8210. }
  8211. }
  8212. }
  8213. $this->_tables=array();
  8214. $this->_tableNames=array();
  8215. $this->_builder=null;
  8216. }
  8217. public function quoteTableName($name)
  8218. {
  8219. if(strpos($name,'.')===false)
  8220. return $this->quoteSimpleTableName($name);
  8221. $parts=explode('.',$name);
  8222. foreach($parts as $i=>$part)
  8223. $parts[$i]=$this->quoteSimpleTableName($part);
  8224. return implode('.',$parts);
  8225. }
  8226. public function quoteSimpleTableName($name)
  8227. {
  8228. return "'".$name."'";
  8229. }
  8230. public function quoteColumnName($name)
  8231. {
  8232. if(($pos=strrpos($name,'.'))!==false)
  8233. {
  8234. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  8235. $name=substr($name,$pos+1);
  8236. }
  8237. else
  8238. $prefix='';
  8239. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  8240. }
  8241. public function quoteSimpleColumnName($name)
  8242. {
  8243. return '"'.$name.'"';
  8244. }
  8245. public function compareTableNames($name1,$name2)
  8246. {
  8247. $name1=str_replace(array('"','`',"'"),'',$name1);
  8248. $name2=str_replace(array('"','`',"'"),'',$name2);
  8249. if(($pos=strrpos($name1,'.'))!==false)
  8250. $name1=substr($name1,$pos+1);
  8251. if(($pos=strrpos($name2,'.'))!==false)
  8252. $name2=substr($name2,$pos+1);
  8253. if($this->_connection->tablePrefix!==null)
  8254. {
  8255. if(strpos($name1,'{')!==false)
  8256. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  8257. if(strpos($name2,'{')!==false)
  8258. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  8259. }
  8260. return $name1===$name2;
  8261. }
  8262. public function resetSequence($table,$value=null)
  8263. {
  8264. }
  8265. public function checkIntegrity($check=true,$schema='')
  8266. {
  8267. }
  8268. protected function createCommandBuilder()
  8269. {
  8270. return new CDbCommandBuilder($this);
  8271. }
  8272. protected function findTableNames($schema='')
  8273. {
  8274. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  8275. array('{class}'=>get_class($this))));
  8276. }
  8277. public function getColumnType($type)
  8278. {
  8279. if(isset($this->columnTypes[$type]))
  8280. return $this->columnTypes[$type];
  8281. else if(($pos=strpos($type,' '))!==false)
  8282. {
  8283. $t=substr($type,0,$pos);
  8284. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  8285. }
  8286. else
  8287. return $type;
  8288. }
  8289. public function createTable($table, $columns, $options=null)
  8290. {
  8291. $cols=array();
  8292. foreach($columns as $name=>$type)
  8293. {
  8294. if(is_string($name))
  8295. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  8296. else
  8297. $cols[]="\t".$type;
  8298. }
  8299. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  8300. return $options===null ? $sql : $sql.' '.$options;
  8301. }
  8302. public function renameTable($table, $newName)
  8303. {
  8304. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  8305. }
  8306. public function dropTable($table)
  8307. {
  8308. return "DROP TABLE ".$this->quoteTableName($table);
  8309. }
  8310. public function truncateTable($table)
  8311. {
  8312. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  8313. }
  8314. public function addColumn($table, $column, $type)
  8315. {
  8316. return 'ALTER TABLE ' . $this->quoteTableName($table)
  8317. . ' ADD ' . $this->quoteColumnName($column) . ' '
  8318. . $this->getColumnType($type);
  8319. }
  8320. public function dropColumn($table, $column)
  8321. {
  8322. return "ALTER TABLE ".$this->quoteTableName($table)
  8323. ." DROP COLUMN ".$this->quoteColumnName($column);
  8324. }
  8325. public function renameColumn($table, $name, $newName)
  8326. {
  8327. return "ALTER TABLE ".$this->quoteTableName($table)
  8328. . " RENAME COLUMN ".$this->quoteColumnName($name)
  8329. . " TO ".$this->quoteColumnName($newName);
  8330. }
  8331. public function alterColumn($table, $column, $type)
  8332. {
  8333. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  8334. . $this->quoteColumnName($column) . ' '
  8335. . $this->quoteColumnName($column) . ' '
  8336. . $this->getColumnType($type);
  8337. }
  8338. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8339. {
  8340. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  8341. foreach($columns as $i=>$col)
  8342. $columns[$i]=$this->quoteColumnName($col);
  8343. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  8344. foreach($refColumns as $i=>$col)
  8345. $refColumns[$i]=$this->quoteColumnName($col);
  8346. $sql='ALTER TABLE '.$this->quoteTableName($table)
  8347. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  8348. .' FOREIGN KEY ('.implode(', ', $columns).')'
  8349. .' REFERENCES '.$this->quoteTableName($refTable)
  8350. .' ('.implode(', ', $refColumns).')';
  8351. if($delete!==null)
  8352. $sql.=' ON DELETE '.$delete;
  8353. if($update!==null)
  8354. $sql.=' ON UPDATE '.$update;
  8355. return $sql;
  8356. }
  8357. public function dropForeignKey($name, $table)
  8358. {
  8359. return 'ALTER TABLE '.$this->quoteTableName($table)
  8360. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  8361. }
  8362. public function createIndex($name, $table, $column, $unique=false)
  8363. {
  8364. $cols=array();
  8365. $columns=preg_split('/\s*,\s*/',$column,-1,PREG_SPLIT_NO_EMPTY);
  8366. foreach($columns as $col)
  8367. {
  8368. if(strpos($col,'(')!==false)
  8369. $cols[]=$col;
  8370. else
  8371. $cols[]=$this->quoteColumnName($col);
  8372. }
  8373. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  8374. . $this->quoteTableName($name).' ON '
  8375. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  8376. }
  8377. public function dropIndex($name, $table)
  8378. {
  8379. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  8380. }
  8381. }
  8382. class CSqliteSchema extends CDbSchema
  8383. {
  8384. public $columnTypes=array(
  8385. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  8386. 'string' => 'varchar(255)',
  8387. 'text' => 'text',
  8388. 'integer' => 'integer',
  8389. 'float' => 'float',
  8390. 'decimal' => 'decimal',
  8391. 'datetime' => 'datetime',
  8392. 'timestamp' => 'timestamp',
  8393. 'time' => 'time',
  8394. 'date' => 'date',
  8395. 'binary' => 'blob',
  8396. 'boolean' => 'tinyint(1)',
  8397. 'money' => 'decimal(19,4)',
  8398. );
  8399. public function resetSequence($table,$value=null)
  8400. {
  8401. if($table->sequenceName!==null)
  8402. {
  8403. if($value===null)
  8404. $value=$this->getDbConnection()->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")->queryScalar();
  8405. else
  8406. $value=(int)$value-1;
  8407. try
  8408. {
  8409. // it's possible sqlite_sequence does not exist
  8410. $this->getDbConnection()->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")->execute();
  8411. }
  8412. catch(Exception $e)
  8413. {
  8414. }
  8415. }
  8416. }
  8417. public function checkIntegrity($check=true,$schema='')
  8418. {
  8419. // SQLite doesn't enforce integrity
  8420. return;
  8421. }
  8422. protected function findTableNames($schema='')
  8423. {
  8424. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  8425. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  8426. }
  8427. protected function createCommandBuilder()
  8428. {
  8429. return new CSqliteCommandBuilder($this);
  8430. }
  8431. protected function loadTable($name)
  8432. {
  8433. $table=new CDbTableSchema;
  8434. $table->name=$name;
  8435. $table->rawName=$this->quoteTableName($name);
  8436. if($this->findColumns($table))
  8437. {
  8438. $this->findConstraints($table);
  8439. return $table;
  8440. }
  8441. else
  8442. return null;
  8443. }
  8444. protected function findColumns($table)
  8445. {
  8446. $sql="PRAGMA table_info({$table->rawName})";
  8447. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  8448. if(empty($columns))
  8449. return false;
  8450. foreach($columns as $column)
  8451. {
  8452. $c=$this->createColumn($column);
  8453. $table->columns[$c->name]=$c;
  8454. if($c->isPrimaryKey)
  8455. {
  8456. if($table->primaryKey===null)
  8457. $table->primaryKey=$c->name;
  8458. else if(is_string($table->primaryKey))
  8459. $table->primaryKey=array($table->primaryKey,$c->name);
  8460. else
  8461. $table->primaryKey[]=$c->name;
  8462. }
  8463. }
  8464. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  8465. {
  8466. $table->sequenceName='';
  8467. $table->columns[$table->primaryKey]->autoIncrement=true;
  8468. }
  8469. return true;
  8470. }
  8471. protected function findConstraints($table)
  8472. {
  8473. $foreignKeys=array();
  8474. $sql="PRAGMA foreign_key_list({$table->rawName})";
  8475. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  8476. foreach($keys as $key)
  8477. {
  8478. $column=$table->columns[$key['from']];
  8479. $column->isForeignKey=true;
  8480. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  8481. }
  8482. $table->foreignKeys=$foreignKeys;
  8483. }
  8484. protected function createColumn($column)
  8485. {
  8486. $c=new CSqliteColumnSchema;
  8487. $c->name=$column['name'];
  8488. $c->rawName=$this->quoteColumnName($c->name);
  8489. $c->allowNull=!$column['notnull'];
  8490. $c->isPrimaryKey=$column['pk']!=0;
  8491. $c->isForeignKey=false;
  8492. $c->init(strtolower($column['type']),$column['dflt_value']);
  8493. return $c;
  8494. }
  8495. public function truncateTable($table)
  8496. {
  8497. return "DELETE FROM ".$this->quoteTableName($table);
  8498. }
  8499. public function dropColumn($table, $column)
  8500. {
  8501. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  8502. }
  8503. public function renameColumn($table, $name, $newName)
  8504. {
  8505. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  8506. }
  8507. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8508. {
  8509. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  8510. }
  8511. public function dropForeignKey($name, $table)
  8512. {
  8513. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  8514. }
  8515. public function alterColumn($table, $column, $type)
  8516. {
  8517. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  8518. }
  8519. public function dropIndex($name, $table)
  8520. {
  8521. return 'DROP INDEX '.$this->quoteTableName($name);
  8522. }
  8523. }
  8524. class CDbTableSchema extends CComponent
  8525. {
  8526. public $name;
  8527. public $rawName;
  8528. public $primaryKey;
  8529. public $sequenceName;
  8530. public $foreignKeys=array();
  8531. public $columns=array();
  8532. public function getColumn($name)
  8533. {
  8534. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  8535. }
  8536. public function getColumnNames()
  8537. {
  8538. return array_keys($this->columns);
  8539. }
  8540. }
  8541. class CDbCommand extends CComponent
  8542. {
  8543. public $params=array();
  8544. private $_connection;
  8545. private $_text;
  8546. private $_statement;
  8547. private $_paramLog=array();
  8548. private $_query;
  8549. private $_fetchMode = array(PDO::FETCH_ASSOC);
  8550. public function __construct(CDbConnection $connection,$query=null)
  8551. {
  8552. $this->_connection=$connection;
  8553. if(is_array($query))
  8554. {
  8555. foreach($query as $name=>$value)
  8556. $this->$name=$value;
  8557. }
  8558. else
  8559. $this->setText($query);
  8560. }
  8561. public function __sleep()
  8562. {
  8563. $this->_statement=null;
  8564. return array_keys(get_object_vars($this));
  8565. }
  8566. public function setFetchMode($mode)
  8567. {
  8568. $params=func_get_args();
  8569. $this->_fetchMode = $params;
  8570. return $this;
  8571. }
  8572. public function reset()
  8573. {
  8574. $this->_text=null;
  8575. $this->_query=null;
  8576. $this->_statement=null;
  8577. $this->_paramLog=array();
  8578. $this->params=array();
  8579. return $this;
  8580. }
  8581. public function getText()
  8582. {
  8583. if($this->_text=='' && !empty($this->_query))
  8584. $this->setText($this->buildQuery($this->_query));
  8585. return $this->_text;
  8586. }
  8587. public function setText($value)
  8588. {
  8589. if($this->_connection->tablePrefix!==null && $value!='')
  8590. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  8591. else
  8592. $this->_text=$value;
  8593. $this->cancel();
  8594. return $this;
  8595. }
  8596. public function getConnection()
  8597. {
  8598. return $this->_connection;
  8599. }
  8600. public function getPdoStatement()
  8601. {
  8602. return $this->_statement;
  8603. }
  8604. public function prepare()
  8605. {
  8606. if($this->_statement==null)
  8607. {
  8608. try
  8609. {
  8610. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  8611. $this->_paramLog=array();
  8612. }
  8613. catch(Exception $e)
  8614. {
  8615. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8616. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8617. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  8618. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  8619. }
  8620. }
  8621. }
  8622. public function cancel()
  8623. {
  8624. $this->_statement=null;
  8625. }
  8626. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  8627. {
  8628. $this->prepare();
  8629. if($dataType===null)
  8630. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  8631. else if($length===null)
  8632. $this->_statement->bindParam($name,$value,$dataType);
  8633. else if($driverOptions===null)
  8634. $this->_statement->bindParam($name,$value,$dataType,$length);
  8635. else
  8636. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  8637. $this->_paramLog[$name]=&$value;
  8638. return $this;
  8639. }
  8640. public function bindValue($name, $value, $dataType=null)
  8641. {
  8642. $this->prepare();
  8643. if($dataType===null)
  8644. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8645. else
  8646. $this->_statement->bindValue($name,$value,$dataType);
  8647. $this->_paramLog[$name]=$value;
  8648. return $this;
  8649. }
  8650. public function bindValues($values)
  8651. {
  8652. $this->prepare();
  8653. foreach($values as $name=>$value)
  8654. {
  8655. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8656. $this->_paramLog[$name]=$value;
  8657. }
  8658. return $this;
  8659. }
  8660. public function execute($params=array())
  8661. {
  8662. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8663. {
  8664. $p=array();
  8665. foreach($pars as $name=>$value)
  8666. $p[$name]=$name.'='.var_export($value,true);
  8667. $par='. Bound with ' .implode(', ',$p);
  8668. }
  8669. else
  8670. $par='';
  8671. try
  8672. {
  8673. if($this->_connection->enableProfiling)
  8674. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  8675. $this->prepare();
  8676. if($params===array())
  8677. $this->_statement->execute();
  8678. else
  8679. $this->_statement->execute($params);
  8680. $n=$this->_statement->rowCount();
  8681. if($this->_connection->enableProfiling)
  8682. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  8683. return $n;
  8684. }
  8685. catch(Exception $e)
  8686. {
  8687. if($this->_connection->enableProfiling)
  8688. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  8689. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8690. $message = $e->getMessage();
  8691. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  8692. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8693. if(YII_DEBUG)
  8694. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  8695. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8696. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8697. }
  8698. }
  8699. public function query($params=array())
  8700. {
  8701. return $this->queryInternal('',0,$params);
  8702. }
  8703. public function queryAll($fetchAssociative=true,$params=array())
  8704. {
  8705. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8706. }
  8707. public function queryRow($fetchAssociative=true,$params=array())
  8708. {
  8709. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8710. }
  8711. public function queryScalar($params=array())
  8712. {
  8713. $result=$this->queryInternal('fetchColumn',0,$params);
  8714. if(is_resource($result) && get_resource_type($result)==='stream')
  8715. return stream_get_contents($result);
  8716. else
  8717. return $result;
  8718. }
  8719. public function queryColumn($params=array())
  8720. {
  8721. return $this->queryInternal('fetchAll',PDO::FETCH_COLUMN,$params);
  8722. }
  8723. private function queryInternal($method,$mode,$params=array())
  8724. {
  8725. $params=array_merge($this->params,$params);
  8726. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8727. {
  8728. $p=array();
  8729. foreach($pars as $name=>$value)
  8730. $p[$name]=$name.'='.var_export($value,true);
  8731. $par='. Bound with '.implode(', ',$p);
  8732. }
  8733. else
  8734. $par='';
  8735. if($this->_connection->queryCachingCount>0 && $method!==''
  8736. && $this->_connection->queryCachingDuration>0
  8737. && $this->_connection->queryCacheID!==false
  8738. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  8739. {
  8740. $this->_connection->queryCachingCount--;
  8741. $cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
  8742. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  8743. if(($result=$cache->get($cacheKey))!==false)
  8744. {
  8745. return $result;
  8746. }
  8747. }
  8748. try
  8749. {
  8750. if($this->_connection->enableProfiling)
  8751. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8752. $this->prepare();
  8753. if($params===array())
  8754. $this->_statement->execute();
  8755. else
  8756. $this->_statement->execute($params);
  8757. if($method==='')
  8758. $result=new CDbDataReader($this);
  8759. else
  8760. {
  8761. $mode=(array)$mode;
  8762. $result=call_user_func_array(array($this->_statement, $method), $mode);
  8763. $this->_statement->closeCursor();
  8764. }
  8765. if($this->_connection->enableProfiling)
  8766. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8767. if(isset($cache,$cacheKey))
  8768. $cache->set($cacheKey, $result, $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  8769. return $result;
  8770. }
  8771. catch(Exception $e)
  8772. {
  8773. if($this->_connection->enableProfiling)
  8774. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8775. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8776. $message = $e->getMessage();
  8777. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  8778. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8779. if(YII_DEBUG)
  8780. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  8781. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8782. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8783. }
  8784. }
  8785. public function buildQuery($query)
  8786. {
  8787. $sql=!empty($query['distinct']) ? 'SELECT DISTINCT' : 'SELECT';
  8788. $sql.=' '.(!empty($query['select']) ? $query['select'] : '*');
  8789. if(!empty($query['from']))
  8790. $sql.="\nFROM ".$query['from'];
  8791. else
  8792. throw new CDbException(Yii::t('yii','The DB query must contain the "from" portion.'));
  8793. if(!empty($query['join']))
  8794. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  8795. if(!empty($query['where']))
  8796. $sql.="\nWHERE ".$query['where'];
  8797. if(!empty($query['group']))
  8798. $sql.="\nGROUP BY ".$query['group'];
  8799. if(!empty($query['having']))
  8800. $sql.="\nHAVING ".$query['having'];
  8801. if(!empty($query['order']))
  8802. $sql.="\nORDER BY ".$query['order'];
  8803. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  8804. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  8805. if($limit>=0 || $offset>0)
  8806. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  8807. if(!empty($query['union']))
  8808. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  8809. return $sql;
  8810. }
  8811. public function select($columns='*', $option='')
  8812. {
  8813. if(is_string($columns) && strpos($columns,'(')!==false)
  8814. $this->_query['select']=$columns;
  8815. else
  8816. {
  8817. if(!is_array($columns))
  8818. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8819. foreach($columns as $i=>$column)
  8820. {
  8821. if(is_object($column))
  8822. $columns[$i]=(string)$column;
  8823. else if(strpos($column,'(')===false)
  8824. {
  8825. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  8826. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  8827. else
  8828. $columns[$i]=$this->_connection->quoteColumnName($column);
  8829. }
  8830. }
  8831. $this->_query['select']=implode(', ',$columns);
  8832. }
  8833. if($option!='')
  8834. $this->_query['select']=$option.' '.$this->_query['select'];
  8835. return $this;
  8836. }
  8837. public function getSelect()
  8838. {
  8839. return isset($this->_query['select']) ? $this->_query['select'] : '';
  8840. }
  8841. public function setSelect($value)
  8842. {
  8843. $this->select($value);
  8844. }
  8845. public function selectDistinct($columns='*')
  8846. {
  8847. $this->_query['distinct']=true;
  8848. return $this->select($columns);
  8849. }
  8850. public function getDistinct()
  8851. {
  8852. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  8853. }
  8854. public function setDistinct($value)
  8855. {
  8856. $this->_query['distinct']=$value;
  8857. }
  8858. public function from($tables)
  8859. {
  8860. if(is_string($tables) && strpos($tables,'(')!==false)
  8861. $this->_query['from']=$tables;
  8862. else
  8863. {
  8864. if(!is_array($tables))
  8865. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  8866. foreach($tables as $i=>$table)
  8867. {
  8868. if(strpos($table,'(')===false)
  8869. {
  8870. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  8871. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  8872. else
  8873. $tables[$i]=$this->_connection->quoteTableName($table);
  8874. }
  8875. }
  8876. $this->_query['from']=implode(', ',$tables);
  8877. }
  8878. return $this;
  8879. }
  8880. public function getFrom()
  8881. {
  8882. return isset($this->_query['from']) ? $this->_query['from'] : '';
  8883. }
  8884. public function setFrom($value)
  8885. {
  8886. $this->from($value);
  8887. }
  8888. public function where($conditions, $params=array())
  8889. {
  8890. $this->_query['where']=$this->processConditions($conditions);
  8891. foreach($params as $name=>$value)
  8892. $this->params[$name]=$value;
  8893. return $this;
  8894. }
  8895. public function getWhere()
  8896. {
  8897. return isset($this->_query['where']) ? $this->_query['where'] : '';
  8898. }
  8899. public function setWhere($value)
  8900. {
  8901. $this->where($value);
  8902. }
  8903. public function join($table, $conditions, $params=array())
  8904. {
  8905. return $this->joinInternal('join', $table, $conditions, $params);
  8906. }
  8907. public function getJoin()
  8908. {
  8909. return isset($this->_query['join']) ? $this->_query['join'] : '';
  8910. }
  8911. public function setJoin($value)
  8912. {
  8913. $this->_query['join']=$value;
  8914. }
  8915. public function leftJoin($table, $conditions, $params=array())
  8916. {
  8917. return $this->joinInternal('left join', $table, $conditions, $params);
  8918. }
  8919. public function rightJoin($table, $conditions, $params=array())
  8920. {
  8921. return $this->joinInternal('right join', $table, $conditions, $params);
  8922. }
  8923. public function crossJoin($table)
  8924. {
  8925. return $this->joinInternal('cross join', $table);
  8926. }
  8927. public function naturalJoin($table)
  8928. {
  8929. return $this->joinInternal('natural join', $table);
  8930. }
  8931. public function group($columns)
  8932. {
  8933. if(is_string($columns) && strpos($columns,'(')!==false)
  8934. $this->_query['group']=$columns;
  8935. else
  8936. {
  8937. if(!is_array($columns))
  8938. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8939. foreach($columns as $i=>$column)
  8940. {
  8941. if(is_object($column))
  8942. $columns[$i]=(string)$column;
  8943. else if(strpos($column,'(')===false)
  8944. $columns[$i]=$this->_connection->quoteColumnName($column);
  8945. }
  8946. $this->_query['group']=implode(', ',$columns);
  8947. }
  8948. return $this;
  8949. }
  8950. public function getGroup()
  8951. {
  8952. return isset($this->_query['group']) ? $this->_query['group'] : '';
  8953. }
  8954. public function setGroup($value)
  8955. {
  8956. $this->group($value);
  8957. }
  8958. public function having($conditions, $params=array())
  8959. {
  8960. $this->_query['having']=$this->processConditions($conditions);
  8961. foreach($params as $name=>$value)
  8962. $this->params[$name]=$value;
  8963. return $this;
  8964. }
  8965. public function getHaving()
  8966. {
  8967. return isset($this->_query['having']) ? $this->_query['having'] : '';
  8968. }
  8969. public function setHaving($value)
  8970. {
  8971. $this->having($value);
  8972. }
  8973. public function order($columns)
  8974. {
  8975. if(is_string($columns) && strpos($columns,'(')!==false)
  8976. $this->_query['order']=$columns;
  8977. else
  8978. {
  8979. if(!is_array($columns))
  8980. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8981. foreach($columns as $i=>$column)
  8982. {
  8983. if(is_object($column))
  8984. $columns[$i]=(string)$column;
  8985. else if(strpos($column,'(')===false)
  8986. {
  8987. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  8988. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  8989. else
  8990. $columns[$i]=$this->_connection->quoteColumnName($column);
  8991. }
  8992. }
  8993. $this->_query['order']=implode(', ',$columns);
  8994. }
  8995. return $this;
  8996. }
  8997. public function getOrder()
  8998. {
  8999. return isset($this->_query['order']) ? $this->_query['order'] : '';
  9000. }
  9001. public function setOrder($value)
  9002. {
  9003. $this->order($value);
  9004. }
  9005. public function limit($limit, $offset=null)
  9006. {
  9007. $this->_query['limit']=(int)$limit;
  9008. if($offset!==null)
  9009. $this->offset($offset);
  9010. return $this;
  9011. }
  9012. public function getLimit()
  9013. {
  9014. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  9015. }
  9016. public function setLimit($value)
  9017. {
  9018. $this->limit($value);
  9019. }
  9020. public function offset($offset)
  9021. {
  9022. $this->_query['offset']=(int)$offset;
  9023. return $this;
  9024. }
  9025. public function getOffset()
  9026. {
  9027. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  9028. }
  9029. public function setOffset($value)
  9030. {
  9031. $this->offset($value);
  9032. }
  9033. public function union($sql)
  9034. {
  9035. if(isset($this->_query['union']) && is_string($this->_query['union']))
  9036. $this->_query['union']=array($this->_query['union']);
  9037. $this->_query['union'][]=$sql;
  9038. return $this;
  9039. }
  9040. public function getUnion()
  9041. {
  9042. return isset($this->_query['union']) ? $this->_query['union'] : '';
  9043. }
  9044. public function setUnion($value)
  9045. {
  9046. $this->_query['union']=$value;
  9047. }
  9048. public function insert($table, $columns)
  9049. {
  9050. $params=array();
  9051. $names=array();
  9052. $placeholders=array();
  9053. foreach($columns as $name=>$value)
  9054. {
  9055. $names[]=$this->_connection->quoteColumnName($name);
  9056. if($value instanceof CDbExpression)
  9057. {
  9058. $placeholders[] = $value->expression;
  9059. foreach($value->params as $n => $v)
  9060. $params[$n] = $v;
  9061. }
  9062. else
  9063. {
  9064. $placeholders[] = ':' . $name;
  9065. $params[':' . $name] = $value;
  9066. }
  9067. }
  9068. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  9069. . ' (' . implode(', ',$names) . ') VALUES ('
  9070. . implode(', ', $placeholders) . ')';
  9071. return $this->setText($sql)->execute($params);
  9072. }
  9073. public function update($table, $columns, $conditions='', $params=array())
  9074. {
  9075. $lines=array();
  9076. foreach($columns as $name=>$value)
  9077. {
  9078. if($value instanceof CDbExpression)
  9079. {
  9080. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  9081. foreach($value->params as $n => $v)
  9082. $params[$n] = $v;
  9083. }
  9084. else
  9085. {
  9086. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  9087. $params[':' . $name]=$value;
  9088. }
  9089. }
  9090. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  9091. if(($where=$this->processConditions($conditions))!='')
  9092. $sql.=' WHERE '.$where;
  9093. return $this->setText($sql)->execute($params);
  9094. }
  9095. public function delete($table, $conditions='', $params=array())
  9096. {
  9097. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  9098. if(($where=$this->processConditions($conditions))!='')
  9099. $sql.=' WHERE '.$where;
  9100. return $this->setText($sql)->execute($params);
  9101. }
  9102. public function createTable($table, $columns, $options=null)
  9103. {
  9104. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  9105. }
  9106. public function renameTable($table, $newName)
  9107. {
  9108. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  9109. }
  9110. public function dropTable($table)
  9111. {
  9112. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  9113. }
  9114. public function truncateTable($table)
  9115. {
  9116. $schema=$this->getConnection()->getSchema();
  9117. $n=$this->setText($schema->truncateTable($table))->execute();
  9118. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  9119. $schema->resetSequence($schema->getTable($table));
  9120. return $n;
  9121. }
  9122. public function addColumn($table, $column, $type)
  9123. {
  9124. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  9125. }
  9126. public function dropColumn($table, $column)
  9127. {
  9128. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  9129. }
  9130. public function renameColumn($table, $name, $newName)
  9131. {
  9132. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  9133. }
  9134. public function alterColumn($table, $column, $type)
  9135. {
  9136. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  9137. }
  9138. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9139. {
  9140. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  9141. }
  9142. public function dropForeignKey($name, $table)
  9143. {
  9144. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  9145. }
  9146. public function createIndex($name, $table, $column, $unique=false)
  9147. {
  9148. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $column, $unique))->execute();
  9149. }
  9150. public function dropIndex($name, $table)
  9151. {
  9152. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  9153. }
  9154. private function processConditions($conditions)
  9155. {
  9156. if(!is_array($conditions))
  9157. return $conditions;
  9158. else if($conditions===array())
  9159. return '';
  9160. $n=count($conditions);
  9161. $operator=strtoupper($conditions[0]);
  9162. if($operator==='OR' || $operator==='AND')
  9163. {
  9164. $parts=array();
  9165. for($i=1;$i<$n;++$i)
  9166. {
  9167. $condition=$this->processConditions($conditions[$i]);
  9168. if($condition!=='')
  9169. $parts[]='('.$condition.')';
  9170. }
  9171. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  9172. }
  9173. if(!isset($conditions[1],$conditions[2]))
  9174. return '';
  9175. $column=$conditions[1];
  9176. if(strpos($column,'(')===false)
  9177. $column=$this->_connection->quoteColumnName($column);
  9178. $values=$conditions[2];
  9179. if(!is_array($values))
  9180. $values=array($values);
  9181. if($operator==='IN' || $operator==='NOT IN')
  9182. {
  9183. if($values===array())
  9184. return $operator==='IN' ? '0=1' : '';
  9185. foreach($values as $i=>$value)
  9186. {
  9187. if(is_string($value))
  9188. $values[$i]=$this->_connection->quoteValue($value);
  9189. else
  9190. $values[$i]=(string)$value;
  9191. }
  9192. return $column.' '.$operator.' ('.implode(', ',$values).')';
  9193. }
  9194. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  9195. {
  9196. if($values===array())
  9197. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  9198. if($operator==='LIKE' || $operator==='NOT LIKE')
  9199. $andor=' AND ';
  9200. else
  9201. {
  9202. $andor=' OR ';
  9203. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  9204. }
  9205. $expressions=array();
  9206. foreach($values as $value)
  9207. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  9208. return implode($andor,$expressions);
  9209. }
  9210. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  9211. }
  9212. private function joinInternal($type, $table, $conditions='', $params=array())
  9213. {
  9214. if(strpos($table,'(')===false)
  9215. {
  9216. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9217. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9218. else
  9219. $table=$this->_connection->quoteTableName($table);
  9220. }
  9221. $conditions=$this->processConditions($conditions);
  9222. if($conditions!='')
  9223. $conditions=' ON '.$conditions;
  9224. if(isset($this->_query['join']) && is_string($this->_query['join']))
  9225. $this->_query['join']=array($this->_query['join']);
  9226. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  9227. foreach($params as $name=>$value)
  9228. $this->params[$name]=$value;
  9229. return $this;
  9230. }
  9231. }
  9232. class CDbColumnSchema extends CComponent
  9233. {
  9234. public $name;
  9235. public $rawName;
  9236. public $allowNull;
  9237. public $dbType;
  9238. public $type;
  9239. public $defaultValue;
  9240. public $size;
  9241. public $precision;
  9242. public $scale;
  9243. public $isPrimaryKey;
  9244. public $isForeignKey;
  9245. public $autoIncrement=false;
  9246. public function init($dbType, $defaultValue)
  9247. {
  9248. $this->dbType=$dbType;
  9249. $this->extractType($dbType);
  9250. $this->extractLimit($dbType);
  9251. if($defaultValue!==null)
  9252. $this->extractDefault($defaultValue);
  9253. }
  9254. protected function extractType($dbType)
  9255. {
  9256. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  9257. $this->type='integer';
  9258. else if(stripos($dbType,'bool')!==false)
  9259. $this->type='boolean';
  9260. else if(preg_match('/(real|floa|doub)/i',$dbType))
  9261. $this->type='double';
  9262. else
  9263. $this->type='string';
  9264. }
  9265. protected function extractLimit($dbType)
  9266. {
  9267. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  9268. {
  9269. $values=explode(',',$matches[1]);
  9270. $this->size=$this->precision=(int)$values[0];
  9271. if(isset($values[1]))
  9272. $this->scale=(int)$values[1];
  9273. }
  9274. }
  9275. protected function extractDefault($defaultValue)
  9276. {
  9277. $this->defaultValue=$this->typecast($defaultValue);
  9278. }
  9279. public function typecast($value)
  9280. {
  9281. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  9282. return $value;
  9283. if($value==='' && $this->allowNull)
  9284. return $this->type==='string' ? '' : null;
  9285. switch($this->type)
  9286. {
  9287. case 'string': return (string)$value;
  9288. case 'integer': return (integer)$value;
  9289. case 'boolean': return (boolean)$value;
  9290. case 'double':
  9291. default: return $value;
  9292. }
  9293. }
  9294. }
  9295. class CSqliteColumnSchema extends CDbColumnSchema
  9296. {
  9297. protected function extractDefault($defaultValue)
  9298. {
  9299. if($this->type==='string') // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  9300. $this->defaultValue=trim($defaultValue,"'\"");
  9301. else
  9302. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  9303. }
  9304. }
  9305. abstract class CValidator extends CComponent
  9306. {
  9307. public static $builtInValidators=array(
  9308. 'required'=>'CRequiredValidator',
  9309. 'filter'=>'CFilterValidator',
  9310. 'match'=>'CRegularExpressionValidator',
  9311. 'email'=>'CEmailValidator',
  9312. 'url'=>'CUrlValidator',
  9313. 'unique'=>'CUniqueValidator',
  9314. 'compare'=>'CCompareValidator',
  9315. 'length'=>'CStringValidator',
  9316. 'in'=>'CRangeValidator',
  9317. 'numerical'=>'CNumberValidator',
  9318. 'captcha'=>'CCaptchaValidator',
  9319. 'type'=>'CTypeValidator',
  9320. 'file'=>'CFileValidator',
  9321. 'default'=>'CDefaultValueValidator',
  9322. 'exist'=>'CExistValidator',
  9323. 'boolean'=>'CBooleanValidator',
  9324. 'safe'=>'CSafeValidator',
  9325. 'unsafe'=>'CUnsafeValidator',
  9326. 'date'=>'CDateValidator',
  9327. );
  9328. public $attributes;
  9329. public $message;
  9330. public $skipOnError=false;
  9331. public $on;
  9332. public $except;
  9333. public $safe=true;
  9334. public $enableClientValidation=true;
  9335. abstract protected function validateAttribute($object,$attribute);
  9336. public static function createValidator($name,$object,$attributes,$params=array())
  9337. {
  9338. if(is_string($attributes))
  9339. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  9340. if(isset($params['on']))
  9341. {
  9342. if(is_array($params['on']))
  9343. $on=$params['on'];
  9344. else
  9345. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  9346. }
  9347. else
  9348. $on=array();
  9349. if(isset($params['except']))
  9350. {
  9351. if(is_array($params['except']))
  9352. $except=$params['except'];
  9353. else
  9354. $except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
  9355. }
  9356. else
  9357. $except=array();
  9358. if(method_exists($object,$name))
  9359. {
  9360. $validator=new CInlineValidator;
  9361. $validator->attributes=$attributes;
  9362. $validator->method=$name;
  9363. if(isset($params['clientValidate']))
  9364. {
  9365. $validator->clientValidate=$params['clientValidate'];
  9366. unset($params['clientValidate']);
  9367. }
  9368. $validator->params=$params;
  9369. if(isset($params['skipOnError']))
  9370. $validator->skipOnError=$params['skipOnError'];
  9371. }
  9372. else
  9373. {
  9374. $params['attributes']=$attributes;
  9375. if(isset(self::$builtInValidators[$name]))
  9376. $className=Yii::import(self::$builtInValidators[$name],true);
  9377. else
  9378. $className=Yii::import($name,true);
  9379. $validator=new $className;
  9380. foreach($params as $name=>$value)
  9381. $validator->$name=$value;
  9382. }
  9383. $validator->on=empty($on) ? array() : array_combine($on,$on);
  9384. $validator->except=empty($except) ? array() : array_combine($except,$except);
  9385. return $validator;
  9386. }
  9387. public function validate($object,$attributes=null)
  9388. {
  9389. if(is_array($attributes))
  9390. $attributes=array_intersect($this->attributes,$attributes);
  9391. else
  9392. $attributes=$this->attributes;
  9393. foreach($attributes as $attribute)
  9394. {
  9395. if(!$this->skipOnError || !$object->hasErrors($attribute))
  9396. $this->validateAttribute($object,$attribute);
  9397. }
  9398. }
  9399. public function clientValidateAttribute($object,$attribute)
  9400. {
  9401. }
  9402. public function applyTo($scenario)
  9403. {
  9404. if(isset($this->except[$scenario]))
  9405. return false;
  9406. return empty($this->on) || isset($this->on[$scenario]);
  9407. }
  9408. protected function addError($object,$attribute,$message,$params=array())
  9409. {
  9410. $params['{attribute}']=$object->getAttributeLabel($attribute);
  9411. $object->addError($attribute,strtr($message,$params));
  9412. }
  9413. protected function isEmpty($value,$trim=false)
  9414. {
  9415. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  9416. }
  9417. }
  9418. class CStringValidator extends CValidator
  9419. {
  9420. public $max;
  9421. public $min;
  9422. public $is;
  9423. public $tooShort;
  9424. public $tooLong;
  9425. public $allowEmpty=true;
  9426. public $encoding;
  9427. protected function validateAttribute($object,$attribute)
  9428. {
  9429. $value=$object->$attribute;
  9430. if($this->allowEmpty && $this->isEmpty($value))
  9431. return;
  9432. if(function_exists('mb_strlen') && $this->encoding!==false)
  9433. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  9434. else
  9435. $length=strlen($value);
  9436. if($this->min!==null && $length<$this->min)
  9437. {
  9438. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9439. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9440. }
  9441. if($this->max!==null && $length>$this->max)
  9442. {
  9443. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9444. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9445. }
  9446. if($this->is!==null && $length!==$this->is)
  9447. {
  9448. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9449. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  9450. }
  9451. }
  9452. public function clientValidateAttribute($object,$attribute)
  9453. {
  9454. $label=$object->getAttributeLabel($attribute);
  9455. if(($message=$this->message)===null)
  9456. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9457. $message=strtr($message, array(
  9458. '{attribute}'=>$label,
  9459. '{length}'=>$this->is,
  9460. ));
  9461. if(($tooShort=$this->tooShort)===null)
  9462. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9463. $tooShort=strtr($tooShort, array(
  9464. '{attribute}'=>$label,
  9465. '{min}'=>$this->min,
  9466. ));
  9467. if(($tooLong=$this->tooLong)===null)
  9468. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9469. $tooLong=strtr($tooLong, array(
  9470. '{attribute}'=>$label,
  9471. '{max}'=>$this->max,
  9472. ));
  9473. $js='';
  9474. if($this->min!==null)
  9475. {
  9476. $js.="
  9477. if(value.length<{$this->min}) {
  9478. messages.push(".CJSON::encode($tooShort).");
  9479. }
  9480. ";
  9481. }
  9482. if($this->max!==null)
  9483. {
  9484. $js.="
  9485. if(value.length>{$this->max}) {
  9486. messages.push(".CJSON::encode($tooLong).");
  9487. }
  9488. ";
  9489. }
  9490. if($this->is!==null)
  9491. {
  9492. $js.="
  9493. if(value.length!={$this->is}) {
  9494. messages.push(".CJSON::encode($message).");
  9495. }
  9496. ";
  9497. }
  9498. if($this->allowEmpty)
  9499. {
  9500. $js="
  9501. if($.trim(value)!='') {
  9502. $js
  9503. }
  9504. ";
  9505. }
  9506. return $js;
  9507. }
  9508. }
  9509. class CRequiredValidator extends CValidator
  9510. {
  9511. public $requiredValue;
  9512. public $strict=false;
  9513. protected function validateAttribute($object,$attribute)
  9514. {
  9515. $value=$object->$attribute;
  9516. if($this->requiredValue!==null)
  9517. {
  9518. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  9519. {
  9520. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  9521. array('{value}'=>$this->requiredValue));
  9522. $this->addError($object,$attribute,$message);
  9523. }
  9524. }
  9525. else if($this->isEmpty($value,true))
  9526. {
  9527. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  9528. $this->addError($object,$attribute,$message);
  9529. }
  9530. }
  9531. public function clientValidateAttribute($object,$attribute)
  9532. {
  9533. $message=$this->message;
  9534. if($this->requiredValue!==null)
  9535. {
  9536. if($message===null)
  9537. $message=Yii::t('yii','{attribute} must be {value}.');
  9538. $message=strtr($message, array(
  9539. '{value}'=>$this->requiredValue,
  9540. '{attribute}'=>$object->getAttributeLabel($attribute),
  9541. ));
  9542. return "
  9543. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  9544. messages.push(".CJSON::encode($message).");
  9545. }
  9546. ";
  9547. }
  9548. else
  9549. {
  9550. if($message===null)
  9551. $message=Yii::t('yii','{attribute} cannot be blank.');
  9552. $message=strtr($message, array(
  9553. '{attribute}'=>$object->getAttributeLabel($attribute),
  9554. ));
  9555. return "
  9556. if($.trim(value)=='') {
  9557. messages.push(".CJSON::encode($message).");
  9558. }
  9559. ";
  9560. }
  9561. }
  9562. }
  9563. class CNumberValidator extends CValidator
  9564. {
  9565. public $integerOnly=false;
  9566. public $allowEmpty=true;
  9567. public $max;
  9568. public $min;
  9569. public $tooBig;
  9570. public $tooSmall;
  9571. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  9572. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  9573. protected function validateAttribute($object,$attribute)
  9574. {
  9575. $value=$object->$attribute;
  9576. if($this->allowEmpty && $this->isEmpty($value))
  9577. return;
  9578. if($this->integerOnly)
  9579. {
  9580. if(!preg_match($this->integerPattern,"$value"))
  9581. {
  9582. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  9583. $this->addError($object,$attribute,$message);
  9584. }
  9585. }
  9586. else
  9587. {
  9588. if(!preg_match($this->numberPattern,"$value"))
  9589. {
  9590. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  9591. $this->addError($object,$attribute,$message);
  9592. }
  9593. }
  9594. if($this->min!==null && $value<$this->min)
  9595. {
  9596. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9597. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9598. }
  9599. if($this->max!==null && $value>$this->max)
  9600. {
  9601. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9602. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9603. }
  9604. }
  9605. public function clientValidateAttribute($object,$attribute)
  9606. {
  9607. $label=$object->getAttributeLabel($attribute);
  9608. if(($message=$this->message)===null)
  9609. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  9610. $message=strtr($message, array(
  9611. '{attribute}'=>$label,
  9612. ));
  9613. if(($tooBig=$this->tooBig)===null)
  9614. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9615. $tooBig=strtr($tooBig, array(
  9616. '{attribute}'=>$label,
  9617. '{max}'=>$this->max,
  9618. ));
  9619. if(($tooSmall=$this->tooSmall)===null)
  9620. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9621. $tooSmall=strtr($tooSmall, array(
  9622. '{attribute}'=>$label,
  9623. '{min}'=>$this->min,
  9624. ));
  9625. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  9626. $js="
  9627. if(!value.match($pattern)) {
  9628. messages.push(".CJSON::encode($message).");
  9629. }
  9630. ";
  9631. if($this->min!==null)
  9632. {
  9633. $js.="
  9634. if(value<{$this->min}) {
  9635. messages.push(".CJSON::encode($tooSmall).");
  9636. }
  9637. ";
  9638. }
  9639. if($this->max!==null)
  9640. {
  9641. $js.="
  9642. if(value>{$this->max}) {
  9643. messages.push(".CJSON::encode($tooBig).");
  9644. }
  9645. ";
  9646. }
  9647. if($this->allowEmpty)
  9648. {
  9649. $js="
  9650. if($.trim(value)!='') {
  9651. $js
  9652. }
  9653. ";
  9654. }
  9655. return $js;
  9656. }
  9657. }
  9658. class CListIterator implements Iterator
  9659. {
  9660. private $_d;
  9661. private $_i;
  9662. private $_c;
  9663. public function __construct(&$data)
  9664. {
  9665. $this->_d=&$data;
  9666. $this->_i=0;
  9667. $this->_c=count($this->_d);
  9668. }
  9669. public function rewind()
  9670. {
  9671. $this->_i=0;
  9672. }
  9673. public function key()
  9674. {
  9675. return $this->_i;
  9676. }
  9677. public function current()
  9678. {
  9679. return $this->_d[$this->_i];
  9680. }
  9681. public function next()
  9682. {
  9683. $this->_i++;
  9684. }
  9685. public function valid()
  9686. {
  9687. return $this->_i<$this->_c;
  9688. }
  9689. }
  9690. interface IApplicationComponent
  9691. {
  9692. public function init();
  9693. public function getIsInitialized();
  9694. }
  9695. interface ICache
  9696. {
  9697. public function get($id);
  9698. public function mget($ids);
  9699. public function set($id,$value,$expire=0,$dependency=null);
  9700. public function add($id,$value,$expire=0,$dependency=null);
  9701. public function delete($id);
  9702. public function flush();
  9703. }
  9704. interface ICacheDependency
  9705. {
  9706. public function evaluateDependency();
  9707. public function getHasChanged();
  9708. }
  9709. interface IStatePersister
  9710. {
  9711. public function load();
  9712. public function save($state);
  9713. }
  9714. interface IFilter
  9715. {
  9716. public function filter($filterChain);
  9717. }
  9718. interface IAction
  9719. {
  9720. public function getId();
  9721. public function getController();
  9722. }
  9723. interface IWebServiceProvider
  9724. {
  9725. public function beforeWebMethod($service);
  9726. public function afterWebMethod($service);
  9727. }
  9728. interface IViewRenderer
  9729. {
  9730. public function renderFile($context,$file,$data,$return);
  9731. }
  9732. interface IUserIdentity
  9733. {
  9734. public function authenticate();
  9735. public function getIsAuthenticated();
  9736. public function getId();
  9737. public function getName();
  9738. public function getPersistentStates();
  9739. }
  9740. interface IWebUser
  9741. {
  9742. public function getId();
  9743. public function getName();
  9744. public function getIsGuest();
  9745. public function checkAccess($operation,$params=array());
  9746. public function loginRequired();
  9747. }
  9748. interface IAuthManager
  9749. {
  9750. public function checkAccess($itemName,$userId,$params=array());
  9751. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  9752. public function removeAuthItem($name);
  9753. public function getAuthItems($type=null,$userId=null);
  9754. public function getAuthItem($name);
  9755. public function saveAuthItem($item,$oldName=null);
  9756. public function addItemChild($itemName,$childName);
  9757. public function removeItemChild($itemName,$childName);
  9758. public function hasItemChild($itemName,$childName);
  9759. public function getItemChildren($itemName);
  9760. public function assign($itemName,$userId,$bizRule=null,$data=null);
  9761. public function revoke($itemName,$userId);
  9762. public function isAssigned($itemName,$userId);
  9763. public function getAuthAssignment($itemName,$userId);
  9764. public function getAuthAssignments($userId);
  9765. public function saveAuthAssignment($assignment);
  9766. public function clearAll();
  9767. public function clearAuthAssignments();
  9768. public function save();
  9769. public function executeBizRule($bizRule,$params,$data);
  9770. }
  9771. interface IBehavior
  9772. {
  9773. public function attach($component);
  9774. public function detach($component);
  9775. public function getEnabled();
  9776. public function setEnabled($value);
  9777. }
  9778. interface IWidgetFactory
  9779. {
  9780. public function createWidget($owner,$className,$properties=array());
  9781. }
  9782. interface IDataProvider
  9783. {
  9784. public function getId();
  9785. public function getItemCount($refresh=false);
  9786. public function getTotalItemCount($refresh=false);
  9787. public function getData($refresh=false);
  9788. public function getKeys($refresh=false);
  9789. public function getSort();
  9790. public function getPagination();
  9791. }
  9792. interface ILogFilter
  9793. {
  9794. public function filter(&$logs);
  9795. }
  9796. ?>