PageRenderTime 118ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 1ms

/framework/yiilite.php

https://github.com/zhuyanxi/yii
PHP | 10565 lines | 10484 code | 2 blank | 79 comment | 1084 complexity | 1a51f39663bb70516de3deeceb1471ac MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1, BSD-2-Clause, LGPL-3.0, GPL-2.0
  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 2008-2013 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.16-dev';
  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. elseif(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. elseif($n===3)
  92. $object=new $type($args[1],$args[2]);
  93. elseif($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. {
  136. // try to autoload the class with an autoloader
  137. if (class_exists($alias,true))
  138. return self::$_imports[$alias]=$alias;
  139. else
  140. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  141. array('{alias}'=>$namespace)));
  142. }
  143. }
  144. if(($pos=strrpos($alias,'.'))===false) // a simple class name
  145. {
  146. // try to autoload the class with an autoloader if $forceInclude is true
  147. if($forceInclude && (Yii::autoload($alias,true) || class_exists($alias,true)))
  148. self::$_imports[$alias]=$alias;
  149. return $alias;
  150. }
  151. $className=(string)substr($alias,$pos+1);
  152. $isClass=$className!=='*';
  153. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  154. return self::$_imports[$alias]=$className;
  155. if(($path=self::getPathOfAlias($alias))!==false)
  156. {
  157. if($isClass)
  158. {
  159. if($forceInclude)
  160. {
  161. if(is_file($path.'.php'))
  162. require($path.'.php');
  163. else
  164. 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)));
  165. self::$_imports[$alias]=$className;
  166. }
  167. else
  168. self::$classMap[$className]=$path.'.php';
  169. return $className;
  170. }
  171. else // a directory
  172. {
  173. if(self::$_includePaths===null)
  174. {
  175. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  176. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  177. unset(self::$_includePaths[$pos]);
  178. }
  179. array_unshift(self::$_includePaths,$path);
  180. if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  181. self::$enableIncludePath=false;
  182. return self::$_imports[$alias]=$path;
  183. }
  184. }
  185. else
  186. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  187. array('{alias}'=>$alias)));
  188. }
  189. public static function getPathOfAlias($alias)
  190. {
  191. if(isset(self::$_aliases[$alias]))
  192. return self::$_aliases[$alias];
  193. elseif(($pos=strpos($alias,'.'))!==false)
  194. {
  195. $rootAlias=substr($alias,0,$pos);
  196. if(isset(self::$_aliases[$rootAlias]))
  197. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  198. elseif(self::$_app instanceof CWebApplication)
  199. {
  200. if(self::$_app->findModule($rootAlias)!==null)
  201. return self::getPathOfAlias($alias);
  202. }
  203. }
  204. return false;
  205. }
  206. public static function setPathOfAlias($alias,$path)
  207. {
  208. if(empty($path))
  209. unset(self::$_aliases[$alias]);
  210. else
  211. self::$_aliases[$alias]=rtrim($path,'\\/');
  212. }
  213. public static function autoload($className,$classMapOnly=false)
  214. {
  215. // use include so that the error PHP file may appear
  216. if(isset(self::$classMap[$className]))
  217. include(self::$classMap[$className]);
  218. elseif(isset(self::$_coreClasses[$className]))
  219. include(YII_PATH.self::$_coreClasses[$className]);
  220. elseif($classMapOnly)
  221. return false;
  222. else
  223. {
  224. // include class file relying on include_path
  225. if(strpos($className,'\\')===false) // class without namespace
  226. {
  227. if(self::$enableIncludePath===false)
  228. {
  229. foreach(self::$_includePaths as $path)
  230. {
  231. $classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
  232. if(is_file($classFile))
  233. {
  234. include($classFile);
  235. if(YII_DEBUG && basename(realpath($classFile))!==$className.'.php')
  236. throw new CException(Yii::t('yii','Class name "{class}" does not match class file "{file}".', array(
  237. '{class}'=>$className,
  238. '{file}'=>$classFile,
  239. )));
  240. break;
  241. }
  242. }
  243. }
  244. else
  245. include($className.'.php');
  246. }
  247. else // class name with namespace in PHP 5.3
  248. {
  249. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  250. if(($path=self::getPathOfAlias($namespace))!==false)
  251. include($path.'.php');
  252. else
  253. return false;
  254. }
  255. return class_exists($className,false) || interface_exists($className,false);
  256. }
  257. return true;
  258. }
  259. public static function trace($msg,$category='application')
  260. {
  261. if(YII_DEBUG)
  262. self::log($msg,CLogger::LEVEL_TRACE,$category);
  263. }
  264. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  265. {
  266. if(self::$_logger===null)
  267. self::$_logger=new CLogger;
  268. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  269. {
  270. $traces=debug_backtrace();
  271. $count=0;
  272. foreach($traces as $trace)
  273. {
  274. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  275. {
  276. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  277. if(++$count>=YII_TRACE_LEVEL)
  278. break;
  279. }
  280. }
  281. }
  282. self::$_logger->log($msg,$level,$category);
  283. }
  284. public static function beginProfile($token,$category='application')
  285. {
  286. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  287. }
  288. public static function endProfile($token,$category='application')
  289. {
  290. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  291. }
  292. public static function getLogger()
  293. {
  294. if(self::$_logger!==null)
  295. return self::$_logger;
  296. else
  297. return self::$_logger=new CLogger;
  298. }
  299. public static function setLogger($logger)
  300. {
  301. self::$_logger=$logger;
  302. }
  303. public static function powered()
  304. {
  305. return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
  306. }
  307. public static function t($category,$message,$params=array(),$source=null,$language=null)
  308. {
  309. if(self::$_app!==null)
  310. {
  311. if($source===null)
  312. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  313. if(($source=self::$_app->getComponent($source))!==null)
  314. $message=$source->translate($category,$message,$language);
  315. }
  316. if($params===array())
  317. return $message;
  318. if(!is_array($params))
  319. $params=array($params);
  320. if(isset($params[0])) // number choice
  321. {
  322. if(strpos($message,'|')!==false)
  323. {
  324. if(strpos($message,'#')===false)
  325. {
  326. $chunks=explode('|',$message);
  327. $expressions=self::$_app->getLocale($language)->getPluralRules();
  328. if($n=min(count($chunks),count($expressions)))
  329. {
  330. for($i=0;$i<$n;$i++)
  331. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  332. $message=implode('|',$chunks);
  333. }
  334. }
  335. $message=CChoiceFormat::format($message,$params[0]);
  336. }
  337. if(!isset($params['{n}']))
  338. $params['{n}']=$params[0];
  339. unset($params[0]);
  340. }
  341. return $params!==array() ? strtr($message,$params) : $message;
  342. }
  343. public static function registerAutoloader($callback, $append=false)
  344. {
  345. if($append)
  346. {
  347. self::$enableIncludePath=false;
  348. spl_autoload_register($callback);
  349. }
  350. else
  351. {
  352. spl_autoload_unregister(array('YiiBase','autoload'));
  353. spl_autoload_register($callback);
  354. spl_autoload_register(array('YiiBase','autoload'));
  355. }
  356. }
  357. private static $_coreClasses=array(
  358. 'CApplication' => '/base/CApplication.php',
  359. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  360. 'CBehavior' => '/base/CBehavior.php',
  361. 'CComponent' => '/base/CComponent.php',
  362. 'CErrorEvent' => '/base/CErrorEvent.php',
  363. 'CErrorHandler' => '/base/CErrorHandler.php',
  364. 'CException' => '/base/CException.php',
  365. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  366. 'CHttpException' => '/base/CHttpException.php',
  367. 'CModel' => '/base/CModel.php',
  368. 'CModelBehavior' => '/base/CModelBehavior.php',
  369. 'CModelEvent' => '/base/CModelEvent.php',
  370. 'CModule' => '/base/CModule.php',
  371. 'CSecurityManager' => '/base/CSecurityManager.php',
  372. 'CStatePersister' => '/base/CStatePersister.php',
  373. 'CApcCache' => '/caching/CApcCache.php',
  374. 'CCache' => '/caching/CCache.php',
  375. 'CDbCache' => '/caching/CDbCache.php',
  376. 'CDummyCache' => '/caching/CDummyCache.php',
  377. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  378. 'CFileCache' => '/caching/CFileCache.php',
  379. 'CMemCache' => '/caching/CMemCache.php',
  380. 'CRedisCache' => '/caching/CRedisCache.php',
  381. 'CWinCache' => '/caching/CWinCache.php',
  382. 'CXCache' => '/caching/CXCache.php',
  383. 'CZendDataCache' => '/caching/CZendDataCache.php',
  384. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  385. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  386. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  387. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  388. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  389. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  390. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  391. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  392. 'CConfiguration' => '/collections/CConfiguration.php',
  393. 'CList' => '/collections/CList.php',
  394. 'CListIterator' => '/collections/CListIterator.php',
  395. 'CMap' => '/collections/CMap.php',
  396. 'CMapIterator' => '/collections/CMapIterator.php',
  397. 'CQueue' => '/collections/CQueue.php',
  398. 'CQueueIterator' => '/collections/CQueueIterator.php',
  399. 'CStack' => '/collections/CStack.php',
  400. 'CStackIterator' => '/collections/CStackIterator.php',
  401. 'CTypedList' => '/collections/CTypedList.php',
  402. 'CTypedMap' => '/collections/CTypedMap.php',
  403. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  404. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  405. 'CConsoleCommandBehavior' => '/console/CConsoleCommandBehavior.php',
  406. 'CConsoleCommandEvent' => '/console/CConsoleCommandEvent.php',
  407. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  408. 'CHelpCommand' => '/console/CHelpCommand.php',
  409. 'CDbCommand' => '/db/CDbCommand.php',
  410. 'CDbConnection' => '/db/CDbConnection.php',
  411. 'CDbDataReader' => '/db/CDbDataReader.php',
  412. 'CDbException' => '/db/CDbException.php',
  413. 'CDbMigration' => '/db/CDbMigration.php',
  414. 'CDbTransaction' => '/db/CDbTransaction.php',
  415. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  416. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  417. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  418. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  419. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  420. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  421. 'CDbExpression' => '/db/schema/CDbExpression.php',
  422. 'CDbSchema' => '/db/schema/CDbSchema.php',
  423. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  424. 'CCubridColumnSchema' => '/db/schema/cubrid/CCubridColumnSchema.php',
  425. 'CCubridSchema' => '/db/schema/cubrid/CCubridSchema.php',
  426. 'CCubridTableSchema' => '/db/schema/cubrid/CCubridTableSchema.php',
  427. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  428. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  429. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  430. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  431. 'CMssqlSqlsrvPdoAdapter' => '/db/schema/mssql/CMssqlSqlsrvPdoAdapter.php',
  432. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  433. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  434. 'CMysqlCommandBuilder' => '/db/schema/mysql/CMysqlCommandBuilder.php',
  435. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  436. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  437. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  438. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  439. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  440. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  441. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  442. 'CPgsqlCommandBuilder' => '/db/schema/pgsql/CPgsqlCommandBuilder.php',
  443. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  444. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  445. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  446. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  447. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  448. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  449. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  450. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  451. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  452. 'CLocale' => '/i18n/CLocale.php',
  453. 'CMessageSource' => '/i18n/CMessageSource.php',
  454. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  455. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  456. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  457. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  458. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  459. 'CChainedLogFilter' => '/logging/CChainedLogFilter.php',
  460. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  461. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  462. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  463. 'CLogFilter' => '/logging/CLogFilter.php',
  464. 'CLogRoute' => '/logging/CLogRoute.php',
  465. 'CLogRouter' => '/logging/CLogRouter.php',
  466. 'CLogger' => '/logging/CLogger.php',
  467. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  468. 'CSysLogRoute' => '/logging/CSysLogRoute.php',
  469. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  470. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  471. 'CFileHelper' => '/utils/CFileHelper.php',
  472. 'CFormatter' => '/utils/CFormatter.php',
  473. 'CLocalizedFormatter' => '/utils/CLocalizedFormatter.php',
  474. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  475. 'CPasswordHelper' => '/utils/CPasswordHelper.php',
  476. 'CPropertyValue' => '/utils/CPropertyValue.php',
  477. 'CTimestamp' => '/utils/CTimestamp.php',
  478. 'CVarDumper' => '/utils/CVarDumper.php',
  479. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  480. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  481. 'CCompareValidator' => '/validators/CCompareValidator.php',
  482. 'CDateValidator' => '/validators/CDateValidator.php',
  483. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  484. 'CEmailValidator' => '/validators/CEmailValidator.php',
  485. 'CExistValidator' => '/validators/CExistValidator.php',
  486. 'CFileValidator' => '/validators/CFileValidator.php',
  487. 'CFilterValidator' => '/validators/CFilterValidator.php',
  488. 'CInlineValidator' => '/validators/CInlineValidator.php',
  489. 'CNumberValidator' => '/validators/CNumberValidator.php',
  490. 'CRangeValidator' => '/validators/CRangeValidator.php',
  491. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  492. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  493. 'CSafeValidator' => '/validators/CSafeValidator.php',
  494. 'CStringValidator' => '/validators/CStringValidator.php',
  495. 'CTypeValidator' => '/validators/CTypeValidator.php',
  496. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  497. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  498. 'CUrlValidator' => '/validators/CUrlValidator.php',
  499. 'CValidator' => '/validators/CValidator.php',
  500. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  501. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  502. 'CAssetManager' => '/web/CAssetManager.php',
  503. 'CBaseController' => '/web/CBaseController.php',
  504. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  505. 'CClientScript' => '/web/CClientScript.php',
  506. 'CController' => '/web/CController.php',
  507. 'CDataProvider' => '/web/CDataProvider.php',
  508. 'CDataProviderIterator' => '/web/CDataProviderIterator.php',
  509. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  510. 'CExtController' => '/web/CExtController.php',
  511. 'CFormModel' => '/web/CFormModel.php',
  512. 'CHttpCookie' => '/web/CHttpCookie.php',
  513. 'CHttpRequest' => '/web/CHttpRequest.php',
  514. 'CHttpSession' => '/web/CHttpSession.php',
  515. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  516. 'COutputEvent' => '/web/COutputEvent.php',
  517. 'CPagination' => '/web/CPagination.php',
  518. 'CSort' => '/web/CSort.php',
  519. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  520. 'CTheme' => '/web/CTheme.php',
  521. 'CThemeManager' => '/web/CThemeManager.php',
  522. 'CUploadedFile' => '/web/CUploadedFile.php',
  523. 'CUrlManager' => '/web/CUrlManager.php',
  524. 'CWebApplication' => '/web/CWebApplication.php',
  525. 'CWebModule' => '/web/CWebModule.php',
  526. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  527. 'CAction' => '/web/actions/CAction.php',
  528. 'CInlineAction' => '/web/actions/CInlineAction.php',
  529. 'CViewAction' => '/web/actions/CViewAction.php',
  530. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  531. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  532. 'CAuthItem' => '/web/auth/CAuthItem.php',
  533. 'CAuthManager' => '/web/auth/CAuthManager.php',
  534. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  535. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  536. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  537. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  538. 'CWebUser' => '/web/auth/CWebUser.php',
  539. 'CFilter' => '/web/filters/CFilter.php',
  540. 'CFilterChain' => '/web/filters/CFilterChain.php',
  541. 'CHttpCacheFilter' => '/web/filters/CHttpCacheFilter.php',
  542. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  543. 'CForm' => '/web/form/CForm.php',
  544. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  545. 'CFormElement' => '/web/form/CFormElement.php',
  546. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  547. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  548. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  549. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  550. 'CHtml' => '/web/helpers/CHtml.php',
  551. 'CJSON' => '/web/helpers/CJSON.php',
  552. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  553. 'CJavaScriptExpression' => '/web/helpers/CJavaScriptExpression.php',
  554. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  555. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  556. 'CWebService' => '/web/services/CWebService.php',
  557. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  558. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  559. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  560. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  561. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  562. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  563. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  564. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  565. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  566. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  567. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  568. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  569. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  570. 'COutputCache' => '/web/widgets/COutputCache.php',
  571. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  572. 'CStarRating' => '/web/widgets/CStarRating.php',
  573. 'CTabView' => '/web/widgets/CTabView.php',
  574. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  575. 'CTreeView' => '/web/widgets/CTreeView.php',
  576. 'CWidget' => '/web/widgets/CWidget.php',
  577. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  578. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  579. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  580. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  581. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  582. );
  583. }
  584. spl_autoload_register(array('YiiBase','autoload'));
  585. class Yii extends YiiBase
  586. {
  587. }
  588. class CComponent
  589. {
  590. private $_e;
  591. private $_m;
  592. public function __get($name)
  593. {
  594. $getter='get'.$name;
  595. if(method_exists($this,$getter))
  596. return $this->$getter();
  597. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  598. {
  599. // duplicating getEventHandlers() here for performance
  600. $name=strtolower($name);
  601. if(!isset($this->_e[$name]))
  602. $this->_e[$name]=new CList;
  603. return $this->_e[$name];
  604. }
  605. elseif(isset($this->_m[$name]))
  606. return $this->_m[$name];
  607. elseif(is_array($this->_m))
  608. {
  609. foreach($this->_m as $object)
  610. {
  611. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  612. return $object->$name;
  613. }
  614. }
  615. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  616. array('{class}'=>get_class($this), '{property}'=>$name)));
  617. }
  618. public function __set($name,$value)
  619. {
  620. $setter='set'.$name;
  621. if(method_exists($this,$setter))
  622. return $this->$setter($value);
  623. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  624. {
  625. // duplicating getEventHandlers() here for performance
  626. $name=strtolower($name);
  627. if(!isset($this->_e[$name]))
  628. $this->_e[$name]=new CList;
  629. return $this->_e[$name]->add($value);
  630. }
  631. elseif(is_array($this->_m))
  632. {
  633. foreach($this->_m as $object)
  634. {
  635. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  636. return $object->$name=$value;
  637. }
  638. }
  639. if(method_exists($this,'get'.$name))
  640. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  641. array('{class}'=>get_class($this), '{property}'=>$name)));
  642. else
  643. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  644. array('{class}'=>get_class($this), '{property}'=>$name)));
  645. }
  646. public function __isset($name)
  647. {
  648. $getter='get'.$name;
  649. if(method_exists($this,$getter))
  650. return $this->$getter()!==null;
  651. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  652. {
  653. $name=strtolower($name);
  654. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  655. }
  656. elseif(is_array($this->_m))
  657. {
  658. if(isset($this->_m[$name]))
  659. return true;
  660. foreach($this->_m as $object)
  661. {
  662. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  663. return $object->$name!==null;
  664. }
  665. }
  666. return false;
  667. }
  668. public function __unset($name)
  669. {
  670. $setter='set'.$name;
  671. if(method_exists($this,$setter))
  672. $this->$setter(null);
  673. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  674. unset($this->_e[strtolower($name)]);
  675. elseif(is_array($this->_m))
  676. {
  677. if(isset($this->_m[$name]))
  678. $this->detachBehavior($name);
  679. else
  680. {
  681. foreach($this->_m as $object)
  682. {
  683. if($object->getEnabled())
  684. {
  685. if(property_exists($object,$name))
  686. return $object->$name=null;
  687. elseif($object->canSetProperty($name))
  688. return $object->$setter(null);
  689. }
  690. }
  691. }
  692. }
  693. elseif(method_exists($this,'get'.$name))
  694. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  695. array('{class}'=>get_class($this), '{property}'=>$name)));
  696. }
  697. public function __call($name,$parameters)
  698. {
  699. if($this->_m!==null)
  700. {
  701. foreach($this->_m as $object)
  702. {
  703. if($object->getEnabled() && method_exists($object,$name))
  704. return call_user_func_array(array($object,$name),$parameters);
  705. }
  706. }
  707. if(class_exists('Closure', false) && ($this->canGetProperty($name) || property_exists($this, $name)) && $this->$name instanceof Closure)
  708. return call_user_func_array($this->$name, $parameters);
  709. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  710. array('{class}'=>get_class($this), '{name}'=>$name)));
  711. }
  712. public function asa($behavior)
  713. {
  714. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  715. }
  716. public function attachBehaviors($behaviors)
  717. {
  718. foreach($behaviors as $name=>$behavior)
  719. $this->attachBehavior($name,$behavior);
  720. }
  721. public function detachBehaviors()
  722. {
  723. if($this->_m!==null)
  724. {
  725. foreach($this->_m as $name=>$behavior)
  726. $this->detachBehavior($name);
  727. $this->_m=null;
  728. }
  729. }
  730. public function attachBehavior($name,$behavior)
  731. {
  732. if(!($behavior instanceof IBehavior))
  733. $behavior=Yii::createComponent($behavior);
  734. $behavior->setEnabled(true);
  735. $behavior->attach($this);
  736. return $this->_m[$name]=$behavior;
  737. }
  738. public function detachBehavior($name)
  739. {
  740. if(isset($this->_m[$name]))
  741. {
  742. $this->_m[$name]->detach($this);
  743. $behavior=$this->_m[$name];
  744. unset($this->_m[$name]);
  745. return $behavior;
  746. }
  747. }
  748. public function enableBehaviors()
  749. {
  750. if($this->_m!==null)
  751. {
  752. foreach($this->_m as $behavior)
  753. $behavior->setEnabled(true);
  754. }
  755. }
  756. public function disableBehaviors()
  757. {
  758. if($this->_m!==null)
  759. {
  760. foreach($this->_m as $behavior)
  761. $behavior->setEnabled(false);
  762. }
  763. }
  764. public function enableBehavior($name)
  765. {
  766. if(isset($this->_m[$name]))
  767. $this->_m[$name]->setEnabled(true);
  768. }
  769. public function disableBehavior($name)
  770. {
  771. if(isset($this->_m[$name]))
  772. $this->_m[$name]->setEnabled(false);
  773. }
  774. public function hasProperty($name)
  775. {
  776. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  777. }
  778. public function canGetProperty($name)
  779. {
  780. return method_exists($this,'get'.$name);
  781. }
  782. public function canSetProperty($name)
  783. {
  784. return method_exists($this,'set'.$name);
  785. }
  786. public function hasEvent($name)
  787. {
  788. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  789. }
  790. public function hasEventHandler($name)
  791. {
  792. $name=strtolower($name);
  793. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  794. }
  795. public function getEventHandlers($name)
  796. {
  797. if($this->hasEvent($name))
  798. {
  799. $name=strtolower($name);
  800. if(!isset($this->_e[$name]))
  801. $this->_e[$name]=new CList;
  802. return $this->_e[$name];
  803. }
  804. else
  805. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  806. array('{class}'=>get_class($this), '{event}'=>$name)));
  807. }
  808. public function attachEventHandler($name,$handler)
  809. {
  810. $this->getEventHandlers($name)->add($handler);
  811. }
  812. public function detachEventHandler($name,$handler)
  813. {
  814. if($this->hasEventHandler($name))
  815. return $this->getEventHandlers($name)->remove($handler)!==false;
  816. else
  817. return false;
  818. }
  819. public function raiseEvent($name,$event)
  820. {
  821. $name=strtolower($name);
  822. if(isset($this->_e[$name]))
  823. {
  824. foreach($this->_e[$name] as $handler)
  825. {
  826. if(is_string($handler))
  827. call_user_func($handler,$event);
  828. elseif(is_callable($handler,true))
  829. {
  830. if(is_array($handler))
  831. {
  832. // an array: 0 - object, 1 - method name
  833. list($object,$method)=$handler;
  834. if(is_string($object)) // static method call
  835. call_user_func($handler,$event);
  836. elseif(method_exists($object,$method))
  837. $object->$method($event);
  838. else
  839. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  840. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  841. }
  842. else // PHP 5.3: anonymous function
  843. call_user_func($handler,$event);
  844. }
  845. else
  846. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  847. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  848. // stop further handling if param.handled is set true
  849. if(($event instanceof CEvent) && $event->handled)
  850. return;
  851. }
  852. }
  853. elseif(YII_DEBUG && !$this->hasEvent($name))
  854. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  855. array('{class}'=>get_class($this), '{event}'=>$name)));
  856. }
  857. public function evaluateExpression($_expression_,$_data_=array())
  858. {
  859. if(is_string($_expression_))
  860. {
  861. extract($_data_);
  862. return eval('return '.$_expression_.';');
  863. }
  864. else
  865. {
  866. $_data_[]=$this;
  867. return call_user_func_array($_expression_, $_data_);
  868. }
  869. }
  870. }
  871. class CEvent extends CComponent
  872. {
  873. public $sender;
  874. public $handled=false;
  875. public $params;
  876. public function __construct($sender=null,$params=null)
  877. {
  878. $this->sender=$sender;
  879. $this->params=$params;
  880. }
  881. }
  882. class CEnumerable
  883. {
  884. }
  885. abstract class CModule extends CComponent
  886. {
  887. public $preload=array();
  888. public $behaviors=array();
  889. private $_id;
  890. private $_parentModule;
  891. private $_basePath;
  892. private $_modulePath;
  893. private $_params;
  894. private $_modules=array();
  895. private $_moduleConfig=array();
  896. private $_components=array();
  897. private $_componentConfig=array();
  898. public function __construct($id,$parent,$config=null)
  899. {
  900. $this->_id=$id;
  901. $this->_parentModule=$parent;
  902. // set basePath at early as possible to avoid trouble
  903. if(is_string($config))
  904. $config=require($config);
  905. if(isset($config['basePath']))
  906. {
  907. $this->setBasePath($config['basePath']);
  908. unset($config['basePath']);
  909. }
  910. Yii::setPathOfAlias($id,$this->getBasePath());
  911. $this->preinit();
  912. $this->configure($config);
  913. $this->attachBehaviors($this->behaviors);
  914. $this->preloadComponents();
  915. $this->init();
  916. }
  917. public function __get($name)
  918. {
  919. if($this->hasComponent($name))
  920. return $this->getComponent($name);
  921. else
  922. return parent::__get($name);
  923. }
  924. public function __isset($name)
  925. {
  926. if($this->hasComponent($name))
  927. return $this->getComponent($name)!==null;
  928. else
  929. return parent::__isset($name);
  930. }
  931. public function getId()
  932. {
  933. return $this->_id;
  934. }
  935. public function setId($id)
  936. {
  937. $this->_id=$id;
  938. }
  939. public function getBasePath()
  940. {
  941. if($this->_basePath===null)
  942. {
  943. $class=new ReflectionClass(get_class($this));
  944. $this->_basePath=dirname($class->getFileName());
  945. }
  946. return $this->_basePath;
  947. }
  948. public function setBasePath($path)
  949. {
  950. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  951. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  952. array('{path}'=>$path)));
  953. }
  954. public function getParams()
  955. {
  956. if($this->_params!==null)
  957. return $this->_params;
  958. else
  959. {
  960. $this->_params=new CAttributeCollection;
  961. $this->_params->caseSensitive=true;
  962. return $this->_params;
  963. }
  964. }
  965. public function setParams($value)
  966. {
  967. $params=$this->getParams();
  968. foreach($value as $k=>$v)
  969. $params->add($k,$v);
  970. }
  971. public function getModulePath()
  972. {
  973. if($this->_modulePath!==null)
  974. return $this->_modulePath;
  975. else
  976. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  977. }
  978. public function setModulePath($value)
  979. {
  980. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  981. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  982. array('{path}'=>$value)));
  983. }
  984. public function setImport($aliases)
  985. {
  986. foreach($aliases as $alias)
  987. Yii::import($alias);
  988. }
  989. public function setAliases($mappings)
  990. {
  991. foreach($mappings as $name=>$alias)
  992. {
  993. if(($path=Yii::getPathOfAlias($alias))!==false)
  994. Yii::setPathOfAlias($name,$path);
  995. else
  996. Yii::setPathOfAlias($name,$alias);
  997. }
  998. }
  999. public function getParentModule()
  1000. {
  1001. return $this->_parentModule;
  1002. }
  1003. public function getModule($id)
  1004. {
  1005. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  1006. return $this->_modules[$id];
  1007. elseif(isset($this->_moduleConfig[$id]))
  1008. {
  1009. $config=$this->_moduleConfig[$id];
  1010. if(!isset($config['enabled']) || $config['enabled'])
  1011. {
  1012. $class=$config['class'];
  1013. unset($config['class'], $config['enabled']);
  1014. if($this===Yii::app())
  1015. $module=Yii::createComponent($class,$id,null,$config);
  1016. else
  1017. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  1018. return $this->_modules[$id]=$module;
  1019. }
  1020. }
  1021. }
  1022. public function hasModule($id)
  1023. {
  1024. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  1025. }
  1026. public function getModules()
  1027. {
  1028. return $this->_moduleConfig;
  1029. }
  1030. public function setModules($modules,$merge=true)
  1031. {
  1032. foreach($modules as $id=>$module)
  1033. {
  1034. if(is_int($id))
  1035. {
  1036. $id=$module;
  1037. $module=array();
  1038. }
  1039. if(isset($this->_moduleConfig[$id]) && $merge)
  1040. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1041. else
  1042. {
  1043. if(!isset($module['class']))
  1044. {
  1045. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1046. $module['class']=$id.'.'.ucfirst($id).'Module';
  1047. }
  1048. $this->_moduleConfig[$id]=$module;
  1049. }
  1050. }
  1051. }
  1052. public function hasComponent($id)
  1053. {
  1054. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1055. }
  1056. public function getComponent($id,$createIfNull=true)
  1057. {
  1058. if(isset($this->_components[$id]))
  1059. return $this->_components[$id];
  1060. elseif(isset($this->_componentConfig[$id]) && $createIfNull)
  1061. {
  1062. $config=$this->_componentConfig[$id];
  1063. if(!isset($config['enabled']) || $config['enabled'])
  1064. {
  1065. unset($config['enabled']);
  1066. $component=Yii::createComponent($config);
  1067. $component->init();
  1068. return $this->_components[$id]=$component;
  1069. }
  1070. }
  1071. }
  1072. public function setComponent($id,$component,$merge=true)
  1073. {
  1074. if($component===null)
  1075. {
  1076. unset($this->_components[$id]);
  1077. return;
  1078. }
  1079. elseif($component instanceof IApplicationComponent)
  1080. {
  1081. $this->_components[$id]=$component;
  1082. if(!$component->getIsInitialized())
  1083. $component->init();
  1084. return;
  1085. }
  1086. elseif(isset($this->_components[$id]))
  1087. {
  1088. if(isset($component['class']) && get_class($this->_components[$id])!==$component['class'])
  1089. {
  1090. unset($this->_components[$id]);
  1091. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1092. return;
  1093. }
  1094. foreach($component as $key=>$value)
  1095. {
  1096. if($key!=='class')
  1097. $this->_components[$id]->$key=$value;
  1098. }
  1099. }
  1100. elseif(isset($this->_componentConfig[$id]['class'],$component['class'])
  1101. && $this->_componentConfig[$id]['class']!==$component['class'])
  1102. {
  1103. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1104. return;
  1105. }
  1106. if(isset($this->_componentConfig[$id]) && $merge)
  1107. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1108. else
  1109. $this->_componentConfig[$id]=$component;
  1110. }
  1111. public function getComponents($loadedOnly=true)
  1112. {
  1113. if($loadedOnly)
  1114. return $this->_components;
  1115. else
  1116. return array_merge($this->_componentConfig, $this->_components);
  1117. }
  1118. public function setComponents($components,$merge=true)
  1119. {
  1120. foreach($components as $id=>$component)
  1121. $this->setComponent($id,$component,$merge);
  1122. }
  1123. public function configure($config)
  1124. {
  1125. if(is_array($config))
  1126. {
  1127. foreach($config as $key=>$value)
  1128. $this->$key=$value;
  1129. }
  1130. }
  1131. protected function preloadComponents()
  1132. {
  1133. foreach($this->preload as $id)
  1134. $this->getComponent($id);
  1135. }
  1136. protected function preinit()
  1137. {
  1138. }
  1139. protected function init()
  1140. {
  1141. }
  1142. }
  1143. abstract class CApplication extends CModule
  1144. {
  1145. public $name='My Application';
  1146. public $charset='UTF-8';
  1147. public $sourceLanguage='en_us';
  1148. public $localeClass='CLocale';
  1149. private $_id;
  1150. private $_basePath;
  1151. private $_runtimePath;
  1152. private $_extensionPath;
  1153. private $_globalState;
  1154. private $_stateChanged;
  1155. private $_ended=false;
  1156. private $_language;
  1157. private $_homeUrl;
  1158. abstract public function processRequest();
  1159. public function __construct($config=null)
  1160. {
  1161. Yii::setApplication($this);
  1162. // set basePath at early as possible to avoid trouble
  1163. if(is_string($config))
  1164. $config=require($config);
  1165. if(isset($config['basePath']))
  1166. {
  1167. $this->setBasePath($config['basePath']);
  1168. unset($config['basePath']);
  1169. }
  1170. else
  1171. $this->setBasePath('protected');
  1172. Yii::setPathOfAlias('application',$this->getBasePath());
  1173. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1174. if(isset($config['extensionPath']))
  1175. {
  1176. $this->setExtensionPath($config['extensionPath']);
  1177. unset($config['extensionPath']);
  1178. }
  1179. else
  1180. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1181. if(isset($config['aliases']))
  1182. {
  1183. $this->setAliases($config['aliases']);
  1184. unset($config['aliases']);
  1185. }
  1186. $this->preinit();
  1187. $this->initSystemHandlers();
  1188. $this->registerCoreComponents();
  1189. $this->configure($config);
  1190. $this->attachBehaviors($this->behaviors);
  1191. $this->preloadComponents();
  1192. $this->init();
  1193. }
  1194. public function run()
  1195. {
  1196. if($this->hasEventHandler('onBeginRequest'))
  1197. $this->onBeginRequest(new CEvent($this));
  1198. register_shutdown_function(array($this,'end'),0,false);
  1199. $this->processRequest();
  1200. if($this->hasEventHandler('onEndRequest'))
  1201. $this->onEndRequest(new CEvent($this));
  1202. }
  1203. public function end($status=0,$exit=true)
  1204. {
  1205. if($this->hasEventHandler('onEndRequest'))
  1206. $this->onEndRequest(new CEvent($this));
  1207. if($exit)
  1208. exit($status);
  1209. }
  1210. public function onBeginRequest($event)
  1211. {
  1212. $this->raiseEvent('onBeginRequest',$event);
  1213. }
  1214. public function onEndRequest($event)
  1215. {
  1216. if(!$this->_ended)
  1217. {
  1218. $this->_ended=true;
  1219. $this->raiseEvent('onEndRequest',$event);
  1220. }
  1221. }
  1222. public function getId()
  1223. {
  1224. if($this->_id!==null)
  1225. return $this->_id;
  1226. else
  1227. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1228. }
  1229. public function setId($id)
  1230. {
  1231. $this->_id=$id;
  1232. }
  1233. public function getBasePath()
  1234. {
  1235. return $this->_basePath;
  1236. }
  1237. public function setBasePath($path)
  1238. {
  1239. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1240. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1241. array('{path}'=>$path)));
  1242. }
  1243. public function getRuntimePath()
  1244. {
  1245. if($this->_runtimePath!==null)
  1246. return $this->_runtimePath;
  1247. else
  1248. {
  1249. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1250. return $this->_runtimePath;
  1251. }
  1252. }
  1253. public function setRuntimePath($path)
  1254. {
  1255. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1256. 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.',
  1257. array('{path}'=>$path)));
  1258. $this->_runtimePath=$runtimePath;
  1259. }
  1260. public function getExtensionPath()
  1261. {
  1262. return Yii::getPathOfAlias('ext');
  1263. }
  1264. public function setExtensionPath($path)
  1265. {
  1266. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1267. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1268. array('{path}'=>$path)));
  1269. Yii::setPathOfAlias('ext',$extensionPath);
  1270. }
  1271. public function getLanguage()
  1272. {
  1273. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1274. }
  1275. public function setLanguage($language)
  1276. {
  1277. $this->_language=$language;
  1278. }
  1279. public function getTimeZone()
  1280. {
  1281. return date_default_timezone_get();
  1282. }
  1283. public function setTimeZone($value)
  1284. {
  1285. date_default_timezone_set($value);
  1286. }
  1287. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1288. {
  1289. if($srcLanguage===null)
  1290. $srcLanguage=$this->sourceLanguage;
  1291. if($language===null)
  1292. $language=$this->getLanguage();
  1293. if($language===$srcLanguage)
  1294. return $srcFile;
  1295. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1296. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1297. }
  1298. public function getLocale($localeID=null)
  1299. {
  1300. return call_user_func_array(array($this->localeClass, 'getInstance'),array($localeID===null?$this->getLanguage():$localeID));
  1301. }
  1302. public function getLocaleDataPath()
  1303. {
  1304. $vars=get_class_vars($this->localeClass);
  1305. if(empty($vars['dataPath']))
  1306. return Yii::getPathOfAlias('system.i18n.data');
  1307. return $vars['dataPath'];
  1308. }
  1309. public function setLocaleDataPath($value)
  1310. {
  1311. $property=new ReflectionProperty($this->localeClass,'dataPath');
  1312. $property->setValue($value);
  1313. }
  1314. public function getNumberFormatter()
  1315. {
  1316. return $this->getLocale()->getNumberFormatter();
  1317. }
  1318. public function getDateFormatter()
  1319. {
  1320. return $this->getLocale()->getDateFormatter();
  1321. }
  1322. public function getDb()
  1323. {
  1324. return $this->getComponent('db');
  1325. }
  1326. public function getErrorHandler()
  1327. {
  1328. return $this->getComponent('errorHandler');
  1329. }
  1330. public function getSecurityManager()
  1331. {
  1332. return $this->getComponent('securityManager');
  1333. }
  1334. public function getStatePersister()
  1335. {
  1336. return $this->getComponent('statePersister');
  1337. }
  1338. public function getCache()
  1339. {
  1340. return $this->getComponent('cache');
  1341. }
  1342. public function getCoreMessages()
  1343. {
  1344. return $this->getComponent('coreMessages');
  1345. }
  1346. public function getMessages()
  1347. {
  1348. return $this->getComponent('messages');
  1349. }
  1350. public function getRequest()
  1351. {
  1352. return $this->getComponent('request');
  1353. }
  1354. public function getUrlManager()
  1355. {
  1356. return $this->getComponent('urlManager');
  1357. }
  1358. public function getController()
  1359. {
  1360. return null;
  1361. }
  1362. public function createUrl($route,$params=array(),$ampersand='&')
  1363. {
  1364. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1365. }
  1366. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1367. {
  1368. $url=$this->createUrl($route,$params,$ampersand);
  1369. if(strpos($url,'http')===0)
  1370. return $url;
  1371. else
  1372. return $this->getRequest()->getHostInfo($schema).$url;
  1373. }
  1374. public function getBaseUrl($absolute=false)
  1375. {
  1376. return $this->getRequest()->getBaseUrl($absolute);
  1377. }
  1378. public function getHomeUrl()
  1379. {
  1380. if($this->_homeUrl===null)
  1381. {
  1382. if($this->getUrlManager()->showScriptName)
  1383. return $this->getRequest()->getScriptUrl();
  1384. else
  1385. return $this->getRequest()->getBaseUrl().'/';
  1386. }
  1387. else
  1388. return $this->_homeUrl;
  1389. }
  1390. public function setHomeUrl($value)
  1391. {
  1392. $this->_homeUrl=$value;
  1393. }
  1394. public function getGlobalState($key,$defaultValue=null)
  1395. {
  1396. if($this->_globalState===null)
  1397. $this->loadGlobalState();
  1398. if(isset($this->_globalState[$key]))
  1399. return $this->_globalState[$key];
  1400. else
  1401. return $defaultValue;
  1402. }
  1403. public function setGlobalState($key,$value,$defaultValue=null)
  1404. {
  1405. if($this->_globalState===null)
  1406. $this->loadGlobalState();
  1407. $changed=$this->_stateChanged;
  1408. if($value===$defaultValue)
  1409. {
  1410. if(isset($this->_globalState[$key]))
  1411. {
  1412. unset($this->_globalState[$key]);
  1413. $this->_stateChanged=true;
  1414. }
  1415. }
  1416. elseif(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1417. {
  1418. $this->_globalState[$key]=$value;
  1419. $this->_stateChanged=true;
  1420. }
  1421. if($this->_stateChanged!==$changed)
  1422. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1423. }
  1424. public function clearGlobalState($key)
  1425. {
  1426. $this->setGlobalState($key,true,true);
  1427. }
  1428. public function loadGlobalState()
  1429. {
  1430. $persister=$this->getStatePersister();
  1431. if(($this->_globalState=$persister->load())===null)
  1432. $this->_globalState=array();
  1433. $this->_stateChanged=false;
  1434. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1435. }
  1436. public function saveGlobalState()
  1437. {
  1438. if($this->_stateChanged)
  1439. {
  1440. $this->_stateChanged=false;
  1441. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1442. $this->getStatePersister()->save($this->_globalState);
  1443. }
  1444. }
  1445. public function handleException($exception)
  1446. {
  1447. // disable error capturing to avoid recursive errors
  1448. restore_error_handler();
  1449. restore_exception_handler();
  1450. $category='exception.'.get_class($exception);
  1451. if($exception instanceof CHttpException)
  1452. $category.='.'.$exception->statusCode;
  1453. // php <5.2 doesn't support string conversion auto-magically
  1454. $message=$exception->__toString();
  1455. if(isset($_SERVER['REQUEST_URI']))
  1456. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  1457. if(isset($_SERVER['HTTP_REFERER']))
  1458. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  1459. $message.="\n---";
  1460. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1461. try
  1462. {
  1463. $event=new CExceptionEvent($this,$exception);
  1464. $this->onException($event);
  1465. if(!$event->handled)
  1466. {
  1467. // try an error handler
  1468. if(($handler=$this->getErrorHandler())!==null)
  1469. $handler->handle($event);
  1470. else
  1471. $this->displayException($exception);
  1472. }
  1473. }
  1474. catch(Exception $e)
  1475. {
  1476. $this->displayException($e);
  1477. }
  1478. try
  1479. {
  1480. $this->end(1);
  1481. }
  1482. catch(Exception $e)
  1483. {
  1484. // use the most primitive way to log error
  1485. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1486. $msg .= $e->getTraceAsString()."\n";
  1487. $msg .= "Previous exception:\n";
  1488. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1489. $msg .= $exception->getTraceAsString()."\n";
  1490. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1491. error_log($msg);
  1492. exit(1);
  1493. }
  1494. }
  1495. public function handleError($code,$message,$file,$line)
  1496. {
  1497. if($code & error_reporting())
  1498. {
  1499. // disable error capturing to avoid recursive errors
  1500. restore_error_handler();
  1501. restore_exception_handler();
  1502. $log="$message ($file:$line)\nStack trace:\n";
  1503. $trace=debug_backtrace();
  1504. // skip the first 3 stacks as they do not tell the error position
  1505. if(count($trace)>3)
  1506. $trace=array_slice($trace,3);
  1507. foreach($trace as $i=>$t)
  1508. {
  1509. if(!isset($t['file']))
  1510. $t['file']='unknown';
  1511. if(!isset($t['line']))
  1512. $t['line']=0;
  1513. if(!isset($t['function']))
  1514. $t['function']='unknown';
  1515. $log.="#$i {$t['file']}({$t['line']}): ";
  1516. if(isset($t['object']) && is_object($t['object']))
  1517. $log.=get_class($t['object']).'->';
  1518. $log.="{$t['function']}()\n";
  1519. }
  1520. if(isset($_SERVER['REQUEST_URI']))
  1521. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1522. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1523. try
  1524. {
  1525. Yii::import('CErrorEvent',true);
  1526. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1527. $this->onError($event);
  1528. if(!$event->handled)
  1529. {
  1530. // try an error handler
  1531. if(($handler=$this->getErrorHandler())!==null)
  1532. $handler->handle($event);
  1533. else
  1534. $this->displayError($code,$message,$file,$line);
  1535. }
  1536. }
  1537. catch(Exception $e)
  1538. {
  1539. $this->displayException($e);
  1540. }
  1541. try
  1542. {
  1543. $this->end(1);
  1544. }
  1545. catch(Exception $e)
  1546. {
  1547. // use the most primitive way to log error
  1548. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1549. $msg .= $e->getTraceAsString()."\n";
  1550. $msg .= "Previous error:\n";
  1551. $msg .= $log."\n";
  1552. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1553. error_log($msg);
  1554. exit(1);
  1555. }
  1556. }
  1557. }
  1558. public function onException($event)
  1559. {
  1560. $this->raiseEvent('onException',$event);
  1561. }
  1562. public function onError($event)
  1563. {
  1564. $this->raiseEvent('onError',$event);
  1565. }
  1566. public function displayError($code,$message,$file,$line)
  1567. {
  1568. if(YII_DEBUG)
  1569. {
  1570. echo "<h1>PHP Error [$code]</h1>\n";
  1571. echo "<p>$message ($file:$line)</p>\n";
  1572. echo '<pre>';
  1573. $trace=debug_backtrace();
  1574. // skip the first 3 stacks as they do not tell the error position
  1575. if(count($trace)>3)
  1576. $trace=array_slice($trace,3);
  1577. foreach($trace as $i=>$t)
  1578. {
  1579. if(!isset($t['file']))
  1580. $t['file']='unknown';
  1581. if(!isset($t['line']))
  1582. $t['line']=0;
  1583. if(!isset($t['function']))
  1584. $t['function']='unknown';
  1585. echo "#$i {$t['file']}({$t['line']}): ";
  1586. if(isset($t['object']) && is_object($t['object']))
  1587. echo get_class($t['object']).'->';
  1588. echo "{$t['function']}()\n";
  1589. }
  1590. echo '</pre>';
  1591. }
  1592. else
  1593. {
  1594. echo "<h1>PHP Error [$code]</h1>\n";
  1595. echo "<p>$message</p>\n";
  1596. }
  1597. }
  1598. public function displayException($exception)
  1599. {
  1600. if(YII_DEBUG)
  1601. {
  1602. echo '<h1>'.get_class($exception)."</h1>\n";
  1603. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1604. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1605. }
  1606. else
  1607. {
  1608. echo '<h1>'.get_class($exception)."</h1>\n";
  1609. echo '<p>'.$exception->getMessage().'</p>';
  1610. }
  1611. }
  1612. protected function initSystemHandlers()
  1613. {
  1614. if(YII_ENABLE_EXCEPTION_HANDLER)
  1615. set_exception_handler(array($this,'handleException'));
  1616. if(YII_ENABLE_ERROR_HANDLER)
  1617. set_error_handler(array($this,'handleError'),error_reporting());
  1618. }
  1619. protected function registerCoreComponents()
  1620. {
  1621. $components=array(
  1622. 'coreMessages'=>array(
  1623. 'class'=>'CPhpMessageSource',
  1624. 'language'=>'en_us',
  1625. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1626. ),
  1627. 'db'=>array(
  1628. 'class'=>'CDbConnection',
  1629. ),
  1630. 'messages'=>array(
  1631. 'class'=>'CPhpMessageSource',
  1632. ),
  1633. 'errorHandler'=>array(
  1634. 'class'=>'CErrorHandler',
  1635. ),
  1636. 'securityManager'=>array(
  1637. 'class'=>'CSecurityManager',
  1638. ),
  1639. 'statePersister'=>array(
  1640. 'class'=>'CStatePersister',
  1641. ),
  1642. 'urlManager'=>array(
  1643. 'class'=>'CUrlManager',
  1644. ),
  1645. 'request'=>array(
  1646. 'class'=>'CHttpRequest',
  1647. ),
  1648. 'format'=>array(
  1649. 'class'=>'CFormatter',
  1650. ),
  1651. );
  1652. $this->setComponents($components);
  1653. }
  1654. }
  1655. class CWebApplication extends CApplication
  1656. {
  1657. public $defaultController='site';
  1658. public $layout='main';
  1659. public $controllerMap=array();
  1660. public $catchAllRequest;
  1661. public $controllerNamespace;
  1662. private $_controllerPath;
  1663. private $_viewPath;
  1664. private $_systemViewPath;
  1665. private $_layoutPath;
  1666. private $_controller;
  1667. private $_theme;
  1668. public function processRequest()
  1669. {
  1670. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1671. {
  1672. $route=$this->catchAllRequest[0];
  1673. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1674. $_GET[$name]=$value;
  1675. }
  1676. else
  1677. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1678. $this->runController($route);
  1679. }
  1680. protected function registerCoreComponents()
  1681. {
  1682. parent::registerCoreComponents();
  1683. $components=array(
  1684. 'session'=>array(
  1685. 'class'=>'CHttpSession',
  1686. ),
  1687. 'assetManager'=>array(
  1688. 'class'=>'CAssetManager',
  1689. ),
  1690. 'user'=>array(
  1691. 'class'=>'CWebUser',
  1692. ),
  1693. 'themeManager'=>array(
  1694. 'class'=>'CThemeManager',
  1695. ),
  1696. 'authManager'=>array(
  1697. 'class'=>'CPhpAuthManager',
  1698. ),
  1699. 'clientScript'=>array(
  1700. 'class'=>'CClientScript',
  1701. ),
  1702. 'widgetFactory'=>array(
  1703. 'class'=>'CWidgetFactory',
  1704. ),
  1705. );
  1706. $this->setComponents($components);
  1707. }
  1708. public function getAuthManager()
  1709. {
  1710. return $this->getComponent('authManager');
  1711. }
  1712. public function getAssetManager()
  1713. {
  1714. return $this->getComponent('assetManager');
  1715. }
  1716. public function getSession()
  1717. {
  1718. return $this->getComponent('session');
  1719. }
  1720. public function getUser()
  1721. {
  1722. return $this->getComponent('user');
  1723. }
  1724. public function getViewRenderer()
  1725. {
  1726. return $this->getComponent('viewRenderer');
  1727. }
  1728. public function getClientScript()
  1729. {
  1730. return $this->getComponent('clientScript');
  1731. }
  1732. public function getWidgetFactory()
  1733. {
  1734. return $this->getComponent('widgetFactory');
  1735. }
  1736. public function getThemeManager()
  1737. {
  1738. return $this->getComponent('themeManager');
  1739. }
  1740. public function getTheme()
  1741. {
  1742. if(is_string($this->_theme))
  1743. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1744. return $this->_theme;
  1745. }
  1746. public function setTheme($value)
  1747. {
  1748. $this->_theme=$value;
  1749. }
  1750. public function runController($route)
  1751. {
  1752. if(($ca=$this->createController($route))!==null)
  1753. {
  1754. list($controller,$actionID)=$ca;
  1755. $oldController=$this->_controller;
  1756. $this->_controller=$controller;
  1757. $controller->init();
  1758. $controller->run($actionID);
  1759. $this->_controller=$oldController;
  1760. }
  1761. else
  1762. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1763. array('{route}'=>$route===''?$this->defaultController:$route)));
  1764. }
  1765. public function createController($route,$owner=null)
  1766. {
  1767. if($owner===null)
  1768. $owner=$this;
  1769. if(($route=trim($route,'/'))==='')
  1770. $route=$owner->defaultController;
  1771. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1772. $route.='/';
  1773. while(($pos=strpos($route,'/'))!==false)
  1774. {
  1775. $id=substr($route,0,$pos);
  1776. if(!preg_match('/^\w+$/',$id))
  1777. return null;
  1778. if(!$caseSensitive)
  1779. $id=strtolower($id);
  1780. $route=(string)substr($route,$pos+1);
  1781. if(!isset($basePath)) // first segment
  1782. {
  1783. if(isset($owner->controllerMap[$id]))
  1784. {
  1785. return array(
  1786. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1787. $this->parseActionParams($route),
  1788. );
  1789. }
  1790. if(($module=$owner->getModule($id))!==null)
  1791. return $this->createController($route,$module);
  1792. $basePath=$owner->getControllerPath();
  1793. $controllerID='';
  1794. }
  1795. else
  1796. $controllerID.='/';
  1797. $className=ucfirst($id).'Controller';
  1798. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1799. if($owner->controllerNamespace!==null)
  1800. $className=$owner->controllerNamespace.'\\'.str_replace('/','\\',$controllerID).$className;
  1801. if(is_file($classFile))
  1802. {
  1803. if(!class_exists($className,false))
  1804. require($classFile);
  1805. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1806. {
  1807. $id[0]=strtolower($id[0]);
  1808. return array(
  1809. new $className($controllerID.$id,$owner===$this?null:$owner),
  1810. $this->parseActionParams($route),
  1811. );
  1812. }
  1813. return null;
  1814. }
  1815. $controllerID.=$id;
  1816. $basePath.=DIRECTORY_SEPARATOR.$id;
  1817. }
  1818. }
  1819. protected function parseActionParams($pathInfo)
  1820. {
  1821. if(($pos=strpos($pathInfo,'/'))!==false)
  1822. {
  1823. $manager=$this->getUrlManager();
  1824. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1825. $actionID=substr($pathInfo,0,$pos);
  1826. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1827. }
  1828. else
  1829. return $pathInfo;
  1830. }
  1831. public function getController()
  1832. {
  1833. return $this->_controller;
  1834. }
  1835. public function setController($value)
  1836. {
  1837. $this->_controller=$value;
  1838. }
  1839. public function getControllerPath()
  1840. {
  1841. if($this->_controllerPath!==null)
  1842. return $this->_controllerPath;
  1843. else
  1844. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1845. }
  1846. public function setControllerPath($value)
  1847. {
  1848. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1849. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1850. array('{path}'=>$value)));
  1851. }
  1852. public function getViewPath()
  1853. {
  1854. if($this->_viewPath!==null)
  1855. return $this->_viewPath;
  1856. else
  1857. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1858. }
  1859. public function setViewPath($path)
  1860. {
  1861. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1862. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1863. array('{path}'=>$path)));
  1864. }
  1865. public function getSystemViewPath()
  1866. {
  1867. if($this->_systemViewPath!==null)
  1868. return $this->_systemViewPath;
  1869. else
  1870. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1871. }
  1872. public function setSystemViewPath($path)
  1873. {
  1874. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1875. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1876. array('{path}'=>$path)));
  1877. }
  1878. public function getLayoutPath()
  1879. {
  1880. if($this->_layoutPath!==null)
  1881. return $this->_layoutPath;
  1882. else
  1883. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1884. }
  1885. public function setLayoutPath($path)
  1886. {
  1887. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1888. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1889. array('{path}'=>$path)));
  1890. }
  1891. public function beforeControllerAction($controller,$action)
  1892. {
  1893. return true;
  1894. }
  1895. public function afterControllerAction($controller,$action)
  1896. {
  1897. }
  1898. public function findModule($id)
  1899. {
  1900. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1901. {
  1902. do
  1903. {
  1904. if(($m=$module->getModule($id))!==null)
  1905. return $m;
  1906. } while(($module=$module->getParentModule())!==null);
  1907. }
  1908. if(($m=$this->getModule($id))!==null)
  1909. return $m;
  1910. }
  1911. protected function init()
  1912. {
  1913. parent::init();
  1914. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1915. $this->getRequest();
  1916. }
  1917. }
  1918. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1919. {
  1920. private $_d=array();
  1921. private $_r=false;
  1922. public function __construct($data=null,$readOnly=false)
  1923. {
  1924. if($data!==null)
  1925. $this->copyFrom($data);
  1926. $this->setReadOnly($readOnly);
  1927. }
  1928. public function getReadOnly()
  1929. {
  1930. return $this->_r;
  1931. }
  1932. protected function setReadOnly($value)
  1933. {
  1934. $this->_r=$value;
  1935. }
  1936. public function getIterator()
  1937. {
  1938. return new CMapIterator($this->_d);
  1939. }
  1940. public function count()
  1941. {
  1942. return $this->getCount();
  1943. }
  1944. public function getCount()
  1945. {
  1946. return count($this->_d);
  1947. }
  1948. public function getKeys()
  1949. {
  1950. return array_keys($this->_d);
  1951. }
  1952. public function itemAt($key)
  1953. {
  1954. if(isset($this->_d[$key]))
  1955. return $this->_d[$key];
  1956. else
  1957. return null;
  1958. }
  1959. public function add($key,$value)
  1960. {
  1961. if(!$this->_r)
  1962. {
  1963. if($key===null)
  1964. $this->_d[]=$value;
  1965. else
  1966. $this->_d[$key]=$value;
  1967. }
  1968. else
  1969. throw new CException(Yii::t('yii','The map is read only.'));
  1970. }
  1971. public function remove($key)
  1972. {
  1973. if(!$this->_r)
  1974. {
  1975. if(isset($this->_d[$key]))
  1976. {
  1977. $value=$this->_d[$key];
  1978. unset($this->_d[$key]);
  1979. return $value;
  1980. }
  1981. else
  1982. {
  1983. // it is possible the value is null, which is not detected by isset
  1984. unset($this->_d[$key]);
  1985. return null;
  1986. }
  1987. }
  1988. else
  1989. throw new CException(Yii::t('yii','The map is read only.'));
  1990. }
  1991. public function clear()
  1992. {
  1993. foreach(array_keys($this->_d) as $key)
  1994. $this->remove($key);
  1995. }
  1996. public function contains($key)
  1997. {
  1998. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  1999. }
  2000. public function toArray()
  2001. {
  2002. return $this->_d;
  2003. }
  2004. public function copyFrom($data)
  2005. {
  2006. if(is_array($data) || $data instanceof Traversable)
  2007. {
  2008. if($this->getCount()>0)
  2009. $this->clear();
  2010. if($data instanceof CMap)
  2011. $data=$data->_d;
  2012. foreach($data as $key=>$value)
  2013. $this->add($key,$value);
  2014. }
  2015. elseif($data!==null)
  2016. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  2017. }
  2018. public function mergeWith($data,$recursive=true)
  2019. {
  2020. if(is_array($data) || $data instanceof Traversable)
  2021. {
  2022. if($data instanceof CMap)
  2023. $data=$data->_d;
  2024. if($recursive)
  2025. {
  2026. if($data instanceof Traversable)
  2027. {
  2028. $d=array();
  2029. foreach($data as $key=>$value)
  2030. $d[$key]=$value;
  2031. $this->_d=self::mergeArray($this->_d,$d);
  2032. }
  2033. else
  2034. $this->_d=self::mergeArray($this->_d,$data);
  2035. }
  2036. else
  2037. {
  2038. foreach($data as $key=>$value)
  2039. $this->add($key,$value);
  2040. }
  2041. }
  2042. elseif($data!==null)
  2043. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  2044. }
  2045. public static function mergeArray($a,$b)
  2046. {
  2047. $args=func_get_args();
  2048. $res=array_shift($args);
  2049. while(!empty($args))
  2050. {
  2051. $next=array_shift($args);
  2052. foreach($next as $k => $v)
  2053. {
  2054. if(is_integer($k))
  2055. isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
  2056. elseif(is_array($v) && isset($res[$k]) && is_array($res[$k]))
  2057. $res[$k]=self::mergeArray($res[$k],$v);
  2058. else
  2059. $res[$k]=$v;
  2060. }
  2061. }
  2062. return $res;
  2063. }
  2064. public function offsetExists($offset)
  2065. {
  2066. return $this->contains($offset);
  2067. }
  2068. public function offsetGet($offset)
  2069. {
  2070. return $this->itemAt($offset);
  2071. }
  2072. public function offsetSet($offset,$item)
  2073. {
  2074. $this->add($offset,$item);
  2075. }
  2076. public function offsetUnset($offset)
  2077. {
  2078. $this->remove($offset);
  2079. }
  2080. }
  2081. class CLogger extends CComponent
  2082. {
  2083. const LEVEL_TRACE='trace';
  2084. const LEVEL_WARNING='warning';
  2085. const LEVEL_ERROR='error';
  2086. const LEVEL_INFO='info';
  2087. const LEVEL_PROFILE='profile';
  2088. public $autoFlush=10000;
  2089. public $autoDump=false;
  2090. private $_logs=array();
  2091. private $_logCount=0;
  2092. private $_levels;
  2093. private $_categories;
  2094. private $_except=array();
  2095. private $_timings;
  2096. private $_processing=false;
  2097. public function log($message,$level='info',$category='application')
  2098. {
  2099. $this->_logs[]=array($message,$level,$category,microtime(true));
  2100. $this->_logCount++;
  2101. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
  2102. {
  2103. $this->_processing=true;
  2104. $this->flush($this->autoDump);
  2105. $this->_processing=false;
  2106. }
  2107. }
  2108. public function getLogs($levels='',$categories=array(), $except=array())
  2109. {
  2110. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2111. if (is_string($categories))
  2112. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2113. else
  2114. $this->_categories=array_filter(array_map('strtolower',$categories));
  2115. if (is_string($except))
  2116. $this->_except=preg_split('/[\s,]+/',strtolower($except),-1,PREG_SPLIT_NO_EMPTY);
  2117. else
  2118. $this->_except=array_filter(array_map('strtolower',$except));
  2119. $ret=$this->_logs;
  2120. if(!empty($levels))
  2121. $ret=array_values(array_filter($ret,array($this,'filterByLevel')));
  2122. if(!empty($this->_categories) || !empty($this->_except))
  2123. $ret=array_values(array_filter($ret,array($this,'filterByCategory')));
  2124. return $ret;
  2125. }
  2126. private function filterByCategory($value)
  2127. {
  2128. return $this->filterAllCategories($value, 2);
  2129. }
  2130. private function filterTimingByCategory($value)
  2131. {
  2132. return $this->filterAllCategories($value, 1);
  2133. }
  2134. private function filterAllCategories($value, $index)
  2135. {
  2136. $cat=strtolower($value[$index]);
  2137. $ret=empty($this->_categories);
  2138. foreach($this->_categories as $category)
  2139. {
  2140. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2141. $ret=true;
  2142. }
  2143. if($ret)
  2144. {
  2145. foreach($this->_except as $category)
  2146. {
  2147. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2148. $ret=false;
  2149. }
  2150. }
  2151. return $ret;
  2152. }
  2153. private function filterByLevel($value)
  2154. {
  2155. return in_array(strtolower($value[1]),$this->_levels);
  2156. }
  2157. public function getExecutionTime()
  2158. {
  2159. return microtime(true)-YII_BEGIN_TIME;
  2160. }
  2161. public function getMemoryUsage()
  2162. {
  2163. if(function_exists('memory_get_usage'))
  2164. return memory_get_usage();
  2165. else
  2166. {
  2167. $output=array();
  2168. if(strncmp(PHP_OS,'WIN',3)===0)
  2169. {
  2170. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2171. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2172. }
  2173. else
  2174. {
  2175. $pid=getmypid();
  2176. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2177. $output=explode(" ",$output[0]);
  2178. return isset($output[1]) ? $output[1]*1024 : 0;
  2179. }
  2180. }
  2181. }
  2182. public function getProfilingResults($token=null,$categories=null,$refresh=false)
  2183. {
  2184. if($this->_timings===null || $refresh)
  2185. $this->calculateTimings();
  2186. if($token===null && $categories===null)
  2187. return $this->_timings;
  2188. $timings = $this->_timings;
  2189. if($categories!==null) {
  2190. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2191. $timings=array_filter($timings,array($this,'filterTimingByCategory'));
  2192. }
  2193. $results=array();
  2194. foreach($timings as $timing)
  2195. {
  2196. if($token===null || $timing[0]===$token)
  2197. $results[]=$timing[2];
  2198. }
  2199. return $results;
  2200. }
  2201. private function calculateTimings()
  2202. {
  2203. $this->_timings=array();
  2204. $stack=array();
  2205. foreach($this->_logs as $log)
  2206. {
  2207. if($log[1]!==CLogger::LEVEL_PROFILE)
  2208. continue;
  2209. list($message,$level,$category,$timestamp)=$log;
  2210. if(!strncasecmp($message,'begin:',6))
  2211. {
  2212. $log[0]=substr($message,6);
  2213. $stack[]=$log;
  2214. }
  2215. elseif(!strncasecmp($message,'end:',4))
  2216. {
  2217. $token=substr($message,4);
  2218. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2219. {
  2220. $delta=$log[3]-$last[3];
  2221. $this->_timings[]=array($message,$category,$delta);
  2222. }
  2223. else
  2224. 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.',
  2225. array('{token}'=>$token)));
  2226. }
  2227. }
  2228. $now=microtime(true);
  2229. while(($last=array_pop($stack))!==null)
  2230. {
  2231. $delta=$now-$last[3];
  2232. $this->_timings[]=array($last[0],$last[2],$delta);
  2233. }
  2234. }
  2235. public function flush($dumpLogs=false)
  2236. {
  2237. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2238. $this->_logs=array();
  2239. $this->_logCount=0;
  2240. }
  2241. public function onFlush($event)
  2242. {
  2243. $this->raiseEvent('onFlush', $event);
  2244. }
  2245. }
  2246. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2247. {
  2248. public $behaviors=array();
  2249. private $_initialized=false;
  2250. public function init()
  2251. {
  2252. $this->attachBehaviors($this->behaviors);
  2253. $this->_initialized=true;
  2254. }
  2255. public function getIsInitialized()
  2256. {
  2257. return $this->_initialized;
  2258. }
  2259. }
  2260. class CHttpRequest extends CApplicationComponent
  2261. {
  2262. public $enableCookieValidation=false;
  2263. public $enableCsrfValidation=false;
  2264. public $csrfTokenName='YII_CSRF_TOKEN';
  2265. public $csrfCookie;
  2266. private $_requestUri;
  2267. private $_pathInfo;
  2268. private $_scriptFile;
  2269. private $_scriptUrl;
  2270. private $_hostInfo;
  2271. private $_baseUrl;
  2272. private $_cookies;
  2273. private $_preferredAcceptTypes;
  2274. private $_preferredLanguages;
  2275. private $_csrfToken;
  2276. private $_restParams;
  2277. public function init()
  2278. {
  2279. parent::init();
  2280. $this->normalizeRequest();
  2281. }
  2282. protected function normalizeRequest()
  2283. {
  2284. // normalize request
  2285. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2286. {
  2287. if(isset($_GET))
  2288. $_GET=$this->stripSlashes($_GET);
  2289. if(isset($_POST))
  2290. $_POST=$this->stripSlashes($_POST);
  2291. if(isset($_REQUEST))
  2292. $_REQUEST=$this->stripSlashes($_REQUEST);
  2293. if(isset($_COOKIE))
  2294. $_COOKIE=$this->stripSlashes($_COOKIE);
  2295. }
  2296. if($this->enableCsrfValidation)
  2297. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2298. }
  2299. public function stripSlashes(&$data)
  2300. {
  2301. if(is_array($data))
  2302. {
  2303. if(count($data) == 0)
  2304. return $data;
  2305. $keys=array_map('stripslashes',array_keys($data));
  2306. $data=array_combine($keys,array_values($data));
  2307. return array_map(array($this,'stripSlashes'),$data);
  2308. }
  2309. else
  2310. return stripslashes($data);
  2311. }
  2312. public function getParam($name,$defaultValue=null)
  2313. {
  2314. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2315. }
  2316. public function getQuery($name,$defaultValue=null)
  2317. {
  2318. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2319. }
  2320. public function getPost($name,$defaultValue=null)
  2321. {
  2322. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2323. }
  2324. public function getDelete($name,$defaultValue=null)
  2325. {
  2326. if($this->getIsDeleteViaPostRequest())
  2327. return $this->getPost($name, $defaultValue);
  2328. if($this->getIsDeleteRequest())
  2329. {
  2330. $restParams=$this->getRestParams();
  2331. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2332. }
  2333. else
  2334. return $defaultValue;
  2335. }
  2336. public function getPut($name,$defaultValue=null)
  2337. {
  2338. if($this->getIsPutViaPostRequest())
  2339. return $this->getPost($name, $defaultValue);
  2340. if($this->getIsPutRequest())
  2341. {
  2342. $restParams=$this->getRestParams();
  2343. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2344. }
  2345. else
  2346. return $defaultValue;
  2347. }
  2348. public function getPatch($name,$defaultValue=null)
  2349. {
  2350. if($this->getIsPatchViaPostRequest())
  2351. return $this->getPost($name, $defaultValue);
  2352. if($this->getIsPatchRequest())
  2353. {
  2354. $restParams=$this->getRestParams();
  2355. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2356. }
  2357. else
  2358. return $defaultValue;
  2359. }
  2360. public function getRestParams()
  2361. {
  2362. if($this->_restParams===null)
  2363. {
  2364. $result=array();
  2365. if(function_exists('mb_parse_str'))
  2366. mb_parse_str($this->getRawBody(), $result);
  2367. else
  2368. parse_str($this->getRawBody(), $result);
  2369. $this->_restParams=$result;
  2370. }
  2371. return $this->_restParams;
  2372. }
  2373. public function getRawBody()
  2374. {
  2375. static $rawBody;
  2376. if($rawBody===null)
  2377. $rawBody=file_get_contents('php://input');
  2378. return $rawBody;
  2379. }
  2380. public function getUrl()
  2381. {
  2382. return $this->getRequestUri();
  2383. }
  2384. public function getHostInfo($schema='')
  2385. {
  2386. if($this->_hostInfo===null)
  2387. {
  2388. if($secure=$this->getIsSecureConnection())
  2389. $http='https';
  2390. else
  2391. $http='http';
  2392. if(isset($_SERVER['HTTP_HOST']))
  2393. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2394. else
  2395. {
  2396. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2397. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2398. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2399. $this->_hostInfo.=':'.$port;
  2400. }
  2401. }
  2402. if($schema!=='')
  2403. {
  2404. $secure=$this->getIsSecureConnection();
  2405. if($secure && $schema==='https' || !$secure && $schema==='http')
  2406. return $this->_hostInfo;
  2407. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2408. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2409. $port=':'.$port;
  2410. else
  2411. $port='';
  2412. $pos=strpos($this->_hostInfo,':');
  2413. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2414. }
  2415. else
  2416. return $this->_hostInfo;
  2417. }
  2418. public function setHostInfo($value)
  2419. {
  2420. $this->_hostInfo=rtrim($value,'/');
  2421. }
  2422. public function getBaseUrl($absolute=false)
  2423. {
  2424. if($this->_baseUrl===null)
  2425. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2426. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2427. }
  2428. public function setBaseUrl($value)
  2429. {
  2430. $this->_baseUrl=$value;
  2431. }
  2432. public function getScriptUrl()
  2433. {
  2434. if($this->_scriptUrl===null)
  2435. {
  2436. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2437. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2438. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2439. elseif(basename($_SERVER['PHP_SELF'])===$scriptName)
  2440. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2441. elseif(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2442. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2443. elseif(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2444. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2445. elseif(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2446. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2447. else
  2448. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2449. }
  2450. return $this->_scriptUrl;
  2451. }
  2452. public function setScriptUrl($value)
  2453. {
  2454. $this->_scriptUrl='/'.trim($value,'/');
  2455. }
  2456. public function getPathInfo()
  2457. {
  2458. if($this->_pathInfo===null)
  2459. {
  2460. $pathInfo=$this->getRequestUri();
  2461. if(($pos=strpos($pathInfo,'?'))!==false)
  2462. $pathInfo=substr($pathInfo,0,$pos);
  2463. $pathInfo=$this->decodePathInfo($pathInfo);
  2464. $scriptUrl=$this->getScriptUrl();
  2465. $baseUrl=$this->getBaseUrl();
  2466. if(strpos($pathInfo,$scriptUrl)===0)
  2467. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2468. elseif($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2469. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2470. elseif(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2471. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2472. else
  2473. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2474. if($pathInfo==='/')
  2475. $pathInfo='';
  2476. elseif($pathInfo[0]==='/')
  2477. $pathInfo=substr($pathInfo,1);
  2478. if(($posEnd=strlen($pathInfo)-1)>0 && $pathInfo[$posEnd]==='/')
  2479. $pathInfo=substr($pathInfo,0,$posEnd);
  2480. $this->_pathInfo=$pathInfo;
  2481. }
  2482. return $this->_pathInfo;
  2483. }
  2484. protected function decodePathInfo($pathInfo)
  2485. {
  2486. $pathInfo = urldecode($pathInfo);
  2487. // is it UTF-8?
  2488. // http://w3.org/International/questions/qa-forms-utf-8.html
  2489. if(preg_match('%^(?:
  2490. [\x09\x0A\x0D\x20-\x7E] # ASCII
  2491. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  2492. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  2493. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  2494. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  2495. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  2496. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  2497. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  2498. )*$%xs', $pathInfo))
  2499. {
  2500. return $pathInfo;
  2501. }
  2502. else
  2503. {
  2504. return utf8_encode($pathInfo);
  2505. }
  2506. }
  2507. public function getRequestUri()
  2508. {
  2509. if($this->_requestUri===null)
  2510. {
  2511. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2512. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2513. elseif(isset($_SERVER['REQUEST_URI']))
  2514. {
  2515. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2516. if(!empty($_SERVER['HTTP_HOST']))
  2517. {
  2518. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2519. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2520. }
  2521. else
  2522. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2523. }
  2524. elseif(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2525. {
  2526. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2527. if(!empty($_SERVER['QUERY_STRING']))
  2528. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2529. }
  2530. else
  2531. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2532. }
  2533. return $this->_requestUri;
  2534. }
  2535. public function getQueryString()
  2536. {
  2537. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2538. }
  2539. public function getIsSecureConnection()
  2540. {
  2541. return isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'],'on')===0 || $_SERVER['HTTPS']==1)
  2542. || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'],'https')===0;
  2543. }
  2544. public function getRequestType()
  2545. {
  2546. if(isset($_POST['_method']))
  2547. return strtoupper($_POST['_method']);
  2548. elseif(isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']))
  2549. return strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
  2550. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2551. }
  2552. public function getIsPostRequest()
  2553. {
  2554. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2555. }
  2556. public function getIsDeleteRequest()
  2557. {
  2558. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE')) || $this->getIsDeleteViaPostRequest();
  2559. }
  2560. protected function getIsDeleteViaPostRequest()
  2561. {
  2562. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'DELETE');
  2563. }
  2564. public function getIsPutRequest()
  2565. {
  2566. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT')) || $this->getIsPutViaPostRequest();
  2567. }
  2568. protected function getIsPutViaPostRequest()
  2569. {
  2570. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PUT');
  2571. }
  2572. public function getIsPatchRequest()
  2573. {
  2574. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PATCH')) || $this->getIsPatchViaPostRequest();
  2575. }
  2576. protected function getIsPatchViaPostRequest()
  2577. {
  2578. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PATCH');
  2579. }
  2580. public function getIsAjaxRequest()
  2581. {
  2582. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2583. }
  2584. public function getIsFlashRequest()
  2585. {
  2586. return isset($_SERVER['HTTP_USER_AGENT']) && (stripos($_SERVER['HTTP_USER_AGENT'],'Shockwave')!==false || stripos($_SERVER['HTTP_USER_AGENT'],'Flash')!==false);
  2587. }
  2588. public function getServerName()
  2589. {
  2590. return $_SERVER['SERVER_NAME'];
  2591. }
  2592. public function getServerPort()
  2593. {
  2594. return $_SERVER['SERVER_PORT'];
  2595. }
  2596. public function getUrlReferrer()
  2597. {
  2598. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2599. }
  2600. public function getUserAgent()
  2601. {
  2602. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2603. }
  2604. public function getUserHostAddress()
  2605. {
  2606. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2607. }
  2608. public function getUserHost()
  2609. {
  2610. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2611. }
  2612. public function getScriptFile()
  2613. {
  2614. if($this->_scriptFile!==null)
  2615. return $this->_scriptFile;
  2616. else
  2617. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2618. }
  2619. public function getBrowser($userAgent=null)
  2620. {
  2621. return get_browser($userAgent,true);
  2622. }
  2623. public function getAcceptTypes()
  2624. {
  2625. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2626. }
  2627. private $_port;
  2628. public function getPort()
  2629. {
  2630. if($this->_port===null)
  2631. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2632. return $this->_port;
  2633. }
  2634. public function setPort($value)
  2635. {
  2636. $this->_port=(int)$value;
  2637. $this->_hostInfo=null;
  2638. }
  2639. private $_securePort;
  2640. public function getSecurePort()
  2641. {
  2642. if($this->_securePort===null)
  2643. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2644. return $this->_securePort;
  2645. }
  2646. public function setSecurePort($value)
  2647. {
  2648. $this->_securePort=(int)$value;
  2649. $this->_hostInfo=null;
  2650. }
  2651. public function getCookies()
  2652. {
  2653. if($this->_cookies!==null)
  2654. return $this->_cookies;
  2655. else
  2656. return $this->_cookies=new CCookieCollection($this);
  2657. }
  2658. public function redirect($url,$terminate=true,$statusCode=302)
  2659. {
  2660. if(strpos($url,'/')===0 && strpos($url,'//')!==0)
  2661. $url=$this->getHostInfo().$url;
  2662. header('Location: '.$url, true, $statusCode);
  2663. if($terminate)
  2664. Yii::app()->end();
  2665. }
  2666. public static function parseAcceptHeader($header)
  2667. {
  2668. $matches=array();
  2669. $accepts=array();
  2670. // get individual entries with their type, subtype, basetype and params
  2671. preg_match_all('/(?:\G\s?,\s?|^)(\w+|\*)\/(\w+|\*)(?:\+(\w+))?|(?<!^)\G(?:\s?;\s?(\w+)=([\w\.]+))/',$header,$matches);
  2672. // the regexp should (in theory) always return an array of 6 arrays
  2673. if(count($matches)===6)
  2674. {
  2675. $i=0;
  2676. $itemLen=count($matches[1]);
  2677. while($i<$itemLen)
  2678. {
  2679. // fill out a content type
  2680. $accept=array(
  2681. 'type'=>$matches[1][$i],
  2682. 'subType'=>$matches[2][$i],
  2683. 'baseType'=>null,
  2684. 'params'=>array(),
  2685. );
  2686. // fill in the base type if it exists
  2687. if($matches[3][$i]!==null && $matches[3][$i]!=='')
  2688. $accept['baseType']=$matches[3][$i];
  2689. // continue looping while there is no new content type, to fill in all accompanying params
  2690. for($i++;$i<$itemLen;$i++)
  2691. {
  2692. // if the next content type is null, then the item is a param for the current content type
  2693. if($matches[1][$i]===null || $matches[1][$i]==='')
  2694. {
  2695. // if this is the quality param, convert it to a double
  2696. if($matches[4][$i]==='q')
  2697. {
  2698. // sanity check on q value
  2699. $q=(double)$matches[5][$i];
  2700. if($q>1)
  2701. $q=(double)1;
  2702. elseif($q<0)
  2703. $q=(double)0;
  2704. $accept['params'][$matches[4][$i]]=$q;
  2705. }
  2706. else
  2707. $accept['params'][$matches[4][$i]]=$matches[5][$i];
  2708. }
  2709. else
  2710. break;
  2711. }
  2712. // q defaults to 1 if not explicitly given
  2713. if(!isset($accept['params']['q']))
  2714. $accept['params']['q']=(double)1;
  2715. $accepts[] = $accept;
  2716. }
  2717. }
  2718. return $accepts;
  2719. }
  2720. public static function compareAcceptTypes($a,$b)
  2721. {
  2722. // check for equal quality first
  2723. if($a['params']['q']===$b['params']['q'])
  2724. if(!($a['type']==='*' xor $b['type']==='*'))
  2725. if (!($a['subType']==='*' xor $b['subType']==='*'))
  2726. // finally, higher number of parameters counts as greater precedence
  2727. if(count($a['params'])===count($b['params']))
  2728. return 0;
  2729. else
  2730. return count($a['params'])<count($b['params']) ? 1 : -1;
  2731. // more specific takes precedence - whichever one doesn't have a * subType
  2732. else
  2733. return $a['subType']==='*' ? 1 : -1;
  2734. // more specific takes precedence - whichever one doesn't have a * type
  2735. else
  2736. return $a['type']==='*' ? 1 : -1;
  2737. else
  2738. return ($a['params']['q']<$b['params']['q']) ? 1 : -1;
  2739. }
  2740. public function getPreferredAcceptTypes()
  2741. {
  2742. if($this->_preferredAcceptTypes===null)
  2743. {
  2744. $accepts=self::parseAcceptHeader($this->getAcceptTypes());
  2745. usort($accepts,array(get_class($this),'compareAcceptTypes'));
  2746. $this->_preferredAcceptTypes=$accepts;
  2747. }
  2748. return $this->_preferredAcceptTypes;
  2749. }
  2750. public function getPreferredAcceptType()
  2751. {
  2752. $preferredAcceptTypes=$this->getPreferredAcceptTypes();
  2753. return empty($preferredAcceptTypes) ? false : $preferredAcceptTypes[0];
  2754. }
  2755. public function getPreferredLanguages()
  2756. {
  2757. if($this->_preferredLanguages===null)
  2758. {
  2759. $sortedLanguages=array();
  2760. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $n=preg_match_all('/([\w\-_]+)(?:\s*;\s*q\s*=\s*(\d*\.?\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))
  2761. {
  2762. $languages=array();
  2763. for($i=0;$i<$n;++$i)
  2764. {
  2765. $q=$matches[2][$i];
  2766. if($q==='')
  2767. $q=1;
  2768. if($q)
  2769. $languages[]=array((float)$q,$matches[1][$i]);
  2770. }
  2771. usort($languages,create_function('$a,$b','if($a[0]==$b[0]) {return 0;} return ($a[0]<$b[0]) ? 1 : -1;'));
  2772. foreach($languages as $language)
  2773. $sortedLanguages[]=$language[1];
  2774. }
  2775. $this->_preferredLanguages=$sortedLanguages;
  2776. }
  2777. return $this->_preferredLanguages;
  2778. }
  2779. public function getPreferredLanguage($languages=array())
  2780. {
  2781. $preferredLanguages=$this->getPreferredLanguages();
  2782. if(empty($languages)) {
  2783. return !empty($preferredLanguages) ? CLocale::getCanonicalID($preferredLanguages[0]) : false;
  2784. }
  2785. foreach ($preferredLanguages as $preferredLanguage) {
  2786. $preferredLanguage=CLocale::getCanonicalID($preferredLanguage);
  2787. foreach ($languages as $language) {
  2788. $language=CLocale::getCanonicalID($language);
  2789. // en_us==en_us, en==en_us, en_us==en
  2790. if($language===$acceptedLanguage || strpos($acceptedLanguage,$language.'_')===0 || strpos($language,$acceptedLanguage.'_')===0) {
  2791. return $language;
  2792. }
  2793. }
  2794. }
  2795. return reset($languages);
  2796. }
  2797. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2798. {
  2799. if($mimeType===null)
  2800. {
  2801. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2802. $mimeType='text/plain';
  2803. }
  2804. $fileSize=(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content));
  2805. $contentStart=0;
  2806. $contentEnd=$fileSize-1;
  2807. if(isset($_SERVER['HTTP_RANGE']))
  2808. {
  2809. header('Accept-Ranges: bytes');
  2810. //client sent us a multibyte range, can not hold this one for now
  2811. if(strpos($_SERVER['HTTP_RANGE'],',')!==false)
  2812. {
  2813. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2814. throw new CHttpException(416,'Requested Range Not Satisfiable');
  2815. }
  2816. $range=str_replace('bytes=','',$_SERVER['HTTP_RANGE']);
  2817. //range requests starts from "-", so it means that data must be dumped the end point.
  2818. if($range[0]==='-')
  2819. $contentStart=$fileSize-substr($range,1);
  2820. else
  2821. {
  2822. $range=explode('-',$range);
  2823. $contentStart=$range[0];
  2824. // check if the last-byte-pos presents in header
  2825. if((isset($range[1]) && is_numeric($range[1])))
  2826. $contentEnd=$range[1];
  2827. }
  2828. /* Check the range and make sure it's treated according to the specs.
  2829. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  2830. */
  2831. // End bytes can not be larger than $end.
  2832. $contentEnd=($contentEnd > $fileSize) ? $fileSize-1 : $contentEnd;
  2833. // Validate the requested range and return an error if it's not correct.
  2834. $wrongContentStart=($contentStart>$contentEnd || $contentStart>$fileSize-1 || $contentStart<0);
  2835. if($wrongContentStart)
  2836. {
  2837. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2838. throw new CHttpException(416,'Requested Range Not Satisfiable');
  2839. }
  2840. header('HTTP/1.1 206 Partial Content');
  2841. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2842. }
  2843. else
  2844. header('HTTP/1.1 200 OK');
  2845. $length=$contentEnd-$contentStart+1; // Calculate new content length
  2846. header('Pragma: public');
  2847. header('Expires: 0');
  2848. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2849. header("Content-Type: $mimeType");
  2850. header('Content-Length: '.$length);
  2851. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2852. header('Content-Transfer-Encoding: binary');
  2853. $content=function_exists('mb_substr') ? mb_substr($content,$contentStart,$length) : substr($content,$contentStart,$length);
  2854. if($terminate)
  2855. {
  2856. // clean up the application first because the file downloading could take long time
  2857. // which may cause timeout of some resources (such as DB connection)
  2858. ob_start();
  2859. Yii::app()->end(0,false);
  2860. ob_end_clean();
  2861. echo $content;
  2862. exit(0);
  2863. }
  2864. else
  2865. echo $content;
  2866. }
  2867. public function xSendFile($filePath, $options=array())
  2868. {
  2869. if(!isset($options['forceDownload']) || $options['forceDownload'])
  2870. $disposition='attachment';
  2871. else
  2872. $disposition='inline';
  2873. if(!isset($options['saveName']))
  2874. $options['saveName']=basename($filePath);
  2875. if(!isset($options['mimeType']))
  2876. {
  2877. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2878. $options['mimeType']='text/plain';
  2879. }
  2880. if(!isset($options['xHeader']))
  2881. $options['xHeader']='X-Sendfile';
  2882. if($options['mimeType']!==null)
  2883. header('Content-Type: '.$options['mimeType']);
  2884. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  2885. if(isset($options['addHeaders']))
  2886. {
  2887. foreach($options['addHeaders'] as $header=>$value)
  2888. header($header.': '.$value);
  2889. }
  2890. header(trim($options['xHeader']).': '.$filePath);
  2891. if(!isset($options['terminate']) || $options['terminate'])
  2892. Yii::app()->end();
  2893. }
  2894. public function getCsrfToken()
  2895. {
  2896. if($this->_csrfToken===null)
  2897. {
  2898. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2899. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2900. {
  2901. $cookie=$this->createCsrfCookie();
  2902. $this->_csrfToken=$cookie->value;
  2903. $this->getCookies()->add($cookie->name,$cookie);
  2904. }
  2905. }
  2906. return $this->_csrfToken;
  2907. }
  2908. protected function createCsrfCookie()
  2909. {
  2910. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2911. if(is_array($this->csrfCookie))
  2912. {
  2913. foreach($this->csrfCookie as $name=>$value)
  2914. $cookie->$name=$value;
  2915. }
  2916. return $cookie;
  2917. }
  2918. public function validateCsrfToken($event)
  2919. {
  2920. if ($this->getIsPostRequest() ||
  2921. $this->getIsPutRequest() ||
  2922. $this->getIsPatchRequest() ||
  2923. $this->getIsDeleteRequest())
  2924. {
  2925. $cookies=$this->getCookies();
  2926. $method=$this->getRequestType();
  2927. switch($method)
  2928. {
  2929. case 'POST':
  2930. $userToken=$this->getPost($this->csrfTokenName);
  2931. break;
  2932. case 'PUT':
  2933. $userToken=$this->getPut($this->csrfTokenName);
  2934. break;
  2935. case 'PATCH':
  2936. $userToken=$this->getPatch($this->csrfTokenName);
  2937. break;
  2938. case 'DELETE':
  2939. $userToken=$this->getDelete($this->csrfTokenName);
  2940. }
  2941. if (!empty($userToken) && $cookies->contains($this->csrfTokenName))
  2942. {
  2943. $cookieToken=$cookies->itemAt($this->csrfTokenName)->value;
  2944. $valid=$cookieToken===$userToken;
  2945. }
  2946. else
  2947. $valid = false;
  2948. if (!$valid)
  2949. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2950. }
  2951. }
  2952. }
  2953. class CCookieCollection extends CMap
  2954. {
  2955. private $_request;
  2956. private $_initialized=false;
  2957. public function __construct(CHttpRequest $request)
  2958. {
  2959. $this->_request=$request;
  2960. $this->copyfrom($this->getCookies());
  2961. $this->_initialized=true;
  2962. }
  2963. public function getRequest()
  2964. {
  2965. return $this->_request;
  2966. }
  2967. protected function getCookies()
  2968. {
  2969. $cookies=array();
  2970. if($this->_request->enableCookieValidation)
  2971. {
  2972. $sm=Yii::app()->getSecurityManager();
  2973. foreach($_COOKIE as $name=>$value)
  2974. {
  2975. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  2976. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  2977. }
  2978. }
  2979. else
  2980. {
  2981. foreach($_COOKIE as $name=>$value)
  2982. $cookies[$name]=new CHttpCookie($name,$value);
  2983. }
  2984. return $cookies;
  2985. }
  2986. public function add($name,$cookie)
  2987. {
  2988. if($cookie instanceof CHttpCookie)
  2989. {
  2990. $this->remove($name);
  2991. parent::add($name,$cookie);
  2992. if($this->_initialized)
  2993. $this->addCookie($cookie);
  2994. }
  2995. else
  2996. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  2997. }
  2998. public function remove($name,$options=array())
  2999. {
  3000. if(($cookie=parent::remove($name))!==null)
  3001. {
  3002. if($this->_initialized)
  3003. {
  3004. $cookie->configure($options);
  3005. $this->removeCookie($cookie);
  3006. }
  3007. }
  3008. return $cookie;
  3009. }
  3010. protected function addCookie($cookie)
  3011. {
  3012. $value=$cookie->value;
  3013. if($this->_request->enableCookieValidation)
  3014. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  3015. if(version_compare(PHP_VERSION,'5.2.0','>='))
  3016. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  3017. else
  3018. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  3019. }
  3020. protected function removeCookie($cookie)
  3021. {
  3022. if(version_compare(PHP_VERSION,'5.2.0','>='))
  3023. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  3024. else
  3025. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure);
  3026. }
  3027. }
  3028. class CUrlManager extends CApplicationComponent
  3029. {
  3030. const CACHE_KEY='Yii.CUrlManager.rules';
  3031. const GET_FORMAT='get';
  3032. const PATH_FORMAT='path';
  3033. public $rules=array();
  3034. public $urlSuffix='';
  3035. public $showScriptName=true;
  3036. public $appendParams=true;
  3037. public $routeVar='r';
  3038. public $caseSensitive=true;
  3039. public $matchValue=false;
  3040. public $cacheID='cache';
  3041. public $useStrictParsing=false;
  3042. public $urlRuleClass='CUrlRule';
  3043. private $_urlFormat=self::GET_FORMAT;
  3044. private $_rules=array();
  3045. private $_baseUrl;
  3046. public function init()
  3047. {
  3048. parent::init();
  3049. $this->processRules();
  3050. }
  3051. protected function processRules()
  3052. {
  3053. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  3054. return;
  3055. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  3056. {
  3057. $hash=md5(serialize($this->rules));
  3058. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  3059. {
  3060. $this->_rules=$data[0];
  3061. return;
  3062. }
  3063. }
  3064. foreach($this->rules as $pattern=>$route)
  3065. $this->_rules[]=$this->createUrlRule($route,$pattern);
  3066. if(isset($cache))
  3067. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  3068. }
  3069. public function addRules($rules,$append=true)
  3070. {
  3071. if ($append)
  3072. {
  3073. foreach($rules as $pattern=>$route)
  3074. $this->_rules[]=$this->createUrlRule($route,$pattern);
  3075. }
  3076. else
  3077. {
  3078. $rules=array_reverse($rules);
  3079. foreach($rules as $pattern=>$route)
  3080. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  3081. }
  3082. }
  3083. protected function createUrlRule($route,$pattern)
  3084. {
  3085. if(is_array($route) && isset($route['class']))
  3086. return $route;
  3087. else
  3088. {
  3089. $urlRuleClass=Yii::import($this->urlRuleClass,true);
  3090. return new $urlRuleClass($route,$pattern);
  3091. }
  3092. }
  3093. public function createUrl($route,$params=array(),$ampersand='&')
  3094. {
  3095. unset($params[$this->routeVar]);
  3096. foreach($params as $i=>$param)
  3097. if($param===null)
  3098. $params[$i]='';
  3099. if(isset($params['#']))
  3100. {
  3101. $anchor='#'.$params['#'];
  3102. unset($params['#']);
  3103. }
  3104. else
  3105. $anchor='';
  3106. $route=trim($route,'/');
  3107. foreach($this->_rules as $i=>$rule)
  3108. {
  3109. if(is_array($rule))
  3110. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  3111. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  3112. {
  3113. if($rule->hasHostInfo)
  3114. return $url==='' ? '/'.$anchor : $url.$anchor;
  3115. else
  3116. return $this->getBaseUrl().'/'.$url.$anchor;
  3117. }
  3118. }
  3119. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  3120. }
  3121. protected function createUrlDefault($route,$params,$ampersand)
  3122. {
  3123. if($this->getUrlFormat()===self::PATH_FORMAT)
  3124. {
  3125. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  3126. if($this->appendParams)
  3127. {
  3128. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  3129. return $route==='' ? $url : $url.$this->urlSuffix;
  3130. }
  3131. else
  3132. {
  3133. if($route!=='')
  3134. $url.=$this->urlSuffix;
  3135. $query=$this->createPathInfo($params,'=',$ampersand);
  3136. return $query==='' ? $url : $url.'?'.$query;
  3137. }
  3138. }
  3139. else
  3140. {
  3141. $url=$this->getBaseUrl();
  3142. if(!$this->showScriptName)
  3143. $url.='/';
  3144. if($route!=='')
  3145. {
  3146. $url.='?'.$this->routeVar.'='.$route;
  3147. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  3148. $url.=$ampersand.$query;
  3149. }
  3150. elseif(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  3151. $url.='?'.$query;
  3152. return $url;
  3153. }
  3154. }
  3155. public function parseUrl($request)
  3156. {
  3157. if($this->getUrlFormat()===self::PATH_FORMAT)
  3158. {
  3159. $rawPathInfo=$request->getPathInfo();
  3160. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3161. foreach($this->_rules as $i=>$rule)
  3162. {
  3163. if(is_array($rule))
  3164. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  3165. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  3166. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  3167. }
  3168. if($this->useStrictParsing)
  3169. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  3170. array('{route}'=>$pathInfo)));
  3171. else
  3172. return $pathInfo;
  3173. }
  3174. elseif(isset($_GET[$this->routeVar]))
  3175. return $_GET[$this->routeVar];
  3176. elseif(isset($_POST[$this->routeVar]))
  3177. return $_POST[$this->routeVar];
  3178. else
  3179. return '';
  3180. }
  3181. public function parsePathInfo($pathInfo)
  3182. {
  3183. if($pathInfo==='')
  3184. return;
  3185. $segs=explode('/',$pathInfo.'/');
  3186. $n=count($segs);
  3187. for($i=0;$i<$n-1;$i+=2)
  3188. {
  3189. $key=$segs[$i];
  3190. if($key==='') continue;
  3191. $value=$segs[$i+1];
  3192. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  3193. {
  3194. $name=substr($key,0,$pos);
  3195. for($j=$m-1;$j>=0;--$j)
  3196. {
  3197. if($matches[1][$j]==='')
  3198. $value=array($value);
  3199. else
  3200. $value=array($matches[1][$j]=>$value);
  3201. }
  3202. if(isset($_GET[$name]) && is_array($_GET[$name]))
  3203. $value=CMap::mergeArray($_GET[$name],$value);
  3204. $_REQUEST[$name]=$_GET[$name]=$value;
  3205. }
  3206. else
  3207. $_REQUEST[$key]=$_GET[$key]=$value;
  3208. }
  3209. }
  3210. public function createPathInfo($params,$equal,$ampersand, $key=null)
  3211. {
  3212. $pairs = array();
  3213. foreach($params as $k => $v)
  3214. {
  3215. if ($key!==null)
  3216. $k = $key.'['.$k.']';
  3217. if (is_array($v))
  3218. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  3219. else
  3220. $pairs[]=urlencode($k).$equal.urlencode($v);
  3221. }
  3222. return implode($ampersand,$pairs);
  3223. }
  3224. public function removeUrlSuffix($pathInfo,$urlSuffix)
  3225. {
  3226. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  3227. return substr($pathInfo,0,-strlen($urlSuffix));
  3228. else
  3229. return $pathInfo;
  3230. }
  3231. public function getBaseUrl()
  3232. {
  3233. if($this->_baseUrl!==null)
  3234. return $this->_baseUrl;
  3235. else
  3236. {
  3237. if($this->showScriptName)
  3238. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  3239. else
  3240. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  3241. return $this->_baseUrl;
  3242. }
  3243. }
  3244. public function setBaseUrl($value)
  3245. {
  3246. $this->_baseUrl=$value;
  3247. }
  3248. public function getUrlFormat()
  3249. {
  3250. return $this->_urlFormat;
  3251. }
  3252. public function setUrlFormat($value)
  3253. {
  3254. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  3255. $this->_urlFormat=$value;
  3256. else
  3257. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  3258. }
  3259. }
  3260. abstract class CBaseUrlRule extends CComponent
  3261. {
  3262. public $hasHostInfo=false;
  3263. abstract public function createUrl($manager,$route,$params,$ampersand);
  3264. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  3265. }
  3266. class CUrlRule extends CBaseUrlRule
  3267. {
  3268. public $urlSuffix;
  3269. public $caseSensitive;
  3270. public $defaultParams=array();
  3271. public $matchValue;
  3272. public $verb;
  3273. public $parsingOnly=false;
  3274. public $route;
  3275. public $references=array();
  3276. public $routePattern;
  3277. public $pattern;
  3278. public $template;
  3279. public $params=array();
  3280. public $append;
  3281. public $hasHostInfo;
  3282. public function __construct($route,$pattern)
  3283. {
  3284. if(is_array($route))
  3285. {
  3286. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  3287. {
  3288. if(isset($route[$name]))
  3289. $this->$name=$route[$name];
  3290. }
  3291. if(isset($route['pattern']))
  3292. $pattern=$route['pattern'];
  3293. $route=$route[0];
  3294. }
  3295. $this->route=trim($route,'/');
  3296. $tr2['/']=$tr['/']='\\/';
  3297. $tr['.']='\\.';
  3298. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  3299. {
  3300. foreach($matches2[1] as $name)
  3301. $this->references[$name]="<$name>";
  3302. }
  3303. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  3304. if($this->verb!==null)
  3305. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  3306. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  3307. {
  3308. $tokens=array_combine($matches[1],$matches[2]);
  3309. foreach($tokens as $name=>$value)
  3310. {
  3311. if($value==='')
  3312. $value='[^\/]+';
  3313. $tr["<$name>"]="(?P<$name>$value)";
  3314. if(isset($this->references[$name]))
  3315. $tr2["<$name>"]=$tr["<$name>"];
  3316. else
  3317. $this->params[$name]=$value;
  3318. }
  3319. }
  3320. $p=rtrim($pattern,'*');
  3321. $this->append=$p!==$pattern;
  3322. $p=trim($p,'/');
  3323. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  3324. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  3325. if($this->append)
  3326. $this->pattern.='/u';
  3327. else
  3328. $this->pattern.='$/u';
  3329. if($this->references!==array())
  3330. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  3331. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  3332. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  3333. array('{route}'=>$route,'{pattern}'=>$pattern)));
  3334. }
  3335. public function createUrl($manager,$route,$params,$ampersand)
  3336. {
  3337. if($this->parsingOnly)
  3338. return false;
  3339. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3340. $case='';
  3341. else
  3342. $case='i';
  3343. $tr=array();
  3344. if($route!==$this->route)
  3345. {
  3346. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  3347. {
  3348. foreach($this->references as $key=>$name)
  3349. $tr[$name]=$matches[$key];
  3350. }
  3351. else
  3352. return false;
  3353. }
  3354. foreach($this->defaultParams as $key=>$value)
  3355. {
  3356. if(isset($params[$key]))
  3357. {
  3358. if($params[$key]==$value)
  3359. unset($params[$key]);
  3360. else
  3361. return false;
  3362. }
  3363. }
  3364. foreach($this->params as $key=>$value)
  3365. if(!isset($params[$key]))
  3366. return false;
  3367. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  3368. {
  3369. foreach($this->params as $key=>$value)
  3370. {
  3371. if(!preg_match('/\A'.$value.'\z/u'.$case,$params[$key]))
  3372. return false;
  3373. }
  3374. }
  3375. foreach($this->params as $key=>$value)
  3376. {
  3377. $tr["<$key>"]=urlencode($params[$key]);
  3378. unset($params[$key]);
  3379. }
  3380. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3381. $url=strtr($this->template,$tr);
  3382. if($this->hasHostInfo)
  3383. {
  3384. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  3385. if(stripos($url,$hostInfo)===0)
  3386. $url=substr($url,strlen($hostInfo));
  3387. }
  3388. if(empty($params))
  3389. return $url!=='' ? $url.$suffix : $url;
  3390. if($this->append)
  3391. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  3392. else
  3393. {
  3394. if($url!=='')
  3395. $url.=$suffix;
  3396. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  3397. }
  3398. return $url;
  3399. }
  3400. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  3401. {
  3402. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  3403. return false;
  3404. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3405. $case='';
  3406. else
  3407. $case='i';
  3408. if($this->urlSuffix!==null)
  3409. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3410. // URL suffix required, but not found in the requested URL
  3411. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3412. {
  3413. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3414. if($urlSuffix!='' && $urlSuffix!=='/')
  3415. return false;
  3416. }
  3417. if($this->hasHostInfo)
  3418. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3419. $pathInfo.='/';
  3420. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3421. {
  3422. foreach($this->defaultParams as $name=>$value)
  3423. {
  3424. if(!isset($_GET[$name]))
  3425. $_REQUEST[$name]=$_GET[$name]=$value;
  3426. }
  3427. $tr=array();
  3428. foreach($matches as $key=>$value)
  3429. {
  3430. if(isset($this->references[$key]))
  3431. $tr[$this->references[$key]]=$value;
  3432. elseif(isset($this->params[$key]))
  3433. $_REQUEST[$key]=$_GET[$key]=$value;
  3434. }
  3435. if($pathInfo!==$matches[0]) // there're additional GET params
  3436. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3437. if($this->routePattern!==null)
  3438. return strtr($this->route,$tr);
  3439. else
  3440. return $this->route;
  3441. }
  3442. else
  3443. return false;
  3444. }
  3445. }
  3446. abstract class CBaseController extends CComponent
  3447. {
  3448. private $_widgetStack=array();
  3449. abstract public function getViewFile($viewName);
  3450. public function renderFile($viewFile,$data=null,$return=false)
  3451. {
  3452. $widgetCount=count($this->_widgetStack);
  3453. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3454. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3455. else
  3456. $content=$this->renderInternal($viewFile,$data,$return);
  3457. if(count($this->_widgetStack)===$widgetCount)
  3458. return $content;
  3459. else
  3460. {
  3461. $widget=end($this->_widgetStack);
  3462. 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.',
  3463. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3464. }
  3465. }
  3466. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3467. {
  3468. // we use special variable names here to avoid conflict when extracting data
  3469. if(is_array($_data_))
  3470. extract($_data_,EXTR_PREFIX_SAME,'data');
  3471. else
  3472. $data=$_data_;
  3473. if($_return_)
  3474. {
  3475. ob_start();
  3476. ob_implicit_flush(false);
  3477. require($_viewFile_);
  3478. return ob_get_clean();
  3479. }
  3480. else
  3481. require($_viewFile_);
  3482. }
  3483. public function createWidget($className,$properties=array())
  3484. {
  3485. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3486. $widget->init();
  3487. return $widget;
  3488. }
  3489. public function widget($className,$properties=array(),$captureOutput=false)
  3490. {
  3491. if($captureOutput)
  3492. {
  3493. ob_start();
  3494. ob_implicit_flush(false);
  3495. try
  3496. {
  3497. $widget=$this->createWidget($className,$properties);
  3498. $widget->run();
  3499. }
  3500. catch(Exception $e)
  3501. {
  3502. ob_end_clean();
  3503. throw $e;
  3504. }
  3505. return ob_get_clean();
  3506. }
  3507. else
  3508. {
  3509. $widget=$this->createWidget($className,$properties);
  3510. $widget->run();
  3511. return $widget;
  3512. }
  3513. }
  3514. public function beginWidget($className,$properties=array())
  3515. {
  3516. $widget=$this->createWidget($className,$properties);
  3517. $this->_widgetStack[]=$widget;
  3518. return $widget;
  3519. }
  3520. public function endWidget($id='')
  3521. {
  3522. if(($widget=array_pop($this->_widgetStack))!==null)
  3523. {
  3524. $widget->run();
  3525. return $widget;
  3526. }
  3527. else
  3528. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3529. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3530. }
  3531. public function beginClip($id,$properties=array())
  3532. {
  3533. $properties['id']=$id;
  3534. $this->beginWidget('CClipWidget',$properties);
  3535. }
  3536. public function endClip()
  3537. {
  3538. $this->endWidget('CClipWidget');
  3539. }
  3540. public function beginCache($id,$properties=array())
  3541. {
  3542. $properties['id']=$id;
  3543. $cache=$this->beginWidget('COutputCache',$properties);
  3544. if($cache->getIsContentCached())
  3545. {
  3546. $this->endCache();
  3547. return false;
  3548. }
  3549. else
  3550. return true;
  3551. }
  3552. public function endCache()
  3553. {
  3554. $this->endWidget('COutputCache');
  3555. }
  3556. public function beginContent($view=null,$data=array())
  3557. {
  3558. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3559. }
  3560. public function endContent()
  3561. {
  3562. $this->endWidget('CContentDecorator');
  3563. }
  3564. }
  3565. class CController extends CBaseController
  3566. {
  3567. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3568. public $layout;
  3569. public $defaultAction='index';
  3570. private $_id;
  3571. private $_action;
  3572. private $_pageTitle;
  3573. private $_cachingStack;
  3574. private $_clips;
  3575. private $_dynamicOutput;
  3576. private $_pageStates;
  3577. private $_module;
  3578. public function __construct($id,$module=null)
  3579. {
  3580. $this->_id=$id;
  3581. $this->_module=$module;
  3582. $this->attachBehaviors($this->behaviors());
  3583. }
  3584. public function init()
  3585. {
  3586. }
  3587. public function filters()
  3588. {
  3589. return array();
  3590. }
  3591. public function actions()
  3592. {
  3593. return array();
  3594. }
  3595. public function behaviors()
  3596. {
  3597. return array();
  3598. }
  3599. public function accessRules()
  3600. {
  3601. return array();
  3602. }
  3603. public function run($actionID)
  3604. {
  3605. if(($action=$this->createAction($actionID))!==null)
  3606. {
  3607. if(($parent=$this->getModule())===null)
  3608. $parent=Yii::app();
  3609. if($parent->beforeControllerAction($this,$action))
  3610. {
  3611. $this->runActionWithFilters($action,$this->filters());
  3612. $parent->afterControllerAction($this,$action);
  3613. }
  3614. }
  3615. else
  3616. $this->missingAction($actionID);
  3617. }
  3618. public function runActionWithFilters($action,$filters)
  3619. {
  3620. if(empty($filters))
  3621. $this->runAction($action);
  3622. else
  3623. {
  3624. $priorAction=$this->_action;
  3625. $this->_action=$action;
  3626. CFilterChain::create($this,$action,$filters)->run();
  3627. $this->_action=$priorAction;
  3628. }
  3629. }
  3630. public function runAction($action)
  3631. {
  3632. $priorAction=$this->_action;
  3633. $this->_action=$action;
  3634. if($this->beforeAction($action))
  3635. {
  3636. if($action->runWithParams($this->getActionParams())===false)
  3637. $this->invalidActionParams($action);
  3638. else
  3639. $this->afterAction($action);
  3640. }
  3641. $this->_action=$priorAction;
  3642. }
  3643. public function getActionParams()
  3644. {
  3645. return $_GET;
  3646. }
  3647. public function invalidActionParams($action)
  3648. {
  3649. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3650. }
  3651. public function processOutput($output)
  3652. {
  3653. Yii::app()->getClientScript()->render($output);
  3654. // if using page caching, we should delay dynamic output replacement
  3655. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3656. {
  3657. $output=$this->processDynamicOutput($output);
  3658. $this->_dynamicOutput=null;
  3659. }
  3660. if($this->_pageStates===null)
  3661. $this->_pageStates=$this->loadPageStates();
  3662. if(!empty($this->_pageStates))
  3663. $this->savePageStates($this->_pageStates,$output);
  3664. return $output;
  3665. }
  3666. public function processDynamicOutput($output)
  3667. {
  3668. if($this->_dynamicOutput)
  3669. {
  3670. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3671. }
  3672. return $output;
  3673. }
  3674. protected function replaceDynamicOutput($matches)
  3675. {
  3676. $content=$matches[0];
  3677. if(isset($this->_dynamicOutput[$matches[1]]))
  3678. {
  3679. $content=$this->_dynamicOutput[$matches[1]];
  3680. $this->_dynamicOutput[$matches[1]]=null;
  3681. }
  3682. return $content;
  3683. }
  3684. public function createAction($actionID)
  3685. {
  3686. if($actionID==='')
  3687. $actionID=$this->defaultAction;
  3688. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3689. return new CInlineAction($this,$actionID);
  3690. else
  3691. {
  3692. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3693. if($action!==null && !method_exists($action,'run'))
  3694. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3695. return $action;
  3696. }
  3697. }
  3698. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3699. {
  3700. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3701. {
  3702. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3703. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3704. }
  3705. elseif($pos===false)
  3706. return null;
  3707. // the action is defined in a provider
  3708. $prefix=substr($actionID,0,$pos+1);
  3709. if(!isset($actionMap[$prefix]))
  3710. return null;
  3711. $actionID=(string)substr($actionID,$pos+1);
  3712. $provider=$actionMap[$prefix];
  3713. if(is_string($provider))
  3714. $providerType=$provider;
  3715. elseif(is_array($provider) && isset($provider['class']))
  3716. {
  3717. $providerType=$provider['class'];
  3718. if(isset($provider[$actionID]))
  3719. {
  3720. if(is_string($provider[$actionID]))
  3721. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3722. else
  3723. $config=array_merge($provider[$actionID],$config);
  3724. }
  3725. }
  3726. else
  3727. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3728. $class=Yii::import($providerType,true);
  3729. $map=call_user_func(array($class,'actions'));
  3730. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3731. }
  3732. public function missingAction($actionID)
  3733. {
  3734. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3735. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3736. }
  3737. public function getAction()
  3738. {
  3739. return $this->_action;
  3740. }
  3741. public function setAction($value)
  3742. {
  3743. $this->_action=$value;
  3744. }
  3745. public function getId()
  3746. {
  3747. return $this->_id;
  3748. }
  3749. public function getUniqueId()
  3750. {
  3751. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3752. }
  3753. public function getRoute()
  3754. {
  3755. if(($action=$this->getAction())!==null)
  3756. return $this->getUniqueId().'/'.$action->getId();
  3757. else
  3758. return $this->getUniqueId();
  3759. }
  3760. public function getModule()
  3761. {
  3762. return $this->_module;
  3763. }
  3764. public function getViewPath()
  3765. {
  3766. if(($module=$this->getModule())===null)
  3767. $module=Yii::app();
  3768. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3769. }
  3770. public function getViewFile($viewName)
  3771. {
  3772. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3773. return $viewFile;
  3774. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3775. if(($module=$this->getModule())!==null)
  3776. $moduleViewPath=$module->getViewPath();
  3777. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3778. }
  3779. public function getLayoutFile($layoutName)
  3780. {
  3781. if($layoutName===false)
  3782. return false;
  3783. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3784. return $layoutFile;
  3785. if(empty($layoutName))
  3786. {
  3787. $module=$this->getModule();
  3788. while($module!==null)
  3789. {
  3790. if($module->layout===false)
  3791. return false;
  3792. if(!empty($module->layout))
  3793. break;
  3794. $module=$module->getParentModule();
  3795. }
  3796. if($module===null)
  3797. $module=Yii::app();
  3798. $layoutName=$module->layout;
  3799. }
  3800. elseif(($module=$this->getModule())===null)
  3801. $module=Yii::app();
  3802. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3803. }
  3804. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3805. {
  3806. if(empty($viewName))
  3807. return false;
  3808. if($moduleViewPath===null)
  3809. $moduleViewPath=$basePath;
  3810. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3811. $extension=$renderer->fileExtension;
  3812. else
  3813. $extension='.php';
  3814. if($viewName[0]==='/')
  3815. {
  3816. if(strncmp($viewName,'//',2)===0)
  3817. $viewFile=$basePath.$viewName;
  3818. else
  3819. $viewFile=$moduleViewPath.$viewName;
  3820. }
  3821. elseif(strpos($viewName,'.'))
  3822. $viewFile=Yii::getPathOfAlias($viewName);
  3823. else
  3824. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3825. if(is_file($viewFile.$extension))
  3826. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3827. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  3828. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3829. else
  3830. return false;
  3831. }
  3832. public function getClips()
  3833. {
  3834. if($this->_clips!==null)
  3835. return $this->_clips;
  3836. else
  3837. return $this->_clips=new CMap;
  3838. }
  3839. public function forward($route,$exit=true)
  3840. {
  3841. if(strpos($route,'/')===false)
  3842. $this->run($route);
  3843. else
  3844. {
  3845. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3846. $route=$module->getId().'/'.$route;
  3847. Yii::app()->runController($route);
  3848. }
  3849. if($exit)
  3850. Yii::app()->end();
  3851. }
  3852. public function render($view,$data=null,$return=false)
  3853. {
  3854. if($this->beforeRender($view))
  3855. {
  3856. $output=$this->renderPartial($view,$data,true);
  3857. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3858. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3859. $this->afterRender($view,$output);
  3860. $output=$this->processOutput($output);
  3861. if($return)
  3862. return $output;
  3863. else
  3864. echo $output;
  3865. }
  3866. }
  3867. protected function beforeRender($view)
  3868. {
  3869. return true;
  3870. }
  3871. protected function afterRender($view, &$output)
  3872. {
  3873. }
  3874. public function renderText($text,$return=false)
  3875. {
  3876. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3877. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3878. $text=$this->processOutput($text);
  3879. if($return)
  3880. return $text;
  3881. else
  3882. echo $text;
  3883. }
  3884. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3885. {
  3886. if(($viewFile=$this->getViewFile($view))!==false)
  3887. {
  3888. $output=$this->renderFile($viewFile,$data,true);
  3889. if($processOutput)
  3890. $output=$this->processOutput($output);
  3891. if($return)
  3892. return $output;
  3893. else
  3894. echo $output;
  3895. }
  3896. else
  3897. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3898. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3899. }
  3900. public function renderClip($name,$params=array(),$return=false)
  3901. {
  3902. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  3903. if($return)
  3904. return $text;
  3905. else
  3906. echo $text;
  3907. }
  3908. public function renderDynamic($callback)
  3909. {
  3910. $n=count($this->_dynamicOutput);
  3911. echo "<###dynamic-$n###>";
  3912. $params=func_get_args();
  3913. array_shift($params);
  3914. $this->renderDynamicInternal($callback,$params);
  3915. }
  3916. public function renderDynamicInternal($callback,$params)
  3917. {
  3918. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3919. if(is_string($callback) && method_exists($this,$callback))
  3920. $callback=array($this,$callback);
  3921. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3922. }
  3923. public function createUrl($route,$params=array(),$ampersand='&')
  3924. {
  3925. if($route==='')
  3926. $route=$this->getId().'/'.$this->getAction()->getId();
  3927. elseif(strpos($route,'/')===false)
  3928. $route=$this->getId().'/'.$route;
  3929. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3930. $route=$module->getId().'/'.$route;
  3931. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3932. }
  3933. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3934. {
  3935. $url=$this->createUrl($route,$params,$ampersand);
  3936. if(strpos($url,'http')===0)
  3937. return $url;
  3938. else
  3939. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  3940. }
  3941. public function getPageTitle()
  3942. {
  3943. if($this->_pageTitle!==null)
  3944. return $this->_pageTitle;
  3945. else
  3946. {
  3947. $name=ucfirst(basename($this->getId()));
  3948. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3949. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3950. else
  3951. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3952. }
  3953. }
  3954. public function setPageTitle($value)
  3955. {
  3956. $this->_pageTitle=$value;
  3957. }
  3958. public function redirect($url,$terminate=true,$statusCode=302)
  3959. {
  3960. if(is_array($url))
  3961. {
  3962. $route=isset($url[0]) ? $url[0] : '';
  3963. $url=$this->createUrl($route,array_splice($url,1));
  3964. }
  3965. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  3966. }
  3967. public function refresh($terminate=true,$anchor='')
  3968. {
  3969. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  3970. }
  3971. public function recordCachingAction($context,$method,$params)
  3972. {
  3973. if($this->_cachingStack) // record only when there is an active output cache
  3974. {
  3975. foreach($this->_cachingStack as $cache)
  3976. $cache->recordAction($context,$method,$params);
  3977. }
  3978. }
  3979. public function getCachingStack($createIfNull=true)
  3980. {
  3981. if(!$this->_cachingStack)
  3982. $this->_cachingStack=new CStack;
  3983. return $this->_cachingStack;
  3984. }
  3985. public function isCachingStackEmpty()
  3986. {
  3987. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  3988. }
  3989. protected function beforeAction($action)
  3990. {
  3991. return true;
  3992. }
  3993. protected function afterAction($action)
  3994. {
  3995. }
  3996. public function filterPostOnly($filterChain)
  3997. {
  3998. if(Yii::app()->getRequest()->getIsPostRequest())
  3999. $filterChain->run();
  4000. else
  4001. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  4002. }
  4003. public function filterAjaxOnly($filterChain)
  4004. {
  4005. if(Yii::app()->getRequest()->getIsAjaxRequest())
  4006. $filterChain->run();
  4007. else
  4008. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  4009. }
  4010. public function filterAccessControl($filterChain)
  4011. {
  4012. $filter=new CAccessControlFilter;
  4013. $filter->setRules($this->accessRules());
  4014. $filter->filter($filterChain);
  4015. }
  4016. public function getPageState($name,$defaultValue=null)
  4017. {
  4018. if($this->_pageStates===null)
  4019. $this->_pageStates=$this->loadPageStates();
  4020. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  4021. }
  4022. public function setPageState($name,$value,$defaultValue=null)
  4023. {
  4024. if($this->_pageStates===null)
  4025. $this->_pageStates=$this->loadPageStates();
  4026. if($value===$defaultValue)
  4027. unset($this->_pageStates[$name]);
  4028. else
  4029. $this->_pageStates[$name]=$value;
  4030. $params=func_get_args();
  4031. $this->recordCachingAction('','setPageState',$params);
  4032. }
  4033. public function clearPageStates()
  4034. {
  4035. $this->_pageStates=array();
  4036. }
  4037. protected function loadPageStates()
  4038. {
  4039. if(!empty($_POST[self::STATE_INPUT_NAME]))
  4040. {
  4041. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  4042. {
  4043. if(extension_loaded('zlib'))
  4044. $data=@gzuncompress($data);
  4045. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  4046. return unserialize($data);
  4047. }
  4048. }
  4049. return array();
  4050. }
  4051. protected function savePageStates($states,&$output)
  4052. {
  4053. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  4054. if(extension_loaded('zlib'))
  4055. $data=gzcompress($data);
  4056. $value=base64_encode($data);
  4057. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  4058. }
  4059. }
  4060. abstract class CAction extends CComponent implements IAction
  4061. {
  4062. private $_id;
  4063. private $_controller;
  4064. public function __construct($controller,$id)
  4065. {
  4066. $this->_controller=$controller;
  4067. $this->_id=$id;
  4068. }
  4069. public function getController()
  4070. {
  4071. return $this->_controller;
  4072. }
  4073. public function getId()
  4074. {
  4075. return $this->_id;
  4076. }
  4077. public function runWithParams($params)
  4078. {
  4079. $method=new ReflectionMethod($this, 'run');
  4080. if($method->getNumberOfParameters()>0)
  4081. return $this->runWithParamsInternal($this, $method, $params);
  4082. else
  4083. return $this->run();
  4084. }
  4085. protected function runWithParamsInternal($object, $method, $params)
  4086. {
  4087. $ps=array();
  4088. foreach($method->getParameters() as $i=>$param)
  4089. {
  4090. $name=$param->getName();
  4091. if(isset($params[$name]))
  4092. {
  4093. if($param->isArray())
  4094. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  4095. elseif(!is_array($params[$name]))
  4096. $ps[]=$params[$name];
  4097. else
  4098. return false;
  4099. }
  4100. elseif($param->isDefaultValueAvailable())
  4101. $ps[]=$param->getDefaultValue();
  4102. else
  4103. return false;
  4104. }
  4105. $method->invokeArgs($object,$ps);
  4106. return true;
  4107. }
  4108. }
  4109. class CInlineAction extends CAction
  4110. {
  4111. public function run()
  4112. {
  4113. $method='action'.$this->getId();
  4114. $this->getController()->$method();
  4115. }
  4116. public function runWithParams($params)
  4117. {
  4118. $methodName='action'.$this->getId();
  4119. $controller=$this->getController();
  4120. $method=new ReflectionMethod($controller, $methodName);
  4121. if($method->getNumberOfParameters()>0)
  4122. return $this->runWithParamsInternal($controller, $method, $params);
  4123. else
  4124. return $controller->$methodName();
  4125. }
  4126. }
  4127. class CWebUser extends CApplicationComponent implements IWebUser
  4128. {
  4129. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  4130. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  4131. const STATES_VAR='__states';
  4132. const AUTH_TIMEOUT_VAR='__timeout';
  4133. const AUTH_ABSOLUTE_TIMEOUT_VAR='__absolute_timeout';
  4134. public $allowAutoLogin=false;
  4135. public $guestName='Guest';
  4136. public $loginUrl=array('/site/login');
  4137. public $identityCookie;
  4138. public $authTimeout;
  4139. public $absoluteAuthTimeout;
  4140. public $autoRenewCookie=false;
  4141. public $autoUpdateFlash=true;
  4142. public $loginRequiredAjaxResponse;
  4143. private $_keyPrefix;
  4144. private $_access=array();
  4145. public function __get($name)
  4146. {
  4147. if($this->hasState($name))
  4148. return $this->getState($name);
  4149. else
  4150. return parent::__get($name);
  4151. }
  4152. public function __set($name,$value)
  4153. {
  4154. if($this->hasState($name))
  4155. $this->setState($name,$value);
  4156. else
  4157. parent::__set($name,$value);
  4158. }
  4159. public function __isset($name)
  4160. {
  4161. if($this->hasState($name))
  4162. return $this->getState($name)!==null;
  4163. else
  4164. return parent::__isset($name);
  4165. }
  4166. public function __unset($name)
  4167. {
  4168. if($this->hasState($name))
  4169. $this->setState($name,null);
  4170. else
  4171. parent::__unset($name);
  4172. }
  4173. public function init()
  4174. {
  4175. parent::init();
  4176. Yii::app()->getSession()->open();
  4177. if($this->getIsGuest() && $this->allowAutoLogin)
  4178. $this->restoreFromCookie();
  4179. elseif($this->autoRenewCookie && $this->allowAutoLogin)
  4180. $this->renewCookie();
  4181. if($this->autoUpdateFlash)
  4182. $this->updateFlash();
  4183. $this->updateAuthStatus();
  4184. }
  4185. public function login($identity,$duration=0)
  4186. {
  4187. $id=$identity->getId();
  4188. $states=$identity->getPersistentStates();
  4189. if($this->beforeLogin($id,$states,false))
  4190. {
  4191. $this->changeIdentity($id,$identity->getName(),$states);
  4192. if($duration>0)
  4193. {
  4194. if($this->allowAutoLogin)
  4195. $this->saveToCookie($duration);
  4196. else
  4197. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  4198. array('{class}'=>get_class($this))));
  4199. }
  4200. if ($this->absoluteAuthTimeout)
  4201. $this->setState(self::AUTH_ABSOLUTE_TIMEOUT_VAR, time()+$this->absoluteAuthTimeout);
  4202. $this->afterLogin(false);
  4203. }
  4204. return !$this->getIsGuest();
  4205. }
  4206. public function logout($destroySession=true)
  4207. {
  4208. if($this->beforeLogout())
  4209. {
  4210. if($this->allowAutoLogin)
  4211. {
  4212. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  4213. if($this->identityCookie!==null)
  4214. {
  4215. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4216. $cookie->value=null;
  4217. $cookie->expire=0;
  4218. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  4219. }
  4220. }
  4221. if($destroySession)
  4222. Yii::app()->getSession()->destroy();
  4223. else
  4224. $this->clearStates();
  4225. $this->_access=array();
  4226. $this->afterLogout();
  4227. }
  4228. }
  4229. public function getIsGuest()
  4230. {
  4231. return $this->getState('__id')===null;
  4232. }
  4233. public function getId()
  4234. {
  4235. return $this->getState('__id');
  4236. }
  4237. public function setId($value)
  4238. {
  4239. $this->setState('__id',$value);
  4240. }
  4241. public function getName()
  4242. {
  4243. if(($name=$this->getState('__name'))!==null)
  4244. return $name;
  4245. else
  4246. return $this->guestName;
  4247. }
  4248. public function setName($value)
  4249. {
  4250. $this->setState('__name',$value);
  4251. }
  4252. public function getReturnUrl($defaultUrl=null)
  4253. {
  4254. if($defaultUrl===null)
  4255. {
  4256. $defaultReturnUrl=Yii::app()->getUrlManager()->showScriptName ? Yii::app()->getRequest()->getScriptUrl() : Yii::app()->getRequest()->getBaseUrl().'/';
  4257. }
  4258. else
  4259. {
  4260. $defaultReturnUrl=CHtml::normalizeUrl($defaultUrl);
  4261. }
  4262. return $this->getState('__returnUrl',$defaultReturnUrl);
  4263. }
  4264. public function setReturnUrl($value)
  4265. {
  4266. $this->setState('__returnUrl',$value);
  4267. }
  4268. public function loginRequired()
  4269. {
  4270. $app=Yii::app();
  4271. $request=$app->getRequest();
  4272. if(!$request->getIsAjaxRequest())
  4273. {
  4274. $this->setReturnUrl($request->getUrl());
  4275. if(($url=$this->loginUrl)!==null)
  4276. {
  4277. if(is_array($url))
  4278. {
  4279. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  4280. $url=$app->createUrl($route,array_splice($url,1));
  4281. }
  4282. $request->redirect($url);
  4283. }
  4284. }
  4285. elseif(isset($this->loginRequiredAjaxResponse))
  4286. {
  4287. echo $this->loginRequiredAjaxResponse;
  4288. Yii::app()->end();
  4289. }
  4290. throw new CHttpException(403,Yii::t('yii','Login Required'));
  4291. }
  4292. protected function beforeLogin($id,$states,$fromCookie)
  4293. {
  4294. return true;
  4295. }
  4296. protected function afterLogin($fromCookie)
  4297. {
  4298. }
  4299. protected function beforeLogout()
  4300. {
  4301. return true;
  4302. }
  4303. protected function afterLogout()
  4304. {
  4305. }
  4306. protected function restoreFromCookie()
  4307. {
  4308. $app=Yii::app();
  4309. $request=$app->getRequest();
  4310. $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  4311. if($cookie && !empty($cookie->value) && is_string($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  4312. {
  4313. $data=@unserialize($data);
  4314. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4315. {
  4316. list($id,$name,$duration,$states)=$data;
  4317. if($this->beforeLogin($id,$states,true))
  4318. {
  4319. $this->changeIdentity($id,$name,$states);
  4320. if($this->autoRenewCookie)
  4321. {
  4322. $this->saveToCookie($duration);
  4323. }
  4324. $this->afterLogin(true);
  4325. }
  4326. }
  4327. }
  4328. }
  4329. protected function renewCookie()
  4330. {
  4331. $request=Yii::app()->getRequest();
  4332. $cookies=$request->getCookies();
  4333. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  4334. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  4335. {
  4336. $data=@unserialize($data);
  4337. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4338. {
  4339. $this->saveToCookie($data[2]);
  4340. }
  4341. }
  4342. }
  4343. protected function saveToCookie($duration)
  4344. {
  4345. $app=Yii::app();
  4346. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4347. $cookie->expire=time()+$duration;
  4348. $data=array(
  4349. $this->getId(),
  4350. $this->getName(),
  4351. $duration,
  4352. $this->saveIdentityStates(),
  4353. );
  4354. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  4355. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  4356. }
  4357. protected function createIdentityCookie($name)
  4358. {
  4359. $cookie=new CHttpCookie($name,'');
  4360. if(is_array($this->identityCookie))
  4361. {
  4362. foreach($this->identityCookie as $name=>$value)
  4363. $cookie->$name=$value;
  4364. }
  4365. return $cookie;
  4366. }
  4367. public function getStateKeyPrefix()
  4368. {
  4369. if($this->_keyPrefix!==null)
  4370. return $this->_keyPrefix;
  4371. else
  4372. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  4373. }
  4374. public function setStateKeyPrefix($value)
  4375. {
  4376. $this->_keyPrefix=$value;
  4377. }
  4378. public function getState($key,$defaultValue=null)
  4379. {
  4380. $key=$this->getStateKeyPrefix().$key;
  4381. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4382. }
  4383. public function setState($key,$value,$defaultValue=null)
  4384. {
  4385. $key=$this->getStateKeyPrefix().$key;
  4386. if($value===$defaultValue)
  4387. unset($_SESSION[$key]);
  4388. else
  4389. $_SESSION[$key]=$value;
  4390. }
  4391. public function hasState($key)
  4392. {
  4393. $key=$this->getStateKeyPrefix().$key;
  4394. return isset($_SESSION[$key]);
  4395. }
  4396. public function clearStates()
  4397. {
  4398. $keys=array_keys($_SESSION);
  4399. $prefix=$this->getStateKeyPrefix();
  4400. $n=strlen($prefix);
  4401. foreach($keys as $key)
  4402. {
  4403. if(!strncmp($key,$prefix,$n))
  4404. unset($_SESSION[$key]);
  4405. }
  4406. }
  4407. public function getFlashes($delete=true)
  4408. {
  4409. $flashes=array();
  4410. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  4411. $keys=array_keys($_SESSION);
  4412. $n=strlen($prefix);
  4413. foreach($keys as $key)
  4414. {
  4415. if(!strncmp($key,$prefix,$n))
  4416. {
  4417. $flashes[substr($key,$n)]=$_SESSION[$key];
  4418. if($delete)
  4419. unset($_SESSION[$key]);
  4420. }
  4421. }
  4422. if($delete)
  4423. $this->setState(self::FLASH_COUNTERS,array());
  4424. return $flashes;
  4425. }
  4426. public function getFlash($key,$defaultValue=null,$delete=true)
  4427. {
  4428. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4429. if($delete)
  4430. $this->setFlash($key,null);
  4431. return $value;
  4432. }
  4433. public function setFlash($key,$value,$defaultValue=null)
  4434. {
  4435. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4436. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4437. if($value===$defaultValue)
  4438. unset($counters[$key]);
  4439. else
  4440. $counters[$key]=0;
  4441. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4442. }
  4443. public function hasFlash($key)
  4444. {
  4445. return $this->getFlash($key, null, false)!==null;
  4446. }
  4447. protected function changeIdentity($id,$name,$states)
  4448. {
  4449. Yii::app()->getSession()->regenerateID(true);
  4450. $this->setId($id);
  4451. $this->setName($name);
  4452. $this->loadIdentityStates($states);
  4453. }
  4454. protected function saveIdentityStates()
  4455. {
  4456. $states=array();
  4457. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4458. $states[$name]=$this->getState($name);
  4459. return $states;
  4460. }
  4461. protected function loadIdentityStates($states)
  4462. {
  4463. $names=array();
  4464. if(is_array($states))
  4465. {
  4466. foreach($states as $name=>$value)
  4467. {
  4468. $this->setState($name,$value);
  4469. $names[$name]=true;
  4470. }
  4471. }
  4472. $this->setState(self::STATES_VAR,$names);
  4473. }
  4474. protected function updateFlash()
  4475. {
  4476. $counters=$this->getState(self::FLASH_COUNTERS);
  4477. if(!is_array($counters))
  4478. return;
  4479. foreach($counters as $key=>$count)
  4480. {
  4481. if($count)
  4482. {
  4483. unset($counters[$key]);
  4484. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4485. }
  4486. else
  4487. $counters[$key]++;
  4488. }
  4489. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4490. }
  4491. protected function updateAuthStatus()
  4492. {
  4493. if(($this->authTimeout!==null || $this->absoluteAuthTimeout!==null) && !$this->getIsGuest())
  4494. {
  4495. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4496. $expiresAbsolute=$this->getState(self::AUTH_ABSOLUTE_TIMEOUT_VAR);
  4497. if ($expires!==null && $expires < time() || $expiresAbsolute!==null && $expiresAbsolute < time())
  4498. $this->logout(false);
  4499. else
  4500. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4501. }
  4502. }
  4503. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4504. {
  4505. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4506. return $this->_access[$operation];
  4507. $access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4508. if($allowCaching && $params===array())
  4509. $this->_access[$operation]=$access;
  4510. return $access;
  4511. }
  4512. }
  4513. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4514. {
  4515. public $autoStart=true;
  4516. public function init()
  4517. {
  4518. parent::init();
  4519. if($this->autoStart)
  4520. $this->open();
  4521. register_shutdown_function(array($this,'close'));
  4522. }
  4523. public function getUseCustomStorage()
  4524. {
  4525. return false;
  4526. }
  4527. public function open()
  4528. {
  4529. if($this->getUseCustomStorage())
  4530. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4531. @session_start();
  4532. if(YII_DEBUG && session_id()=='')
  4533. {
  4534. $message=Yii::t('yii','Failed to start session.');
  4535. if(function_exists('error_get_last'))
  4536. {
  4537. $error=error_get_last();
  4538. if(isset($error['message']))
  4539. $message=$error['message'];
  4540. }
  4541. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4542. }
  4543. }
  4544. public function close()
  4545. {
  4546. if(session_id()!=='')
  4547. @session_write_close();
  4548. }
  4549. public function destroy()
  4550. {
  4551. if(session_id()!=='')
  4552. {
  4553. @session_unset();
  4554. @session_destroy();
  4555. }
  4556. }
  4557. public function getIsStarted()
  4558. {
  4559. return session_id()!=='';
  4560. }
  4561. public function getSessionID()
  4562. {
  4563. return session_id();
  4564. }
  4565. public function setSessionID($value)
  4566. {
  4567. session_id($value);
  4568. }
  4569. public function regenerateID($deleteOldSession=false)
  4570. {
  4571. session_regenerate_id($deleteOldSession);
  4572. }
  4573. public function getSessionName()
  4574. {
  4575. return session_name();
  4576. }
  4577. public function setSessionName($value)
  4578. {
  4579. session_name($value);
  4580. }
  4581. public function getSavePath()
  4582. {
  4583. return session_save_path();
  4584. }
  4585. public function setSavePath($value)
  4586. {
  4587. if(is_dir($value))
  4588. session_save_path($value);
  4589. else
  4590. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4591. array('{path}'=>$value)));
  4592. }
  4593. public function getCookieParams()
  4594. {
  4595. return session_get_cookie_params();
  4596. }
  4597. public function setCookieParams($value)
  4598. {
  4599. $data=session_get_cookie_params();
  4600. extract($data);
  4601. extract($value);
  4602. if(isset($httponly))
  4603. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4604. else
  4605. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4606. }
  4607. public function getCookieMode()
  4608. {
  4609. if(ini_get('session.use_cookies')==='0')
  4610. return 'none';
  4611. elseif(ini_get('session.use_only_cookies')==='0')
  4612. return 'allow';
  4613. else
  4614. return 'only';
  4615. }
  4616. public function setCookieMode($value)
  4617. {
  4618. if($value==='none')
  4619. {
  4620. ini_set('session.use_cookies','0');
  4621. ini_set('session.use_only_cookies','0');
  4622. }
  4623. elseif($value==='allow')
  4624. {
  4625. ini_set('session.use_cookies','1');
  4626. ini_set('session.use_only_cookies','0');
  4627. }
  4628. elseif($value==='only')
  4629. {
  4630. ini_set('session.use_cookies','1');
  4631. ini_set('session.use_only_cookies','1');
  4632. }
  4633. else
  4634. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4635. }
  4636. public function getGCProbability()
  4637. {
  4638. return (float)(ini_get('session.gc_probability')/ini_get('session.gc_divisor')*100);
  4639. }
  4640. public function setGCProbability($value)
  4641. {
  4642. if($value>=0 && $value<=100)
  4643. {
  4644. // percent * 21474837 / 2147483647 ≈ percent * 0.01
  4645. ini_set('session.gc_probability',floor($value*21474836.47));
  4646. ini_set('session.gc_divisor',2147483647);
  4647. }
  4648. else
  4649. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be a float between 0 and 100.',
  4650. array('{value}'=>$value)));
  4651. }
  4652. public function getUseTransparentSessionID()
  4653. {
  4654. return ini_get('session.use_trans_sid')==1;
  4655. }
  4656. public function setUseTransparentSessionID($value)
  4657. {
  4658. ini_set('session.use_trans_sid',$value?'1':'0');
  4659. }
  4660. public function getTimeout()
  4661. {
  4662. return (int)ini_get('session.gc_maxlifetime');
  4663. }
  4664. public function setTimeout($value)
  4665. {
  4666. ini_set('session.gc_maxlifetime',$value);
  4667. }
  4668. public function openSession($savePath,$sessionName)
  4669. {
  4670. return true;
  4671. }
  4672. public function closeSession()
  4673. {
  4674. return true;
  4675. }
  4676. public function readSession($id)
  4677. {
  4678. return '';
  4679. }
  4680. public function writeSession($id,$data)
  4681. {
  4682. return true;
  4683. }
  4684. public function destroySession($id)
  4685. {
  4686. return true;
  4687. }
  4688. public function gcSession($maxLifetime)
  4689. {
  4690. return true;
  4691. }
  4692. //------ The following methods enable CHttpSession to be CMap-like -----
  4693. public function getIterator()
  4694. {
  4695. return new CHttpSessionIterator;
  4696. }
  4697. public function getCount()
  4698. {
  4699. return count($_SESSION);
  4700. }
  4701. public function count()
  4702. {
  4703. return $this->getCount();
  4704. }
  4705. public function getKeys()
  4706. {
  4707. return array_keys($_SESSION);
  4708. }
  4709. public function get($key,$defaultValue=null)
  4710. {
  4711. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4712. }
  4713. public function itemAt($key)
  4714. {
  4715. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4716. }
  4717. public function add($key,$value)
  4718. {
  4719. $_SESSION[$key]=$value;
  4720. }
  4721. public function remove($key)
  4722. {
  4723. if(isset($_SESSION[$key]))
  4724. {
  4725. $value=$_SESSION[$key];
  4726. unset($_SESSION[$key]);
  4727. return $value;
  4728. }
  4729. else
  4730. return null;
  4731. }
  4732. public function clear()
  4733. {
  4734. foreach(array_keys($_SESSION) as $key)
  4735. unset($_SESSION[$key]);
  4736. }
  4737. public function contains($key)
  4738. {
  4739. return isset($_SESSION[$key]);
  4740. }
  4741. public function toArray()
  4742. {
  4743. return $_SESSION;
  4744. }
  4745. public function offsetExists($offset)
  4746. {
  4747. return isset($_SESSION[$offset]);
  4748. }
  4749. public function offsetGet($offset)
  4750. {
  4751. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4752. }
  4753. public function offsetSet($offset,$item)
  4754. {
  4755. $_SESSION[$offset]=$item;
  4756. }
  4757. public function offsetUnset($offset)
  4758. {
  4759. unset($_SESSION[$offset]);
  4760. }
  4761. }
  4762. class CHtml
  4763. {
  4764. const ID_PREFIX='yt';
  4765. public static $errorSummaryCss='errorSummary';
  4766. public static $errorMessageCss='errorMessage';
  4767. public static $errorCss='error';
  4768. public static $errorContainerTag='div';
  4769. public static $requiredCss='required';
  4770. public static $beforeRequiredLabel='';
  4771. public static $afterRequiredLabel=' <span class="required">*</span>';
  4772. public static $count=0;
  4773. public static $liveEvents=true;
  4774. public static $closeSingleTags=true;
  4775. public static $renderSpecialAttributesValue=true;
  4776. private static $_modelNameConverter;
  4777. public static function encode($text)
  4778. {
  4779. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4780. }
  4781. public static function decode($text)
  4782. {
  4783. return htmlspecialchars_decode($text,ENT_QUOTES);
  4784. }
  4785. public static function encodeArray($data)
  4786. {
  4787. $d=array();
  4788. foreach($data as $key=>$value)
  4789. {
  4790. if(is_string($key))
  4791. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4792. if(is_string($value))
  4793. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4794. elseif(is_array($value))
  4795. $value=self::encodeArray($value);
  4796. $d[$key]=$value;
  4797. }
  4798. return $d;
  4799. }
  4800. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4801. {
  4802. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4803. if($content===false)
  4804. return $closeTag && self::$closeSingleTags ? $html.' />' : $html.'>';
  4805. else
  4806. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4807. }
  4808. public static function openTag($tag,$htmlOptions=array())
  4809. {
  4810. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4811. }
  4812. public static function closeTag($tag)
  4813. {
  4814. return '</'.$tag.'>';
  4815. }
  4816. public static function cdata($text)
  4817. {
  4818. return '<![CDATA[' . $text . ']]>';
  4819. }
  4820. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4821. {
  4822. if($name!==null)
  4823. $options['name']=$name;
  4824. if($httpEquiv!==null)
  4825. $options['http-equiv']=$httpEquiv;
  4826. $options['content']=$content;
  4827. return self::tag('meta',$options);
  4828. }
  4829. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4830. {
  4831. if($relation!==null)
  4832. $options['rel']=$relation;
  4833. if($type!==null)
  4834. $options['type']=$type;
  4835. if($href!==null)
  4836. $options['href']=$href;
  4837. if($media!==null)
  4838. $options['media']=$media;
  4839. return self::tag('link',$options);
  4840. }
  4841. public static function css($text,$media='')
  4842. {
  4843. if($media!=='')
  4844. $media=' media="'.$media.'"';
  4845. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4846. }
  4847. public static function refresh($seconds,$url='')
  4848. {
  4849. $content="$seconds";
  4850. if($url!=='')
  4851. $content.=';url='.self::normalizeUrl($url);
  4852. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4853. }
  4854. public static function cssFile($url,$media='')
  4855. {
  4856. return CHtml::linkTag('stylesheet','text/css',$url,$media!=='' ? $media : null);
  4857. }
  4858. public static function script($text,array $htmlOptions=array())
  4859. {
  4860. $defaultHtmlOptions=array(
  4861. 'type'=>'text/javascript',
  4862. );
  4863. $htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
  4864. return self::tag('script',$htmlOptions,"\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n");
  4865. }
  4866. public static function scriptFile($url,array $htmlOptions=array())
  4867. {
  4868. $defaultHtmlOptions=array(
  4869. 'type'=>'text/javascript',
  4870. 'src'=>$url
  4871. );
  4872. $htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
  4873. return self::tag('script',$htmlOptions,'');
  4874. }
  4875. public static function form($action='',$method='post',$htmlOptions=array())
  4876. {
  4877. return self::beginForm($action,$method,$htmlOptions);
  4878. }
  4879. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4880. {
  4881. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4882. if(strcasecmp($method,'get')!==0 && strcasecmp($method,'post')!==0)
  4883. {
  4884. $customMethod=$method;
  4885. $method='post';
  4886. }
  4887. else
  4888. $customMethod=false;
  4889. $htmlOptions['method']=$method;
  4890. $form=self::tag('form',$htmlOptions,false,false);
  4891. $hiddens=array();
  4892. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4893. {
  4894. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4895. {
  4896. if(($pos=strpos($pair,'='))!==false)
  4897. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4898. else
  4899. $hiddens[]=self::hiddenField(urldecode($pair),'',array('id'=>false));
  4900. }
  4901. }
  4902. $request=Yii::app()->request;
  4903. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4904. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4905. if($customMethod!==false)
  4906. $hiddens[]=self::hiddenField('_method',$customMethod);
  4907. if($hiddens!==array())
  4908. $form.="\n".implode("\n",$hiddens);
  4909. return $form;
  4910. }
  4911. public static function endForm()
  4912. {
  4913. return '</form>';
  4914. }
  4915. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4916. {
  4917. return self::form($action,$method,$htmlOptions)."\n".
  4918. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4919. }
  4920. public static function pageStateField($value)
  4921. {
  4922. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4923. }
  4924. public static function link($text,$url='#',$htmlOptions=array())
  4925. {
  4926. if($url!=='')
  4927. $htmlOptions['href']=self::normalizeUrl($url);
  4928. self::clientChange('click',$htmlOptions);
  4929. return self::tag('a',$htmlOptions,$text);
  4930. }
  4931. public static function mailto($text,$email='',$htmlOptions=array())
  4932. {
  4933. if($email==='')
  4934. $email=$text;
  4935. return self::link($text,'mailto:'.$email,$htmlOptions);
  4936. }
  4937. public static function image($src,$alt='',$htmlOptions=array())
  4938. {
  4939. $htmlOptions['src']=$src;
  4940. $htmlOptions['alt']=$alt;
  4941. return self::tag('img',$htmlOptions);
  4942. }
  4943. public static function button($label='button',$htmlOptions=array())
  4944. {
  4945. if(!isset($htmlOptions['name']))
  4946. {
  4947. if(!array_key_exists('name',$htmlOptions))
  4948. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4949. }
  4950. if(!isset($htmlOptions['type']))
  4951. $htmlOptions['type']='button';
  4952. if(!isset($htmlOptions['value']) && $htmlOptions['type']!='image')
  4953. $htmlOptions['value']=$label;
  4954. self::clientChange('click',$htmlOptions);
  4955. return self::tag('input',$htmlOptions);
  4956. }
  4957. public static function htmlButton($label='button',$htmlOptions=array())
  4958. {
  4959. if(!isset($htmlOptions['name']))
  4960. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4961. if(!isset($htmlOptions['type']))
  4962. $htmlOptions['type']='button';
  4963. self::clientChange('click',$htmlOptions);
  4964. return self::tag('button',$htmlOptions,$label);
  4965. }
  4966. public static function submitButton($label='submit',$htmlOptions=array())
  4967. {
  4968. $htmlOptions['type']='submit';
  4969. return self::button($label,$htmlOptions);
  4970. }
  4971. public static function resetButton($label='reset',$htmlOptions=array())
  4972. {
  4973. $htmlOptions['type']='reset';
  4974. return self::button($label,$htmlOptions);
  4975. }
  4976. public static function imageButton($src,$htmlOptions=array())
  4977. {
  4978. $htmlOptions['src']=$src;
  4979. $htmlOptions['type']='image';
  4980. return self::button('submit',$htmlOptions);
  4981. }
  4982. public static function linkButton($label='submit',$htmlOptions=array())
  4983. {
  4984. if(!isset($htmlOptions['submit']))
  4985. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  4986. return self::link($label,'#',$htmlOptions);
  4987. }
  4988. public static function label($label,$for,$htmlOptions=array())
  4989. {
  4990. if($for===false)
  4991. unset($htmlOptions['for']);
  4992. else
  4993. $htmlOptions['for']=$for;
  4994. if(isset($htmlOptions['required']))
  4995. {
  4996. if($htmlOptions['required'])
  4997. {
  4998. if(isset($htmlOptions['class']))
  4999. $htmlOptions['class'].=' '.self::$requiredCss;
  5000. else
  5001. $htmlOptions['class']=self::$requiredCss;
  5002. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  5003. }
  5004. unset($htmlOptions['required']);
  5005. }
  5006. return self::tag('label',$htmlOptions,$label);
  5007. }
  5008. public static function colorField($name,$value='',$htmlOptions=array())
  5009. {
  5010. self::clientChange('change',$htmlOptions);
  5011. return self::inputField('color',$name,$value,$htmlOptions);
  5012. }
  5013. public static function textField($name,$value='',$htmlOptions=array())
  5014. {
  5015. self::clientChange('change',$htmlOptions);
  5016. return self::inputField('text',$name,$value,$htmlOptions);
  5017. }
  5018. public static function searchField($name,$value='',$htmlOptions=array())
  5019. {
  5020. self::clientChange('change',$htmlOptions);
  5021. return self::inputField('search',$name,$value,$htmlOptions);
  5022. }
  5023. public static function numberField($name,$value='',$htmlOptions=array())
  5024. {
  5025. self::clientChange('change',$htmlOptions);
  5026. return self::inputField('number',$name,$value,$htmlOptions);
  5027. }
  5028. public static function rangeField($name,$value='',$htmlOptions=array())
  5029. {
  5030. self::clientChange('change',$htmlOptions);
  5031. return self::inputField('range',$name,$value,$htmlOptions);
  5032. }
  5033. public static function dateField($name,$value='',$htmlOptions=array())
  5034. {
  5035. self::clientChange('change',$htmlOptions);
  5036. return self::inputField('date',$name,$value,$htmlOptions);
  5037. }
  5038. public static function timeField($name,$value='',$htmlOptions=array())
  5039. {
  5040. self::clientChange('change',$htmlOptions);
  5041. return self::inputField('time',$name,$value,$htmlOptions);
  5042. }
  5043. public static function dateTimeField($name,$value='',$htmlOptions=array())
  5044. {
  5045. self::clientChange('change',$htmlOptions);
  5046. return self::inputField('datetime',$name,$value,$htmlOptions);
  5047. }
  5048. public static function dateTimeLocalField($name,$value='',$htmlOptions=array())
  5049. {
  5050. self::clientChange('change',$htmlOptions);
  5051. return self::inputField('datetime-local',$name,$value,$htmlOptions);
  5052. }
  5053. public static function weekField($name,$value='',$htmlOptions=array())
  5054. {
  5055. self::clientChange('change',$htmlOptions);
  5056. return self::inputField('week',$name,$value,$htmlOptions);
  5057. }
  5058. public static function emailField($name,$value='',$htmlOptions=array())
  5059. {
  5060. self::clientChange('change',$htmlOptions);
  5061. return self::inputField('email',$name,$value,$htmlOptions);
  5062. }
  5063. public static function telField($name,$value='',$htmlOptions=array())
  5064. {
  5065. self::clientChange('change',$htmlOptions);
  5066. return self::inputField('tel',$name,$value,$htmlOptions);
  5067. }
  5068. public static function urlField($name,$value='',$htmlOptions=array())
  5069. {
  5070. self::clientChange('change',$htmlOptions);
  5071. return self::inputField('url',$name,$value,$htmlOptions);
  5072. }
  5073. public static function hiddenField($name,$value='',$htmlOptions=array())
  5074. {
  5075. return self::inputField('hidden',$name,$value,$htmlOptions);
  5076. }
  5077. public static function passwordField($name,$value='',$htmlOptions=array())
  5078. {
  5079. self::clientChange('change',$htmlOptions);
  5080. return self::inputField('password',$name,$value,$htmlOptions);
  5081. }
  5082. public static function fileField($name,$value='',$htmlOptions=array())
  5083. {
  5084. return self::inputField('file',$name,$value,$htmlOptions);
  5085. }
  5086. public static function textArea($name,$value='',$htmlOptions=array())
  5087. {
  5088. $htmlOptions['name']=$name;
  5089. if(!isset($htmlOptions['id']))
  5090. $htmlOptions['id']=self::getIdByName($name);
  5091. elseif($htmlOptions['id']===false)
  5092. unset($htmlOptions['id']);
  5093. self::clientChange('change',$htmlOptions);
  5094. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  5095. }
  5096. public static function radioButton($name,$checked=false,$htmlOptions=array())
  5097. {
  5098. if($checked)
  5099. $htmlOptions['checked']='checked';
  5100. else
  5101. unset($htmlOptions['checked']);
  5102. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  5103. self::clientChange('click',$htmlOptions);
  5104. if(array_key_exists('uncheckValue',$htmlOptions))
  5105. {
  5106. $uncheck=$htmlOptions['uncheckValue'];
  5107. unset($htmlOptions['uncheckValue']);
  5108. }
  5109. else
  5110. $uncheck=null;
  5111. if($uncheck!==null)
  5112. {
  5113. // add a hidden field so that if the radio button is not selected, it still submits a value
  5114. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  5115. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  5116. else
  5117. $uncheckOptions=array('id'=>false);
  5118. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  5119. }
  5120. else
  5121. $hidden='';
  5122. // add a hidden field so that if the radio button is not selected, it still submits a value
  5123. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  5124. }
  5125. public static function checkBox($name,$checked=false,$htmlOptions=array())
  5126. {
  5127. if($checked)
  5128. $htmlOptions['checked']='checked';
  5129. else
  5130. unset($htmlOptions['checked']);
  5131. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  5132. self::clientChange('click',$htmlOptions);
  5133. if(array_key_exists('uncheckValue',$htmlOptions))
  5134. {
  5135. $uncheck=$htmlOptions['uncheckValue'];
  5136. unset($htmlOptions['uncheckValue']);
  5137. }
  5138. else
  5139. $uncheck=null;
  5140. if($uncheck!==null)
  5141. {
  5142. // add a hidden field so that if the check box is not checked, it still submits a value
  5143. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  5144. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  5145. else
  5146. $uncheckOptions=array('id'=>false);
  5147. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  5148. }
  5149. else
  5150. $hidden='';
  5151. // add a hidden field so that if the check box is not checked, it still submits a value
  5152. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  5153. }
  5154. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  5155. {
  5156. $htmlOptions['name']=$name;
  5157. if(!isset($htmlOptions['id']))
  5158. $htmlOptions['id']=self::getIdByName($name);
  5159. elseif($htmlOptions['id']===false)
  5160. unset($htmlOptions['id']);
  5161. self::clientChange('change',$htmlOptions);
  5162. $options="\n".self::listOptions($select,$data,$htmlOptions);
  5163. $hidden='';
  5164. if(!empty($htmlOptions['multiple']))
  5165. {
  5166. if(substr($htmlOptions['name'],-2)!=='[]')
  5167. $htmlOptions['name'].='[]';
  5168. if(isset($htmlOptions['unselectValue']))
  5169. {
  5170. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5171. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  5172. unset($htmlOptions['unselectValue']);
  5173. }
  5174. }
  5175. // add a hidden field so that if the option is not selected, it still submits a value
  5176. return $hidden . self::tag('select',$htmlOptions,$options);
  5177. }
  5178. public static function listBox($name,$select,$data,$htmlOptions=array())
  5179. {
  5180. if(!isset($htmlOptions['size']))
  5181. $htmlOptions['size']=4;
  5182. if(!empty($htmlOptions['multiple']))
  5183. {
  5184. if(substr($name,-2)!=='[]')
  5185. $name.='[]';
  5186. }
  5187. return self::dropDownList($name,$select,$data,$htmlOptions);
  5188. }
  5189. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  5190. {
  5191. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  5192. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:self::tag('br');
  5193. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  5194. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  5195. if(substr($name,-2)!=='[]')
  5196. $name.='[]';
  5197. if(isset($htmlOptions['checkAll']))
  5198. {
  5199. $checkAllLabel=$htmlOptions['checkAll'];
  5200. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  5201. }
  5202. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  5203. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  5204. unset($htmlOptions['labelOptions']);
  5205. $items=array();
  5206. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  5207. unset($htmlOptions['baseID']);
  5208. $id=0;
  5209. $checkAll=true;
  5210. foreach($data as $value=>$labelTitle)
  5211. {
  5212. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  5213. $checkAll=$checkAll && $checked;
  5214. $htmlOptions['value']=$value;
  5215. $htmlOptions['id']=$baseID.'_'.$id++;
  5216. $option=self::checkBox($name,$checked,$htmlOptions);
  5217. $beginLabel=self::openTag('label',$labelOptions);
  5218. $label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
  5219. $endLabel=self::closeTag('label');
  5220. $items[]=strtr($template,array(
  5221. '{input}'=>$option,
  5222. '{beginLabel}'=>$beginLabel,
  5223. '{label}'=>$label,
  5224. '{labelTitle}'=>$labelTitle,
  5225. '{endLabel}'=>$endLabel,
  5226. ));
  5227. }
  5228. if(isset($checkAllLabel))
  5229. {
  5230. $htmlOptions['value']=1;
  5231. $htmlOptions['id']=$id=$baseID.'_all';
  5232. $option=self::checkBox($id,$checkAll,$htmlOptions);
  5233. $beginLabel=self::openTag('label',$labelOptions);
  5234. $label=self::label($checkAllLabel,$id,$labelOptions);
  5235. $endLabel=self::closeTag('label');
  5236. $item=strtr($template,array(
  5237. '{input}'=>$option,
  5238. '{beginLabel}'=>$beginLabel,
  5239. '{label}'=>$label,
  5240. '{labelTitle}'=>$checkAllLabel,
  5241. '{endLabel}'=>$endLabel,
  5242. ));
  5243. if($checkAllLast)
  5244. $items[]=$item;
  5245. else
  5246. array_unshift($items,$item);
  5247. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  5248. $js=<<<EOD
  5249. jQuery('#$id').click(function() {
  5250. jQuery("input[name='$name']").prop('checked', this.checked);
  5251. });
  5252. jQuery("input[name='$name']").click(function() {
  5253. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  5254. });
  5255. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  5256. EOD;
  5257. $cs=Yii::app()->getClientScript();
  5258. $cs->registerCoreScript('jquery');
  5259. $cs->registerScript($id,$js);
  5260. }
  5261. if(empty($container))
  5262. return implode($separator,$items);
  5263. else
  5264. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  5265. }
  5266. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  5267. {
  5268. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  5269. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:self::tag('br');
  5270. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  5271. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  5272. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  5273. unset($htmlOptions['labelOptions']);
  5274. if(isset($htmlOptions['empty']))
  5275. {
  5276. if(!is_array($htmlOptions['empty']))
  5277. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5278. $data=CMap::mergeArray($htmlOptions['empty'],$data);
  5279. unset($htmlOptions['empty']);
  5280. }
  5281. $items=array();
  5282. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  5283. unset($htmlOptions['baseID']);
  5284. $id=0;
  5285. foreach($data as $value=>$labelTitle)
  5286. {
  5287. $checked=!strcmp($value,$select);
  5288. $htmlOptions['value']=$value;
  5289. $htmlOptions['id']=$baseID.'_'.$id++;
  5290. $option=self::radioButton($name,$checked,$htmlOptions);
  5291. $beginLabel=self::openTag('label',$labelOptions);
  5292. $label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
  5293. $endLabel=self::closeTag('label');
  5294. $items[]=strtr($template,array(
  5295. '{input}'=>$option,
  5296. '{beginLabel}'=>$beginLabel,
  5297. '{label}'=>$label,
  5298. '{labelTitle}'=>$labelTitle,
  5299. '{endLabel}'=>$endLabel,
  5300. ));
  5301. }
  5302. if(empty($container))
  5303. return implode($separator,$items);
  5304. else
  5305. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  5306. }
  5307. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  5308. {
  5309. if(!isset($htmlOptions['href']))
  5310. $htmlOptions['href']='#';
  5311. $ajaxOptions['url']=$url;
  5312. $htmlOptions['ajax']=$ajaxOptions;
  5313. self::clientChange('click',$htmlOptions);
  5314. return self::tag('a',$htmlOptions,$text);
  5315. }
  5316. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  5317. {
  5318. $ajaxOptions['url']=$url;
  5319. $htmlOptions['ajax']=$ajaxOptions;
  5320. return self::button($label,$htmlOptions);
  5321. }
  5322. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  5323. {
  5324. $ajaxOptions['type']='POST';
  5325. $htmlOptions['type']='submit';
  5326. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  5327. }
  5328. public static function ajax($options)
  5329. {
  5330. Yii::app()->getClientScript()->registerCoreScript('jquery');
  5331. if(!isset($options['url']))
  5332. $options['url']=new CJavaScriptExpression('location.href');
  5333. else
  5334. $options['url']=self::normalizeUrl($options['url']);
  5335. if(!isset($options['cache']))
  5336. $options['cache']=false;
  5337. if(!isset($options['data']) && isset($options['type']))
  5338. $options['data']=new CJavaScriptExpression('jQuery(this).parents("form").serialize()');
  5339. foreach(array('beforeSend','complete','error','success') as $name)
  5340. {
  5341. if(isset($options[$name]) && !($options[$name] instanceof CJavaScriptExpression))
  5342. $options[$name]=new CJavaScriptExpression($options[$name]);
  5343. }
  5344. if(isset($options['update']))
  5345. {
  5346. if(!isset($options['success']))
  5347. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['update'].'").html(html)}');
  5348. unset($options['update']);
  5349. }
  5350. if(isset($options['replace']))
  5351. {
  5352. if(!isset($options['success']))
  5353. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['replace'].'").replaceWith(html)}');
  5354. unset($options['replace']);
  5355. }
  5356. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  5357. }
  5358. public static function asset($path,$hashByName=false)
  5359. {
  5360. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  5361. }
  5362. public static function normalizeUrl($url)
  5363. {
  5364. if(is_array($url))
  5365. {
  5366. if(isset($url[0]))
  5367. {
  5368. if(($c=Yii::app()->getController())!==null)
  5369. $url=$c->createUrl($url[0],array_splice($url,1));
  5370. else
  5371. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  5372. }
  5373. else
  5374. $url='';
  5375. }
  5376. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  5377. }
  5378. protected static function inputField($type,$name,$value,$htmlOptions)
  5379. {
  5380. $htmlOptions['type']=$type;
  5381. $htmlOptions['value']=$value;
  5382. $htmlOptions['name']=$name;
  5383. if(!isset($htmlOptions['id']))
  5384. $htmlOptions['id']=self::getIdByName($name);
  5385. elseif($htmlOptions['id']===false)
  5386. unset($htmlOptions['id']);
  5387. return self::tag('input',$htmlOptions);
  5388. }
  5389. public static function activeLabel($model,$attribute,$htmlOptions=array())
  5390. {
  5391. $inputName=self::resolveName($model,$attribute);
  5392. if(isset($htmlOptions['for']))
  5393. {
  5394. $for=$htmlOptions['for'];
  5395. unset($htmlOptions['for']);
  5396. }
  5397. else
  5398. $for=self::getIdByName($inputName);
  5399. if(isset($htmlOptions['label']))
  5400. {
  5401. if(($label=$htmlOptions['label'])===false)
  5402. return '';
  5403. unset($htmlOptions['label']);
  5404. }
  5405. else
  5406. $label=$model->getAttributeLabel($attribute);
  5407. if($model->hasErrors($attribute))
  5408. self::addErrorCss($htmlOptions);
  5409. return self::label($label,$for,$htmlOptions);
  5410. }
  5411. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  5412. {
  5413. $realAttribute=$attribute;
  5414. self::resolveName($model,$attribute); // strip off square brackets if any
  5415. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  5416. return self::activeLabel($model,$realAttribute,$htmlOptions);
  5417. }
  5418. public static function activeTextField($model,$attribute,$htmlOptions=array())
  5419. {
  5420. self::resolveNameID($model,$attribute,$htmlOptions);
  5421. self::clientChange('change',$htmlOptions);
  5422. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  5423. }
  5424. public static function activeSearchField($model,$attribute,$htmlOptions=array())
  5425. {
  5426. self::resolveNameID($model,$attribute,$htmlOptions);
  5427. self::clientChange('change',$htmlOptions);
  5428. return self::activeInputField('search',$model,$attribute,$htmlOptions);
  5429. }
  5430. public static function activeUrlField($model,$attribute,$htmlOptions=array())
  5431. {
  5432. self::resolveNameID($model,$attribute,$htmlOptions);
  5433. self::clientChange('change',$htmlOptions);
  5434. return self::activeInputField('url',$model,$attribute,$htmlOptions);
  5435. }
  5436. public static function activeEmailField($model,$attribute,$htmlOptions=array())
  5437. {
  5438. self::resolveNameID($model,$attribute,$htmlOptions);
  5439. self::clientChange('change',$htmlOptions);
  5440. return self::activeInputField('email',$model,$attribute,$htmlOptions);
  5441. }
  5442. public static function activeNumberField($model,$attribute,$htmlOptions=array())
  5443. {
  5444. self::resolveNameID($model,$attribute,$htmlOptions);
  5445. self::clientChange('change',$htmlOptions);
  5446. return self::activeInputField('number',$model,$attribute,$htmlOptions);
  5447. }
  5448. public static function activeRangeField($model,$attribute,$htmlOptions=array())
  5449. {
  5450. self::resolveNameID($model,$attribute,$htmlOptions);
  5451. self::clientChange('change',$htmlOptions);
  5452. return self::activeInputField('range',$model,$attribute,$htmlOptions);
  5453. }
  5454. public static function activeDateField($model,$attribute,$htmlOptions=array())
  5455. {
  5456. self::resolveNameID($model,$attribute,$htmlOptions);
  5457. self::clientChange('change',$htmlOptions);
  5458. return self::activeInputField('date',$model,$attribute,$htmlOptions);
  5459. }
  5460. public static function activeTimeField($model,$attribute,$htmlOptions=array())
  5461. {
  5462. self::resolveNameID($model,$attribute,$htmlOptions);
  5463. self::clientChange('change',$htmlOptions);
  5464. return self::activeInputField('time',$model,$attribute,$htmlOptions);
  5465. }
  5466. public static function activeDateTimeField($model,$attribute,$htmlOptions=array())
  5467. {
  5468. self::resolveNameID($model,$attribute,$htmlOptions);
  5469. self::clientChange('change',$htmlOptions);
  5470. return self::activeInputField('datetime',$model,$attribute,$htmlOptions);
  5471. }
  5472. public static function activeDateTimeLocalField($model,$attribute,$htmlOptions=array())
  5473. {
  5474. self::resolveNameID($model,$attribute,$htmlOptions);
  5475. self::clientChange('change',$htmlOptions);
  5476. return self::activeInputField('datetime-local',$model,$attribute,$htmlOptions);
  5477. }
  5478. public static function activeWeekField($model,$attribute,$htmlOptions=array())
  5479. {
  5480. self::resolveNameID($model,$attribute,$htmlOptions);
  5481. self::clientChange('change',$htmlOptions);
  5482. return self::activeInputField('week',$model,$attribute,$htmlOptions);
  5483. }
  5484. public static function activeColorField($model,$attribute,$htmlOptions=array())
  5485. {
  5486. self::resolveNameID($model,$attribute,$htmlOptions);
  5487. self::clientChange('change',$htmlOptions);
  5488. return self::activeInputField('color',$model,$attribute,$htmlOptions);
  5489. }
  5490. public static function activeTelField($model,$attribute,$htmlOptions=array())
  5491. {
  5492. self::resolveNameID($model,$attribute,$htmlOptions);
  5493. self::clientChange('change',$htmlOptions);
  5494. return self::activeInputField('tel',$model,$attribute,$htmlOptions);
  5495. }
  5496. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  5497. {
  5498. self::resolveNameID($model,$attribute,$htmlOptions);
  5499. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  5500. }
  5501. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  5502. {
  5503. self::resolveNameID($model,$attribute,$htmlOptions);
  5504. self::clientChange('change',$htmlOptions);
  5505. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  5506. }
  5507. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  5508. {
  5509. self::resolveNameID($model,$attribute,$htmlOptions);
  5510. self::clientChange('change',$htmlOptions);
  5511. if($model->hasErrors($attribute))
  5512. self::addErrorCss($htmlOptions);
  5513. if(isset($htmlOptions['value']))
  5514. {
  5515. $text=$htmlOptions['value'];
  5516. unset($htmlOptions['value']);
  5517. }
  5518. else
  5519. $text=self::resolveValue($model,$attribute);
  5520. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  5521. }
  5522. public static function activeFileField($model,$attribute,$htmlOptions=array())
  5523. {
  5524. self::resolveNameID($model,$attribute,$htmlOptions);
  5525. // add a hidden field so that if a model only has a file field, we can
  5526. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  5527. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5528. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  5529. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  5530. }
  5531. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  5532. {
  5533. self::resolveNameID($model,$attribute,$htmlOptions);
  5534. if(!isset($htmlOptions['value']))
  5535. $htmlOptions['value']=1;
  5536. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5537. $htmlOptions['checked']='checked';
  5538. self::clientChange('click',$htmlOptions);
  5539. if(array_key_exists('uncheckValue',$htmlOptions))
  5540. {
  5541. $uncheck=$htmlOptions['uncheckValue'];
  5542. unset($htmlOptions['uncheckValue']);
  5543. }
  5544. else
  5545. $uncheck='0';
  5546. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5547. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5548. // add a hidden field so that if the radio button is not selected, it still submits a value
  5549. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  5550. }
  5551. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  5552. {
  5553. self::resolveNameID($model,$attribute,$htmlOptions);
  5554. if(!isset($htmlOptions['value']))
  5555. $htmlOptions['value']=1;
  5556. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5557. $htmlOptions['checked']='checked';
  5558. self::clientChange('click',$htmlOptions);
  5559. if(array_key_exists('uncheckValue',$htmlOptions))
  5560. {
  5561. $uncheck=$htmlOptions['uncheckValue'];
  5562. unset($htmlOptions['uncheckValue']);
  5563. }
  5564. else
  5565. $uncheck='0';
  5566. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5567. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5568. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  5569. }
  5570. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  5571. {
  5572. self::resolveNameID($model,$attribute,$htmlOptions);
  5573. $selection=self::resolveValue($model,$attribute);
  5574. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  5575. self::clientChange('change',$htmlOptions);
  5576. if($model->hasErrors($attribute))
  5577. self::addErrorCss($htmlOptions);
  5578. $hidden='';
  5579. if(!empty($htmlOptions['multiple']))
  5580. {
  5581. if(substr($htmlOptions['name'],-2)!=='[]')
  5582. $htmlOptions['name'].='[]';
  5583. if(isset($htmlOptions['unselectValue']))
  5584. {
  5585. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5586. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  5587. unset($htmlOptions['unselectValue']);
  5588. }
  5589. }
  5590. return $hidden . self::tag('select',$htmlOptions,$options);
  5591. }
  5592. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  5593. {
  5594. if(!isset($htmlOptions['size']))
  5595. $htmlOptions['size']=4;
  5596. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  5597. }
  5598. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  5599. {
  5600. self::resolveNameID($model,$attribute,$htmlOptions);
  5601. $selection=self::resolveValue($model,$attribute);
  5602. if($model->hasErrors($attribute))
  5603. self::addErrorCss($htmlOptions);
  5604. $name=$htmlOptions['name'];
  5605. unset($htmlOptions['name']);
  5606. if(array_key_exists('uncheckValue',$htmlOptions))
  5607. {
  5608. $uncheck=$htmlOptions['uncheckValue'];
  5609. unset($htmlOptions['uncheckValue']);
  5610. }
  5611. else
  5612. $uncheck='';
  5613. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5614. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5615. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  5616. }
  5617. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  5618. {
  5619. self::resolveNameID($model,$attribute,$htmlOptions);
  5620. $selection=self::resolveValue($model,$attribute);
  5621. if($model->hasErrors($attribute))
  5622. self::addErrorCss($htmlOptions);
  5623. $name=$htmlOptions['name'];
  5624. unset($htmlOptions['name']);
  5625. if(array_key_exists('uncheckValue',$htmlOptions))
  5626. {
  5627. $uncheck=$htmlOptions['uncheckValue'];
  5628. unset($htmlOptions['uncheckValue']);
  5629. }
  5630. else
  5631. $uncheck='';
  5632. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5633. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5634. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  5635. }
  5636. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  5637. {
  5638. $content='';
  5639. if(!is_array($model))
  5640. $model=array($model);
  5641. if(isset($htmlOptions['firstError']))
  5642. {
  5643. $firstError=$htmlOptions['firstError'];
  5644. unset($htmlOptions['firstError']);
  5645. }
  5646. else
  5647. $firstError=false;
  5648. foreach($model as $m)
  5649. {
  5650. foreach($m->getErrors() as $errors)
  5651. {
  5652. foreach($errors as $error)
  5653. {
  5654. if($error!='')
  5655. $content.="<li>$error</li>\n";
  5656. if($firstError)
  5657. break;
  5658. }
  5659. }
  5660. }
  5661. if($content!=='')
  5662. {
  5663. if($header===null)
  5664. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5665. if(!isset($htmlOptions['class']))
  5666. $htmlOptions['class']=self::$errorSummaryCss;
  5667. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5668. }
  5669. else
  5670. return '';
  5671. }
  5672. public static function error($model,$attribute,$htmlOptions=array())
  5673. {
  5674. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5675. $error=$model->getError($attribute);
  5676. if($error!='')
  5677. {
  5678. if(!isset($htmlOptions['class']))
  5679. $htmlOptions['class']=self::$errorMessageCss;
  5680. return self::tag(self::$errorContainerTag,$htmlOptions,$error);
  5681. }
  5682. else
  5683. return '';
  5684. }
  5685. public static function listData($models,$valueField,$textField,$groupField='')
  5686. {
  5687. $listData=array();
  5688. if($groupField==='')
  5689. {
  5690. foreach($models as $model)
  5691. {
  5692. $value=self::value($model,$valueField);
  5693. $text=self::value($model,$textField);
  5694. $listData[$value]=$text;
  5695. }
  5696. }
  5697. else
  5698. {
  5699. foreach($models as $model)
  5700. {
  5701. $group=self::value($model,$groupField);
  5702. $value=self::value($model,$valueField);
  5703. $text=self::value($model,$textField);
  5704. if($group===null)
  5705. $listData[$value]=$text;
  5706. else
  5707. $listData[$group][$value]=$text;
  5708. }
  5709. }
  5710. return $listData;
  5711. }
  5712. public static function value($model,$attribute,$defaultValue=null)
  5713. {
  5714. if(is_scalar($attribute) || $attribute===null)
  5715. foreach(explode('.',$attribute) as $name)
  5716. {
  5717. if(is_object($model) && isset($model->$name))
  5718. $model=$model->$name;
  5719. elseif(is_array($model) && isset($model[$name]))
  5720. $model=$model[$name];
  5721. else
  5722. return $defaultValue;
  5723. }
  5724. else
  5725. return call_user_func($attribute,$model);
  5726. return $model;
  5727. }
  5728. public static function getIdByName($name)
  5729. {
  5730. return str_replace(array('[]','][','[',']',' '),array('','_','_','','_'),$name);
  5731. }
  5732. public static function activeId($model,$attribute)
  5733. {
  5734. return self::getIdByName(self::activeName($model,$attribute));
  5735. }
  5736. public static function modelName($model)
  5737. {
  5738. if(is_callable(self::$_modelNameConverter))
  5739. return call_user_func(self::$_modelNameConverter,$model);
  5740. $className=is_object($model) ? get_class($model) : (string)$model;
  5741. return trim(str_replace('\\','_',$className),'_');
  5742. }
  5743. public static function setModelNameConverter($converter)
  5744. {
  5745. if(is_callable($converter))
  5746. self::$_modelNameConverter=$converter;
  5747. elseif($converter===null)
  5748. self::$_modelNameConverter=null;
  5749. else
  5750. throw new CException(Yii::t('yii','The $converter argument must be a valid callback or null.'));
  5751. }
  5752. public static function activeName($model,$attribute)
  5753. {
  5754. $a=$attribute; // because the attribute name may be changed by resolveName
  5755. return self::resolveName($model,$a);
  5756. }
  5757. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5758. {
  5759. $htmlOptions['type']=$type;
  5760. if($type==='text'||$type==='password'||$type==='color'||$type==='date'||$type==='datetime'||
  5761. $type==='datetime-local'||$type==='email'||$type==='month'||$type==='number'||$type==='range'||
  5762. $type==='search'||$type==='tel'||$type==='time'||$type==='url'||$type==='week')
  5763. {
  5764. if(!isset($htmlOptions['maxlength']))
  5765. {
  5766. foreach($model->getValidators($attribute) as $validator)
  5767. {
  5768. if($validator instanceof CStringValidator && $validator->max!==null)
  5769. {
  5770. $htmlOptions['maxlength']=$validator->max;
  5771. break;
  5772. }
  5773. }
  5774. }
  5775. elseif($htmlOptions['maxlength']===false)
  5776. unset($htmlOptions['maxlength']);
  5777. }
  5778. if($type==='file')
  5779. unset($htmlOptions['value']);
  5780. elseif(!isset($htmlOptions['value']))
  5781. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5782. if($model->hasErrors($attribute))
  5783. self::addErrorCss($htmlOptions);
  5784. return self::tag('input',$htmlOptions);
  5785. }
  5786. public static function listOptions($selection,$listData,&$htmlOptions)
  5787. {
  5788. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5789. $content='';
  5790. if(isset($htmlOptions['prompt']))
  5791. {
  5792. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;','>'=>'&gt;'))."</option>\n";
  5793. unset($htmlOptions['prompt']);
  5794. }
  5795. if(isset($htmlOptions['empty']))
  5796. {
  5797. if(!is_array($htmlOptions['empty']))
  5798. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5799. foreach($htmlOptions['empty'] as $value=>$label)
  5800. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;','>'=>'&gt;'))."</option>\n";
  5801. unset($htmlOptions['empty']);
  5802. }
  5803. if(isset($htmlOptions['options']))
  5804. {
  5805. $options=$htmlOptions['options'];
  5806. unset($htmlOptions['options']);
  5807. }
  5808. else
  5809. $options=array();
  5810. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  5811. if(is_array($selection))
  5812. {
  5813. foreach($selection as $i=>$item)
  5814. {
  5815. if(is_object($item))
  5816. $selection[$i]=$item->$key;
  5817. }
  5818. }
  5819. elseif(is_object($selection))
  5820. $selection=$selection->$key;
  5821. foreach($listData as $key=>$value)
  5822. {
  5823. if(is_array($value))
  5824. {
  5825. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  5826. $dummy=array('options'=>$options);
  5827. if(isset($htmlOptions['encode']))
  5828. $dummy['encode']=$htmlOptions['encode'];
  5829. $content.=self::listOptions($selection,$value,$dummy);
  5830. $content.='</optgroup>'."\n";
  5831. }
  5832. else
  5833. {
  5834. $attributes=array('value'=>(string)$key,'encode'=>!$raw);
  5835. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  5836. $attributes['selected']='selected';
  5837. if(isset($options[$key]))
  5838. $attributes=array_merge($attributes,$options[$key]);
  5839. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  5840. }
  5841. }
  5842. unset($htmlOptions['key']);
  5843. return $content;
  5844. }
  5845. protected static function clientChange($event,&$htmlOptions)
  5846. {
  5847. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  5848. return;
  5849. if(isset($htmlOptions['live']))
  5850. {
  5851. $live=$htmlOptions['live'];
  5852. unset($htmlOptions['live']);
  5853. }
  5854. else
  5855. $live = self::$liveEvents;
  5856. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  5857. $return='return true';
  5858. else
  5859. $return='return false';
  5860. if(isset($htmlOptions['on'.$event]))
  5861. {
  5862. $handler=trim($htmlOptions['on'.$event],';').';';
  5863. unset($htmlOptions['on'.$event]);
  5864. }
  5865. else
  5866. $handler='';
  5867. if(isset($htmlOptions['id']))
  5868. $id=$htmlOptions['id'];
  5869. else
  5870. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  5871. $cs=Yii::app()->getClientScript();
  5872. $cs->registerCoreScript('jquery');
  5873. if(isset($htmlOptions['submit']))
  5874. {
  5875. $cs->registerCoreScript('yii');
  5876. $request=Yii::app()->getRequest();
  5877. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  5878. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  5879. if(isset($htmlOptions['params']))
  5880. $params=CJavaScript::encode($htmlOptions['params']);
  5881. else
  5882. $params='{}';
  5883. if($htmlOptions['submit']!=='')
  5884. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  5885. else
  5886. $url='';
  5887. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  5888. }
  5889. if(isset($htmlOptions['ajax']))
  5890. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  5891. if(isset($htmlOptions['confirm']))
  5892. {
  5893. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  5894. if($handler!=='')
  5895. $handler="if($confirm) {".$handler."} else return false;";
  5896. else
  5897. $handler="return $confirm;";
  5898. }
  5899. if($live)
  5900. $cs->registerScript('Yii.CHtml.#' . $id,"jQuery('body').on('$event','#$id',function(){{$handler}});");
  5901. else
  5902. $cs->registerScript('Yii.CHtml.#' . $id,"jQuery('#$id').on('$event', function(){{$handler}});");
  5903. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  5904. }
  5905. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  5906. {
  5907. if(!isset($htmlOptions['name']))
  5908. $htmlOptions['name']=self::resolveName($model,$attribute);
  5909. if(!isset($htmlOptions['id']))
  5910. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  5911. elseif($htmlOptions['id']===false)
  5912. unset($htmlOptions['id']);
  5913. }
  5914. public static function resolveName($model,&$attribute)
  5915. {
  5916. $modelName=self::modelName($model);
  5917. if(($pos=strpos($attribute,'['))!==false)
  5918. {
  5919. if($pos!==0) // e.g. name[a][b]
  5920. return $modelName.'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5921. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5922. {
  5923. $sub=substr($attribute,0,$pos+1);
  5924. $attribute=substr($attribute,$pos+1);
  5925. return $modelName.$sub.'['.$attribute.']';
  5926. }
  5927. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5928. {
  5929. $name=$modelName.'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5930. $attribute=$matches[1];
  5931. return $name;
  5932. }
  5933. }
  5934. return $modelName.'['.$attribute.']';
  5935. }
  5936. public static function resolveValue($model,$attribute)
  5937. {
  5938. if(($pos=strpos($attribute,'['))!==false)
  5939. {
  5940. if($pos===0) // [a]name[b][c], should ignore [a]
  5941. {
  5942. if(preg_match('/\](\w+(\[.+)?)/',$attribute,$matches))
  5943. $attribute=$matches[1]; // we get: name[b][c]
  5944. if(($pos=strpos($attribute,'['))===false)
  5945. return $model->$attribute;
  5946. }
  5947. $name=substr($attribute,0,$pos);
  5948. $value=$model->$name;
  5949. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5950. {
  5951. if((is_array($value) || $value instanceof ArrayAccess) && isset($value[$id]))
  5952. $value=$value[$id];
  5953. else
  5954. return null;
  5955. }
  5956. return $value;
  5957. }
  5958. else
  5959. return $model->$attribute;
  5960. }
  5961. protected static function addErrorCss(&$htmlOptions)
  5962. {
  5963. if(empty(self::$errorCss))
  5964. return;
  5965. if(isset($htmlOptions['class']))
  5966. $htmlOptions['class'].=' '.self::$errorCss;
  5967. else
  5968. $htmlOptions['class']=self::$errorCss;
  5969. }
  5970. public static function renderAttributes($htmlOptions)
  5971. {
  5972. static $specialAttributes=array(
  5973. 'autofocus'=>1,
  5974. 'autoplay'=>1,
  5975. 'async'=>1,
  5976. 'checked'=>1,
  5977. 'controls'=>1,
  5978. 'declare'=>1,
  5979. 'default'=>1,
  5980. 'defer'=>1,
  5981. 'disabled'=>1,
  5982. 'formnovalidate'=>1,
  5983. 'hidden'=>1,
  5984. 'ismap'=>1,
  5985. 'loop'=>1,
  5986. 'multiple'=>1,
  5987. 'muted'=>1,
  5988. 'nohref'=>1,
  5989. 'noresize'=>1,
  5990. 'novalidate'=>1,
  5991. 'open'=>1,
  5992. 'readonly'=>1,
  5993. 'required'=>1,
  5994. 'reversed'=>1,
  5995. 'scoped'=>1,
  5996. 'seamless'=>1,
  5997. 'selected'=>1,
  5998. 'typemustmatch'=>1,
  5999. );
  6000. if($htmlOptions===array())
  6001. return '';
  6002. $html='';
  6003. if(isset($htmlOptions['encode']))
  6004. {
  6005. $raw=!$htmlOptions['encode'];
  6006. unset($htmlOptions['encode']);
  6007. }
  6008. else
  6009. $raw=false;
  6010. foreach($htmlOptions as $name=>$value)
  6011. {
  6012. if(isset($specialAttributes[$name]))
  6013. {
  6014. if($value===false && $name==='async') {
  6015. $html .= ' ' . $name.'="false"';
  6016. }
  6017. elseif($value)
  6018. {
  6019. $html .= ' ' . $name;
  6020. if(self::$renderSpecialAttributesValue)
  6021. $html .= '="' . $name . '"';
  6022. }
  6023. }
  6024. elseif($value!==null)
  6025. $html .= ' ' . $name . '="' . ($raw ? $value : self::encode($value)) . '"';
  6026. }
  6027. return $html;
  6028. }
  6029. }
  6030. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  6031. {
  6032. public $enableSkin=false;
  6033. public $widgets=array();
  6034. public $skinnableWidgets;
  6035. public $skinPath;
  6036. private $_skins=array(); // class name, skin name, property name => value
  6037. public function init()
  6038. {
  6039. parent::init();
  6040. if($this->enableSkin && $this->skinPath===null)
  6041. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  6042. }
  6043. public function createWidget($owner,$className,$properties=array())
  6044. {
  6045. $className=Yii::import($className,true);
  6046. $widget=new $className($owner);
  6047. if(isset($this->widgets[$className]))
  6048. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  6049. if($this->enableSkin)
  6050. {
  6051. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  6052. {
  6053. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  6054. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  6055. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  6056. }
  6057. }
  6058. foreach($properties as $name=>$value)
  6059. $widget->$name=$value;
  6060. return $widget;
  6061. }
  6062. protected function getSkin($className,$skinName)
  6063. {
  6064. if(!isset($this->_skins[$className][$skinName]))
  6065. {
  6066. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  6067. if(is_file($skinFile))
  6068. $this->_skins[$className]=require($skinFile);
  6069. else
  6070. $this->_skins[$className]=array();
  6071. if(($theme=Yii::app()->getTheme())!==null)
  6072. {
  6073. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  6074. if(is_file($skinFile))
  6075. {
  6076. $skins=require($skinFile);
  6077. foreach($skins as $name=>$skin)
  6078. $this->_skins[$className][$name]=$skin;
  6079. }
  6080. }
  6081. if(!isset($this->_skins[$className][$skinName]))
  6082. $this->_skins[$className][$skinName]=array();
  6083. }
  6084. return $this->_skins[$className][$skinName];
  6085. }
  6086. }
  6087. class CWidget extends CBaseController
  6088. {
  6089. public $actionPrefix;
  6090. public $skin='default';
  6091. private static $_viewPaths;
  6092. private static $_counter=0;
  6093. private $_id;
  6094. private $_owner;
  6095. public static function actions()
  6096. {
  6097. return array();
  6098. }
  6099. public function __construct($owner=null)
  6100. {
  6101. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  6102. }
  6103. public function getOwner()
  6104. {
  6105. return $this->_owner;
  6106. }
  6107. public function getId($autoGenerate=true)
  6108. {
  6109. if($this->_id!==null)
  6110. return $this->_id;
  6111. elseif($autoGenerate)
  6112. return $this->_id='yw'.self::$_counter++;
  6113. }
  6114. public function setId($value)
  6115. {
  6116. $this->_id=$value;
  6117. }
  6118. public function getController()
  6119. {
  6120. if($this->_owner instanceof CController)
  6121. return $this->_owner;
  6122. else
  6123. return Yii::app()->getController();
  6124. }
  6125. public function init()
  6126. {
  6127. }
  6128. public function run()
  6129. {
  6130. }
  6131. public function getViewPath($checkTheme=false)
  6132. {
  6133. $className=get_class($this);
  6134. $scope=$checkTheme?'theme':'local';
  6135. if(isset(self::$_viewPaths[$className][$scope]))
  6136. return self::$_viewPaths[$className][$scope];
  6137. else
  6138. {
  6139. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  6140. {
  6141. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  6142. if(strpos($className,'\\')!==false) // namespaced class
  6143. $path.=str_replace('\\','_',ltrim($className,'\\'));
  6144. else
  6145. $path.=$className;
  6146. if(is_dir($path))
  6147. return self::$_viewPaths[$className]['theme']=$path;
  6148. }
  6149. $class=new ReflectionClass($className);
  6150. return self::$_viewPaths[$className]['local']=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  6151. }
  6152. }
  6153. public function getViewFile($viewName)
  6154. {
  6155. if(($renderer=Yii::app()->getViewRenderer())!==null)
  6156. $extension=$renderer->fileExtension;
  6157. else
  6158. $extension='.php';
  6159. if(strpos($viewName,'.')) // a path alias
  6160. $viewFile=Yii::getPathOfAlias($viewName);
  6161. else
  6162. {
  6163. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  6164. if(is_file($viewFile.$extension))
  6165. return Yii::app()->findLocalizedFile($viewFile.$extension);
  6166. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  6167. return Yii::app()->findLocalizedFile($viewFile.'.php');
  6168. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  6169. }
  6170. if(is_file($viewFile.$extension))
  6171. return Yii::app()->findLocalizedFile($viewFile.$extension);
  6172. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  6173. return Yii::app()->findLocalizedFile($viewFile.'.php');
  6174. else
  6175. return false;
  6176. }
  6177. public function render($view,$data=null,$return=false)
  6178. {
  6179. if(($viewFile=$this->getViewFile($view))!==false)
  6180. return $this->renderFile($viewFile,$data,$return);
  6181. else
  6182. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  6183. array('{widget}'=>get_class($this), '{view}'=>$view)));
  6184. }
  6185. }
  6186. class CClientScript extends CApplicationComponent
  6187. {
  6188. const POS_HEAD=0;
  6189. const POS_BEGIN=1;
  6190. const POS_END=2;
  6191. const POS_LOAD=3;
  6192. const POS_READY=4;
  6193. public $enableJavaScript=true;
  6194. public $scriptMap=array();
  6195. public $packages=array();
  6196. public $corePackages;
  6197. public $scripts=array();
  6198. protected $cssFiles=array();
  6199. protected $scriptFiles=array();
  6200. protected $metaTags=array();
  6201. protected $linkTags=array();
  6202. protected $css=array();
  6203. protected $hasScripts=false;
  6204. protected $coreScripts=array();
  6205. public $coreScriptPosition=self::POS_HEAD;
  6206. public $defaultScriptFilePosition=self::POS_HEAD;
  6207. public $defaultScriptPosition=self::POS_READY;
  6208. private $_baseUrl;
  6209. public function reset()
  6210. {
  6211. $this->hasScripts=false;
  6212. $this->coreScripts=array();
  6213. $this->cssFiles=array();
  6214. $this->css=array();
  6215. $this->scriptFiles=array();
  6216. $this->scripts=array();
  6217. $this->metaTags=array();
  6218. $this->linkTags=array();
  6219. $this->recordCachingAction('clientScript','reset',array());
  6220. }
  6221. public function render(&$output)
  6222. {
  6223. if(!$this->hasScripts)
  6224. return;
  6225. $this->renderCoreScripts();
  6226. if(!empty($this->scriptMap))
  6227. $this->remapScripts();
  6228. $this->unifyScripts();
  6229. $this->renderHead($output);
  6230. if($this->enableJavaScript)
  6231. {
  6232. $this->renderBodyBegin($output);
  6233. $this->renderBodyEnd($output);
  6234. }
  6235. }
  6236. protected function unifyScripts()
  6237. {
  6238. if(!$this->enableJavaScript)
  6239. return;
  6240. $map=array();
  6241. if(isset($this->scriptFiles[self::POS_HEAD]))
  6242. $map=$this->scriptFiles[self::POS_HEAD];
  6243. if(isset($this->scriptFiles[self::POS_BEGIN]))
  6244. {
  6245. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile=>$scriptFileValue)
  6246. {
  6247. if(isset($map[$scriptFile]))
  6248. unset($this->scriptFiles[self::POS_BEGIN][$scriptFile]);
  6249. else
  6250. $map[$scriptFile]=true;
  6251. }
  6252. }
  6253. if(isset($this->scriptFiles[self::POS_END]))
  6254. {
  6255. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  6256. {
  6257. if(isset($map[$key]))
  6258. unset($this->scriptFiles[self::POS_END][$key]);
  6259. }
  6260. }
  6261. }
  6262. protected function remapScripts()
  6263. {
  6264. $cssFiles=array();
  6265. foreach($this->cssFiles as $url=>$media)
  6266. {
  6267. $name=basename($url);
  6268. if(isset($this->scriptMap[$name]))
  6269. {
  6270. if($this->scriptMap[$name]!==false)
  6271. $cssFiles[$this->scriptMap[$name]]=$media;
  6272. }
  6273. elseif(isset($this->scriptMap['*.css']))
  6274. {
  6275. if($this->scriptMap['*.css']!==false)
  6276. $cssFiles[$this->scriptMap['*.css']]=$media;
  6277. }
  6278. else
  6279. $cssFiles[$url]=$media;
  6280. }
  6281. $this->cssFiles=$cssFiles;
  6282. $jsFiles=array();
  6283. foreach($this->scriptFiles as $position=>$scriptFiles)
  6284. {
  6285. $jsFiles[$position]=array();
  6286. foreach($scriptFiles as $scriptFile=>$scriptFileValue)
  6287. {
  6288. $name=basename($scriptFile);
  6289. if(isset($this->scriptMap[$name]))
  6290. {
  6291. if($this->scriptMap[$name]!==false)
  6292. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  6293. }
  6294. elseif(isset($this->scriptMap['*.js']))
  6295. {
  6296. if($this->scriptMap['*.js']!==false)
  6297. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  6298. }
  6299. else
  6300. $jsFiles[$position][$scriptFile]=$scriptFileValue;
  6301. }
  6302. }
  6303. $this->scriptFiles=$jsFiles;
  6304. }
  6305. protected function renderScriptBatch(array $scripts)
  6306. {
  6307. $html = '';
  6308. $scriptBatches = array();
  6309. foreach($scripts as $scriptValue)
  6310. {
  6311. if(is_array($scriptValue))
  6312. {
  6313. $scriptContent = $scriptValue['content'];
  6314. unset($scriptValue['content']);
  6315. $scriptHtmlOptions = $scriptValue;
  6316. ksort($scriptHtmlOptions);
  6317. }
  6318. else
  6319. {
  6320. $scriptContent = $scriptValue;
  6321. $scriptHtmlOptions = array();
  6322. }
  6323. $key=serialize($scriptHtmlOptions);
  6324. $scriptBatches[$key]['htmlOptions']=$scriptHtmlOptions;
  6325. $scriptBatches[$key]['scripts'][]=$scriptContent;
  6326. }
  6327. foreach($scriptBatches as $scriptBatch)
  6328. if(!empty($scriptBatch['scripts']))
  6329. $html.=CHtml::script(implode("\n",$scriptBatch['scripts']),$scriptBatch['htmlOptions'])."\n";
  6330. return $html;
  6331. }
  6332. public function renderCoreScripts()
  6333. {
  6334. if($this->coreScripts===null)
  6335. return;
  6336. $cssFiles=array();
  6337. $jsFiles=array();
  6338. foreach($this->coreScripts as $name=>$package)
  6339. {
  6340. $baseUrl=$this->getPackageBaseUrl($name);
  6341. if(!empty($package['js']))
  6342. {
  6343. foreach($package['js'] as $js)
  6344. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  6345. }
  6346. if(!empty($package['css']))
  6347. {
  6348. foreach($package['css'] as $css)
  6349. $cssFiles[$baseUrl.'/'.$css]='';
  6350. }
  6351. }
  6352. // merge in place
  6353. if($cssFiles!==array())
  6354. {
  6355. foreach($this->cssFiles as $cssFile=>$media)
  6356. $cssFiles[$cssFile]=$media;
  6357. $this->cssFiles=$cssFiles;
  6358. }
  6359. if($jsFiles!==array())
  6360. {
  6361. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  6362. {
  6363. foreach($this->scriptFiles[$this->coreScriptPosition] as $url => $value)
  6364. $jsFiles[$url]=$value;
  6365. }
  6366. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  6367. }
  6368. }
  6369. public function renderHead(&$output)
  6370. {
  6371. $html='';
  6372. foreach($this->metaTags as $meta)
  6373. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  6374. foreach($this->linkTags as $link)
  6375. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  6376. foreach($this->cssFiles as $url=>$media)
  6377. $html.=CHtml::cssFile($url,$media)."\n";
  6378. foreach($this->css as $css)
  6379. $html.=CHtml::css($css[0],$css[1])."\n";
  6380. if($this->enableJavaScript)
  6381. {
  6382. if(isset($this->scriptFiles[self::POS_HEAD]))
  6383. {
  6384. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFileValueUrl=>$scriptFileValue)
  6385. {
  6386. if(is_array($scriptFileValue))
  6387. $html.=CHtml::scriptFile($scriptFileValueUrl,$scriptFileValue)."\n";
  6388. else
  6389. $html.=CHtml::scriptFile($scriptFileValueUrl)."\n";
  6390. }
  6391. }
  6392. if(isset($this->scripts[self::POS_HEAD]))
  6393. $html.=$this->renderScriptBatch($this->scripts[self::POS_HEAD]);
  6394. }
  6395. if($html!=='')
  6396. {
  6397. $count=0;
  6398. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  6399. if($count)
  6400. $output=str_replace('<###head###>',$html,$output);
  6401. else
  6402. $output=$html.$output;
  6403. }
  6404. }
  6405. public function renderBodyBegin(&$output)
  6406. {
  6407. $html='';
  6408. if(isset($this->scriptFiles[self::POS_BEGIN]))
  6409. {
  6410. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFileUrl=>$scriptFileValue)
  6411. {
  6412. if(is_array($scriptFileValue))
  6413. $html.=CHtml::scriptFile($scriptFileUrl,$scriptFileValue)."\n";
  6414. else
  6415. $html.=CHtml::scriptFile($scriptFileUrl)."\n";
  6416. }
  6417. }
  6418. if(isset($this->scripts[self::POS_BEGIN]))
  6419. $html.=$this->renderScriptBatch($this->scripts[self::POS_BEGIN]);
  6420. if($html!=='')
  6421. {
  6422. $count=0;
  6423. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  6424. if($count)
  6425. $output=str_replace('<###begin###>',$html,$output);
  6426. else
  6427. $output=$html.$output;
  6428. }
  6429. }
  6430. public function renderBodyEnd(&$output)
  6431. {
  6432. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  6433. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  6434. return;
  6435. $fullPage=0;
  6436. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  6437. $html='';
  6438. if(isset($this->scriptFiles[self::POS_END]))
  6439. {
  6440. foreach($this->scriptFiles[self::POS_END] as $scriptFileUrl=>$scriptFileValue)
  6441. {
  6442. if(is_array($scriptFileValue))
  6443. $html.=CHtml::scriptFile($scriptFileUrl,$scriptFileValue)."\n";
  6444. else
  6445. $html.=CHtml::scriptFile($scriptFileUrl)."\n";
  6446. }
  6447. }
  6448. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  6449. if(isset($this->scripts[self::POS_READY]))
  6450. {
  6451. if($fullPage)
  6452. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  6453. else
  6454. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  6455. }
  6456. if(isset($this->scripts[self::POS_LOAD]))
  6457. {
  6458. if($fullPage)
  6459. $scripts[]="jQuery(window).on('load',function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  6460. else
  6461. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  6462. }
  6463. if(!empty($scripts))
  6464. $html.=$this->renderScriptBatch($scripts);
  6465. if($fullPage)
  6466. $output=str_replace('<###end###>',$html,$output);
  6467. else
  6468. $output=$output.$html;
  6469. }
  6470. public function getCoreScriptUrl()
  6471. {
  6472. if($this->_baseUrl!==null)
  6473. return $this->_baseUrl;
  6474. else
  6475. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  6476. }
  6477. public function setCoreScriptUrl($value)
  6478. {
  6479. $this->_baseUrl=$value;
  6480. }
  6481. public function getPackageBaseUrl($name)
  6482. {
  6483. if(!isset($this->coreScripts[$name]))
  6484. return false;
  6485. $package=$this->coreScripts[$name];
  6486. if(isset($package['baseUrl']))
  6487. {
  6488. $baseUrl=$package['baseUrl'];
  6489. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  6490. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  6491. $baseUrl=rtrim($baseUrl,'/');
  6492. }
  6493. elseif(isset($package['basePath']))
  6494. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  6495. else
  6496. $baseUrl=$this->getCoreScriptUrl();
  6497. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  6498. }
  6499. public function registerPackage($name)
  6500. {
  6501. return $this->registerCoreScript($name);
  6502. }
  6503. public function registerCoreScript($name)
  6504. {
  6505. if(isset($this->coreScripts[$name]))
  6506. return $this;
  6507. if(isset($this->packages[$name]))
  6508. $package=$this->packages[$name];
  6509. else
  6510. {
  6511. if($this->corePackages===null)
  6512. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  6513. if(isset($this->corePackages[$name]))
  6514. $package=$this->corePackages[$name];
  6515. }
  6516. if(isset($package))
  6517. {
  6518. if(!empty($package['depends']))
  6519. {
  6520. foreach($package['depends'] as $p)
  6521. $this->registerCoreScript($p);
  6522. }
  6523. $this->coreScripts[$name]=$package;
  6524. $this->hasScripts=true;
  6525. $params=func_get_args();
  6526. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  6527. }
  6528. elseif(YII_DEBUG)
  6529. throw new CException('There is no CClientScript package: '.$name);
  6530. else
  6531. Yii::log('There is no CClientScript package: '.$name,CLogger::LEVEL_WARNING,'system.web.CClientScript');
  6532. return $this;
  6533. }
  6534. public function registerCssFile($url,$media='')
  6535. {
  6536. $this->hasScripts=true;
  6537. $this->cssFiles[$url]=$media;
  6538. $params=func_get_args();
  6539. $this->recordCachingAction('clientScript','registerCssFile',$params);
  6540. return $this;
  6541. }
  6542. public function registerCss($id,$css,$media='')
  6543. {
  6544. $this->hasScripts=true;
  6545. $this->css[$id]=array($css,$media);
  6546. $params=func_get_args();
  6547. $this->recordCachingAction('clientScript','registerCss',$params);
  6548. return $this;
  6549. }
  6550. public function registerScriptFile($url,$position=null,array $htmlOptions=array())
  6551. {
  6552. if($position===null)
  6553. $position=$this->defaultScriptFilePosition;
  6554. $this->hasScripts=true;
  6555. if(empty($htmlOptions))
  6556. $value=$url;
  6557. else
  6558. {
  6559. $value=$htmlOptions;
  6560. $value['src']=$url;
  6561. }
  6562. $this->scriptFiles[$position][$url]=$value;
  6563. $params=func_get_args();
  6564. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  6565. return $this;
  6566. }
  6567. public function registerScript($id,$script,$position=null,array $htmlOptions=array())
  6568. {
  6569. if($position===null)
  6570. $position=$this->defaultScriptPosition;
  6571. $this->hasScripts=true;
  6572. if(empty($htmlOptions))
  6573. $scriptValue=$script;
  6574. else
  6575. {
  6576. if($position==self::POS_LOAD || $position==self::POS_READY)
  6577. throw new CException(Yii::t('yii','Script HTML options are not allowed for "CClientScript::POS_LOAD" and "CClientScript::POS_READY".'));
  6578. $scriptValue=$htmlOptions;
  6579. $scriptValue['content']=$script;
  6580. }
  6581. $this->scripts[$position][$id]=$scriptValue;
  6582. if($position===self::POS_READY || $position===self::POS_LOAD)
  6583. $this->registerCoreScript('jquery');
  6584. $params=func_get_args();
  6585. $this->recordCachingAction('clientScript','registerScript',$params);
  6586. return $this;
  6587. }
  6588. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array(),$id=null)
  6589. {
  6590. $this->hasScripts=true;
  6591. if($name!==null)
  6592. $options['name']=$name;
  6593. if($httpEquiv!==null)
  6594. $options['http-equiv']=$httpEquiv;
  6595. $options['content']=$content;
  6596. $this->metaTags[null===$id?count($this->metaTags):$id]=$options;
  6597. $params=func_get_args();
  6598. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  6599. return $this;
  6600. }
  6601. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  6602. {
  6603. $this->hasScripts=true;
  6604. if($relation!==null)
  6605. $options['rel']=$relation;
  6606. if($type!==null)
  6607. $options['type']=$type;
  6608. if($href!==null)
  6609. $options['href']=$href;
  6610. if($media!==null)
  6611. $options['media']=$media;
  6612. $this->linkTags[serialize($options)]=$options;
  6613. $params=func_get_args();
  6614. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  6615. return $this;
  6616. }
  6617. public function isCssFileRegistered($url)
  6618. {
  6619. return isset($this->cssFiles[$url]);
  6620. }
  6621. public function isCssRegistered($id)
  6622. {
  6623. return isset($this->css[$id]);
  6624. }
  6625. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  6626. {
  6627. return isset($this->scriptFiles[$position][$url]);
  6628. }
  6629. public function isScriptRegistered($id,$position=self::POS_READY)
  6630. {
  6631. return isset($this->scripts[$position][$id]);
  6632. }
  6633. protected function recordCachingAction($context,$method,$params)
  6634. {
  6635. if(($controller=Yii::app()->getController())!==null)
  6636. $controller->recordCachingAction($context,$method,$params);
  6637. }
  6638. public function addPackage($name,$definition)
  6639. {
  6640. $this->packages[$name]=$definition;
  6641. return $this;
  6642. }
  6643. }
  6644. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  6645. {
  6646. private $_d=array();
  6647. private $_c=0;
  6648. private $_r=false;
  6649. public function __construct($data=null,$readOnly=false)
  6650. {
  6651. if($data!==null)
  6652. $this->copyFrom($data);
  6653. $this->setReadOnly($readOnly);
  6654. }
  6655. public function getReadOnly()
  6656. {
  6657. return $this->_r;
  6658. }
  6659. protected function setReadOnly($value)
  6660. {
  6661. $this->_r=$value;
  6662. }
  6663. public function getIterator()
  6664. {
  6665. return new CListIterator($this->_d);
  6666. }
  6667. public function count()
  6668. {
  6669. return $this->getCount();
  6670. }
  6671. public function getCount()
  6672. {
  6673. return $this->_c;
  6674. }
  6675. public function itemAt($index)
  6676. {
  6677. if(isset($this->_d[$index]))
  6678. return $this->_d[$index];
  6679. elseif($index>=0 && $index<$this->_c) // in case the value is null
  6680. return $this->_d[$index];
  6681. else
  6682. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6683. array('{index}'=>$index)));
  6684. }
  6685. public function add($item)
  6686. {
  6687. $this->insertAt($this->_c,$item);
  6688. return $this->_c-1;
  6689. }
  6690. public function insertAt($index,$item)
  6691. {
  6692. if(!$this->_r)
  6693. {
  6694. if($index===$this->_c)
  6695. $this->_d[$this->_c++]=$item;
  6696. elseif($index>=0 && $index<$this->_c)
  6697. {
  6698. array_splice($this->_d,$index,0,array($item));
  6699. $this->_c++;
  6700. }
  6701. else
  6702. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6703. array('{index}'=>$index)));
  6704. }
  6705. else
  6706. throw new CException(Yii::t('yii','The list is read only.'));
  6707. }
  6708. public function remove($item)
  6709. {
  6710. if(($index=$this->indexOf($item))>=0)
  6711. {
  6712. $this->removeAt($index);
  6713. return $index;
  6714. }
  6715. else
  6716. return false;
  6717. }
  6718. public function removeAt($index)
  6719. {
  6720. if(!$this->_r)
  6721. {
  6722. if($index>=0 && $index<$this->_c)
  6723. {
  6724. $this->_c--;
  6725. if($index===$this->_c)
  6726. return array_pop($this->_d);
  6727. else
  6728. {
  6729. $item=$this->_d[$index];
  6730. array_splice($this->_d,$index,1);
  6731. return $item;
  6732. }
  6733. }
  6734. else
  6735. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6736. array('{index}'=>$index)));
  6737. }
  6738. else
  6739. throw new CException(Yii::t('yii','The list is read only.'));
  6740. }
  6741. public function clear()
  6742. {
  6743. for($i=$this->_c-1;$i>=0;--$i)
  6744. $this->removeAt($i);
  6745. }
  6746. public function contains($item)
  6747. {
  6748. return $this->indexOf($item)>=0;
  6749. }
  6750. public function indexOf($item)
  6751. {
  6752. if(($index=array_search($item,$this->_d,true))!==false)
  6753. return $index;
  6754. else
  6755. return -1;
  6756. }
  6757. public function toArray()
  6758. {
  6759. return $this->_d;
  6760. }
  6761. public function copyFrom($data)
  6762. {
  6763. if(is_array($data) || ($data instanceof Traversable))
  6764. {
  6765. if($this->_c>0)
  6766. $this->clear();
  6767. if($data instanceof CList)
  6768. $data=$data->_d;
  6769. foreach($data as $item)
  6770. $this->add($item);
  6771. }
  6772. elseif($data!==null)
  6773. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6774. }
  6775. public function mergeWith($data)
  6776. {
  6777. if(is_array($data) || ($data instanceof Traversable))
  6778. {
  6779. if($data instanceof CList)
  6780. $data=$data->_d;
  6781. foreach($data as $item)
  6782. $this->add($item);
  6783. }
  6784. elseif($data!==null)
  6785. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6786. }
  6787. public function offsetExists($offset)
  6788. {
  6789. return ($offset>=0 && $offset<$this->_c);
  6790. }
  6791. public function offsetGet($offset)
  6792. {
  6793. return $this->itemAt($offset);
  6794. }
  6795. public function offsetSet($offset,$item)
  6796. {
  6797. if($offset===null || $offset===$this->_c)
  6798. $this->insertAt($this->_c,$item);
  6799. else
  6800. {
  6801. $this->removeAt($offset);
  6802. $this->insertAt($offset,$item);
  6803. }
  6804. }
  6805. public function offsetUnset($offset)
  6806. {
  6807. $this->removeAt($offset);
  6808. }
  6809. }
  6810. class CFilterChain extends CList
  6811. {
  6812. public $controller;
  6813. public $action;
  6814. public $filterIndex=0;
  6815. public function __construct($controller,$action)
  6816. {
  6817. $this->controller=$controller;
  6818. $this->action=$action;
  6819. }
  6820. public static function create($controller,$action,$filters)
  6821. {
  6822. $chain=new CFilterChain($controller,$action);
  6823. $actionID=$action->getId();
  6824. foreach($filters as $filter)
  6825. {
  6826. if(is_string($filter)) // filterName [+|- action1 action2]
  6827. {
  6828. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  6829. {
  6830. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  6831. if(($filter[$pos]==='+')===$matched)
  6832. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  6833. }
  6834. else
  6835. $filter=CInlineFilter::create($controller,$filter);
  6836. }
  6837. elseif(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  6838. {
  6839. if(!isset($filter[0]))
  6840. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  6841. $filterClass=$filter[0];
  6842. unset($filter[0]);
  6843. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  6844. {
  6845. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  6846. if(($filterClass[$pos]==='+')===$matched)
  6847. $filterClass=trim(substr($filterClass,0,$pos));
  6848. else
  6849. continue;
  6850. }
  6851. $filter['class']=$filterClass;
  6852. $filter=Yii::createComponent($filter);
  6853. }
  6854. if(is_object($filter))
  6855. {
  6856. $filter->init();
  6857. $chain->add($filter);
  6858. }
  6859. }
  6860. return $chain;
  6861. }
  6862. public function insertAt($index,$item)
  6863. {
  6864. if($item instanceof IFilter)
  6865. parent::insertAt($index,$item);
  6866. else
  6867. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  6868. }
  6869. public function run()
  6870. {
  6871. if($this->offsetExists($this->filterIndex))
  6872. {
  6873. $filter=$this->itemAt($this->filterIndex++);
  6874. $filter->filter($this);
  6875. }
  6876. else
  6877. $this->controller->runAction($this->action);
  6878. }
  6879. }
  6880. class CFilter extends CComponent implements IFilter
  6881. {
  6882. public function filter($filterChain)
  6883. {
  6884. if($this->preFilter($filterChain))
  6885. {
  6886. $filterChain->run();
  6887. $this->postFilter($filterChain);
  6888. }
  6889. }
  6890. public function init()
  6891. {
  6892. }
  6893. protected function preFilter($filterChain)
  6894. {
  6895. return true;
  6896. }
  6897. protected function postFilter($filterChain)
  6898. {
  6899. }
  6900. }
  6901. class CInlineFilter extends CFilter
  6902. {
  6903. public $name;
  6904. public static function create($controller,$filterName)
  6905. {
  6906. if(method_exists($controller,'filter'.$filterName))
  6907. {
  6908. $filter=new CInlineFilter;
  6909. $filter->name=$filterName;
  6910. return $filter;
  6911. }
  6912. else
  6913. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  6914. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  6915. }
  6916. public function filter($filterChain)
  6917. {
  6918. $method='filter'.$this->name;
  6919. $filterChain->controller->$method($filterChain);
  6920. }
  6921. }
  6922. class CAccessControlFilter extends CFilter
  6923. {
  6924. public $message;
  6925. private $_rules=array();
  6926. public function getRules()
  6927. {
  6928. return $this->_rules;
  6929. }
  6930. public function setRules($rules)
  6931. {
  6932. foreach($rules as $rule)
  6933. {
  6934. if(is_array($rule) && isset($rule[0]))
  6935. {
  6936. $r=new CAccessRule;
  6937. $r->allow=$rule[0]==='allow';
  6938. foreach(array_slice($rule,1) as $name=>$value)
  6939. {
  6940. if($name==='expression' || $name==='roles' || $name==='message' || $name==='deniedCallback')
  6941. $r->$name=$value;
  6942. else
  6943. $r->$name=array_map('strtolower',$value);
  6944. }
  6945. $this->_rules[]=$r;
  6946. }
  6947. }
  6948. }
  6949. protected function preFilter($filterChain)
  6950. {
  6951. $app=Yii::app();
  6952. $request=$app->getRequest();
  6953. $user=$app->getUser();
  6954. $verb=$request->getRequestType();
  6955. $ip=$request->getUserHostAddress();
  6956. foreach($this->getRules() as $rule)
  6957. {
  6958. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  6959. break;
  6960. elseif($allow<0) // denied
  6961. {
  6962. if(isset($rule->deniedCallback))
  6963. call_user_func($rule->deniedCallback, $rule);
  6964. else
  6965. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  6966. return false;
  6967. }
  6968. }
  6969. return true;
  6970. }
  6971. protected function resolveErrorMessage($rule)
  6972. {
  6973. if($rule->message!==null)
  6974. return $rule->message;
  6975. elseif($this->message!==null)
  6976. return $this->message;
  6977. else
  6978. return Yii::t('yii','You are not authorized to perform this action.');
  6979. }
  6980. protected function accessDenied($user,$message)
  6981. {
  6982. if($user->getIsGuest())
  6983. $user->loginRequired();
  6984. else
  6985. throw new CHttpException(403,$message);
  6986. }
  6987. }
  6988. class CAccessRule extends CComponent
  6989. {
  6990. public $allow;
  6991. public $actions;
  6992. public $controllers;
  6993. public $users;
  6994. public $roles;
  6995. public $ips;
  6996. public $verbs;
  6997. public $expression;
  6998. public $message;
  6999. public $deniedCallback;
  7000. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  7001. {
  7002. if($this->isActionMatched($action)
  7003. && $this->isUserMatched($user)
  7004. && $this->isRoleMatched($user)
  7005. && $this->isIpMatched($ip)
  7006. && $this->isVerbMatched($verb)
  7007. && $this->isControllerMatched($controller)
  7008. && $this->isExpressionMatched($user))
  7009. return $this->allow ? 1 : -1;
  7010. else
  7011. return 0;
  7012. }
  7013. protected function isActionMatched($action)
  7014. {
  7015. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  7016. }
  7017. protected function isControllerMatched($controller)
  7018. {
  7019. return empty($this->controllers) || in_array(strtolower($controller->getUniqueId()),$this->controllers);
  7020. }
  7021. protected function isUserMatched($user)
  7022. {
  7023. if(empty($this->users))
  7024. return true;
  7025. foreach($this->users as $u)
  7026. {
  7027. if($u==='*')
  7028. return true;
  7029. elseif($u==='?' && $user->getIsGuest())
  7030. return true;
  7031. elseif($u==='@' && !$user->getIsGuest())
  7032. return true;
  7033. elseif(!strcasecmp($u,$user->getName()))
  7034. return true;
  7035. }
  7036. return false;
  7037. }
  7038. protected function isRoleMatched($user)
  7039. {
  7040. if(empty($this->roles))
  7041. return true;
  7042. foreach($this->roles as $key=>$role)
  7043. {
  7044. if(is_numeric($key))
  7045. {
  7046. if($user->checkAccess($role))
  7047. return true;
  7048. }
  7049. else
  7050. {
  7051. if($user->checkAccess($key,$role))
  7052. return true;
  7053. }
  7054. }
  7055. return false;
  7056. }
  7057. protected function isIpMatched($ip)
  7058. {
  7059. if(empty($this->ips))
  7060. return true;
  7061. foreach($this->ips as $rule)
  7062. {
  7063. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  7064. return true;
  7065. }
  7066. return false;
  7067. }
  7068. protected function isVerbMatched($verb)
  7069. {
  7070. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  7071. }
  7072. protected function isExpressionMatched($user)
  7073. {
  7074. if($this->expression===null)
  7075. return true;
  7076. else
  7077. return $this->evaluateExpression($this->expression, array('user'=>$user));
  7078. }
  7079. }
  7080. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  7081. {
  7082. private $_errors=array(); // attribute name => array of errors
  7083. private $_validators; // validators
  7084. private $_scenario=''; // scenario
  7085. abstract public function attributeNames();
  7086. public function rules()
  7087. {
  7088. return array();
  7089. }
  7090. public function behaviors()
  7091. {
  7092. return array();
  7093. }
  7094. public function attributeLabels()
  7095. {
  7096. return array();
  7097. }
  7098. public function validate($attributes=null, $clearErrors=true)
  7099. {
  7100. if($clearErrors)
  7101. $this->clearErrors();
  7102. if($this->beforeValidate())
  7103. {
  7104. foreach($this->getValidators() as $validator)
  7105. $validator->validate($this,$attributes);
  7106. $this->afterValidate();
  7107. return !$this->hasErrors();
  7108. }
  7109. else
  7110. return false;
  7111. }
  7112. protected function afterConstruct()
  7113. {
  7114. if($this->hasEventHandler('onAfterConstruct'))
  7115. $this->onAfterConstruct(new CEvent($this));
  7116. }
  7117. protected function beforeValidate()
  7118. {
  7119. $event=new CModelEvent($this);
  7120. $this->onBeforeValidate($event);
  7121. return $event->isValid;
  7122. }
  7123. protected function afterValidate()
  7124. {
  7125. $this->onAfterValidate(new CEvent($this));
  7126. }
  7127. public function onAfterConstruct($event)
  7128. {
  7129. $this->raiseEvent('onAfterConstruct',$event);
  7130. }
  7131. public function onBeforeValidate($event)
  7132. {
  7133. $this->raiseEvent('onBeforeValidate',$event);
  7134. }
  7135. public function onAfterValidate($event)
  7136. {
  7137. $this->raiseEvent('onAfterValidate',$event);
  7138. }
  7139. public function getValidatorList()
  7140. {
  7141. if($this->_validators===null)
  7142. $this->_validators=$this->createValidators();
  7143. return $this->_validators;
  7144. }
  7145. public function getValidators($attribute=null)
  7146. {
  7147. if($this->_validators===null)
  7148. $this->_validators=$this->createValidators();
  7149. $validators=array();
  7150. $scenario=$this->getScenario();
  7151. foreach($this->_validators as $validator)
  7152. {
  7153. if($validator->applyTo($scenario))
  7154. {
  7155. if($attribute===null || in_array($attribute,$validator->attributes,true))
  7156. $validators[]=$validator;
  7157. }
  7158. }
  7159. return $validators;
  7160. }
  7161. public function createValidators()
  7162. {
  7163. $validators=new CList;
  7164. foreach($this->rules() as $rule)
  7165. {
  7166. if(isset($rule[0],$rule[1])) // attributes, validator name
  7167. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  7168. else
  7169. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  7170. array('{class}'=>get_class($this))));
  7171. }
  7172. return $validators;
  7173. }
  7174. public function isAttributeRequired($attribute)
  7175. {
  7176. foreach($this->getValidators($attribute) as $validator)
  7177. {
  7178. if($validator instanceof CRequiredValidator)
  7179. return true;
  7180. }
  7181. return false;
  7182. }
  7183. public function isAttributeSafe($attribute)
  7184. {
  7185. $attributes=$this->getSafeAttributeNames();
  7186. return in_array($attribute,$attributes);
  7187. }
  7188. public function getAttributeLabel($attribute)
  7189. {
  7190. $labels=$this->attributeLabels();
  7191. if(isset($labels[$attribute]))
  7192. return $labels[$attribute];
  7193. else
  7194. return $this->generateAttributeLabel($attribute);
  7195. }
  7196. public function hasErrors($attribute=null)
  7197. {
  7198. if($attribute===null)
  7199. return $this->_errors!==array();
  7200. else
  7201. return isset($this->_errors[$attribute]);
  7202. }
  7203. public function getErrors($attribute=null)
  7204. {
  7205. if($attribute===null)
  7206. return $this->_errors;
  7207. else
  7208. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  7209. }
  7210. public function getError($attribute)
  7211. {
  7212. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  7213. }
  7214. public function addError($attribute,$error)
  7215. {
  7216. $this->_errors[$attribute][]=$error;
  7217. }
  7218. public function addErrors($errors)
  7219. {
  7220. foreach($errors as $attribute=>$error)
  7221. {
  7222. if(is_array($error))
  7223. {
  7224. foreach($error as $e)
  7225. $this->addError($attribute, $e);
  7226. }
  7227. else
  7228. $this->addError($attribute, $error);
  7229. }
  7230. }
  7231. public function clearErrors($attribute=null)
  7232. {
  7233. if($attribute===null)
  7234. $this->_errors=array();
  7235. else
  7236. unset($this->_errors[$attribute]);
  7237. }
  7238. public function generateAttributeLabel($name)
  7239. {
  7240. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  7241. }
  7242. public function getAttributes($names=null)
  7243. {
  7244. $values=array();
  7245. foreach($this->attributeNames() as $name)
  7246. $values[$name]=$this->$name;
  7247. if(is_array($names))
  7248. {
  7249. $values2=array();
  7250. foreach($names as $name)
  7251. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  7252. return $values2;
  7253. }
  7254. else
  7255. return $values;
  7256. }
  7257. public function setAttributes($values,$safeOnly=true)
  7258. {
  7259. if(!is_array($values))
  7260. return;
  7261. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  7262. foreach($values as $name=>$value)
  7263. {
  7264. if(isset($attributes[$name]))
  7265. $this->$name=$value;
  7266. elseif($safeOnly)
  7267. $this->onUnsafeAttribute($name,$value);
  7268. }
  7269. }
  7270. public function unsetAttributes($names=null)
  7271. {
  7272. if($names===null)
  7273. $names=$this->attributeNames();
  7274. foreach($names as $name)
  7275. $this->$name=null;
  7276. }
  7277. public function onUnsafeAttribute($name,$value)
  7278. {
  7279. if(YII_DEBUG)
  7280. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  7281. }
  7282. public function getScenario()
  7283. {
  7284. return $this->_scenario;
  7285. }
  7286. public function setScenario($value)
  7287. {
  7288. $this->_scenario=$value;
  7289. }
  7290. public function getSafeAttributeNames()
  7291. {
  7292. $attributes=array();
  7293. $unsafe=array();
  7294. foreach($this->getValidators() as $validator)
  7295. {
  7296. if(!$validator->safe)
  7297. {
  7298. foreach($validator->attributes as $name)
  7299. $unsafe[]=$name;
  7300. }
  7301. else
  7302. {
  7303. foreach($validator->attributes as $name)
  7304. $attributes[$name]=true;
  7305. }
  7306. }
  7307. foreach($unsafe as $name)
  7308. unset($attributes[$name]);
  7309. return array_keys($attributes);
  7310. }
  7311. public function getIterator()
  7312. {
  7313. $attributes=$this->getAttributes();
  7314. return new CMapIterator($attributes);
  7315. }
  7316. public function offsetExists($offset)
  7317. {
  7318. return property_exists($this,$offset);
  7319. }
  7320. public function offsetGet($offset)
  7321. {
  7322. return $this->$offset;
  7323. }
  7324. public function offsetSet($offset,$item)
  7325. {
  7326. $this->$offset=$item;
  7327. }
  7328. public function offsetUnset($offset)
  7329. {
  7330. unset($this->$offset);
  7331. }
  7332. }
  7333. abstract class CActiveRecord extends CModel
  7334. {
  7335. const BELONGS_TO='CBelongsToRelation';
  7336. const HAS_ONE='CHasOneRelation';
  7337. const HAS_MANY='CHasManyRelation';
  7338. const MANY_MANY='CManyManyRelation';
  7339. const STAT='CStatRelation';
  7340. public static $db;
  7341. private static $_models=array(); // class name => model
  7342. private static $_md=array(); // class name => meta data
  7343. private $_new=false; // whether this instance is new or not
  7344. private $_attributes=array(); // attribute name => attribute value
  7345. private $_related=array(); // attribute name => related objects
  7346. private $_c; // query criteria (used by finder only)
  7347. private $_pk; // old primary key value
  7348. private $_alias='t'; // the table alias being used for query
  7349. public function __construct($scenario='insert')
  7350. {
  7351. if($scenario===null) // internally used by populateRecord() and model()
  7352. return;
  7353. $this->setScenario($scenario);
  7354. $this->setIsNewRecord(true);
  7355. $this->_attributes=$this->getMetaData()->attributeDefaults;
  7356. $this->init();
  7357. $this->attachBehaviors($this->behaviors());
  7358. $this->afterConstruct();
  7359. }
  7360. public function init()
  7361. {
  7362. }
  7363. public function cache($duration, $dependency=null, $queryCount=1)
  7364. {
  7365. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  7366. return $this;
  7367. }
  7368. public function __sleep()
  7369. {
  7370. return array_keys((array)$this);
  7371. }
  7372. public function __get($name)
  7373. {
  7374. if(isset($this->_attributes[$name]))
  7375. return $this->_attributes[$name];
  7376. elseif(isset($this->getMetaData()->columns[$name]))
  7377. return null;
  7378. elseif(isset($this->_related[$name]))
  7379. return $this->_related[$name];
  7380. elseif(isset($this->getMetaData()->relations[$name]))
  7381. return $this->getRelated($name);
  7382. else
  7383. return parent::__get($name);
  7384. }
  7385. public function __set($name,$value)
  7386. {
  7387. if($this->setAttribute($name,$value)===false)
  7388. {
  7389. if(isset($this->getMetaData()->relations[$name]))
  7390. $this->_related[$name]=$value;
  7391. else
  7392. parent::__set($name,$value);
  7393. }
  7394. }
  7395. public function __isset($name)
  7396. {
  7397. if(isset($this->_attributes[$name]))
  7398. return true;
  7399. elseif(isset($this->getMetaData()->columns[$name]))
  7400. return false;
  7401. elseif(isset($this->_related[$name]))
  7402. return true;
  7403. elseif(isset($this->getMetaData()->relations[$name]))
  7404. return $this->getRelated($name)!==null;
  7405. else
  7406. return parent::__isset($name);
  7407. }
  7408. public function __unset($name)
  7409. {
  7410. if(isset($this->getMetaData()->columns[$name]))
  7411. unset($this->_attributes[$name]);
  7412. elseif(isset($this->getMetaData()->relations[$name]))
  7413. unset($this->_related[$name]);
  7414. else
  7415. parent::__unset($name);
  7416. }
  7417. public function __call($name,$parameters)
  7418. {
  7419. if(isset($this->getMetaData()->relations[$name]))
  7420. {
  7421. if(empty($parameters))
  7422. return $this->getRelated($name,false);
  7423. else
  7424. return $this->getRelated($name,false,$parameters[0]);
  7425. }
  7426. $scopes=$this->scopes();
  7427. if(isset($scopes[$name]))
  7428. {
  7429. $this->getDbCriteria()->mergeWith($scopes[$name]);
  7430. return $this;
  7431. }
  7432. return parent::__call($name,$parameters);
  7433. }
  7434. public function getRelated($name,$refresh=false,$params=array())
  7435. {
  7436. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  7437. return $this->_related[$name];
  7438. $md=$this->getMetaData();
  7439. if(!isset($md->relations[$name]))
  7440. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  7441. array('{class}'=>get_class($this), '{name}'=>$name)));
  7442. $relation=$md->relations[$name];
  7443. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  7444. return $relation instanceof CHasOneRelation ? null : array();
  7445. if($params!==array()) // dynamic query
  7446. {
  7447. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7448. if($exists)
  7449. $save=$this->_related[$name];
  7450. if($params instanceof CDbCriteria)
  7451. $params = $params->toArray();
  7452. $r=array($name=>$params);
  7453. }
  7454. else
  7455. $r=$name;
  7456. unset($this->_related[$name]);
  7457. $finder=$this->getActiveFinder($r);
  7458. $finder->lazyFind($this);
  7459. if(!isset($this->_related[$name]))
  7460. {
  7461. if($relation instanceof CHasManyRelation)
  7462. $this->_related[$name]=array();
  7463. elseif($relation instanceof CStatRelation)
  7464. $this->_related[$name]=$relation->defaultValue;
  7465. else
  7466. $this->_related[$name]=null;
  7467. }
  7468. if($params!==array())
  7469. {
  7470. $results=$this->_related[$name];
  7471. if($exists)
  7472. $this->_related[$name]=$save;
  7473. else
  7474. unset($this->_related[$name]);
  7475. return $results;
  7476. }
  7477. else
  7478. return $this->_related[$name];
  7479. }
  7480. public function hasRelated($name)
  7481. {
  7482. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7483. }
  7484. public function getDbCriteria($createIfNull=true)
  7485. {
  7486. if($this->_c===null)
  7487. {
  7488. if(($c=$this->defaultScope())!==array() || $createIfNull)
  7489. $this->_c=new CDbCriteria($c);
  7490. }
  7491. return $this->_c;
  7492. }
  7493. public function setDbCriteria($criteria)
  7494. {
  7495. $this->_c=$criteria;
  7496. }
  7497. public function defaultScope()
  7498. {
  7499. return array();
  7500. }
  7501. public function resetScope($resetDefault=true)
  7502. {
  7503. if($resetDefault)
  7504. $this->_c=new CDbCriteria();
  7505. else
  7506. $this->_c=null;
  7507. return $this;
  7508. }
  7509. public static function model($className=__CLASS__)
  7510. {
  7511. if(isset(self::$_models[$className]))
  7512. return self::$_models[$className];
  7513. else
  7514. {
  7515. $model=self::$_models[$className]=new $className(null);
  7516. $model->attachBehaviors($model->behaviors());
  7517. return $model;
  7518. }
  7519. }
  7520. public function getMetaData()
  7521. {
  7522. $className=get_class($this);
  7523. if(!array_key_exists($className,self::$_md))
  7524. {
  7525. self::$_md[$className]=null; // preventing recursive invokes of {@link getMetaData()} via {@link __get()}
  7526. self::$_md[$className]=new CActiveRecordMetaData($this);
  7527. }
  7528. return self::$_md[$className];
  7529. }
  7530. public function refreshMetaData()
  7531. {
  7532. $className=get_class($this);
  7533. if(array_key_exists($className,self::$_md))
  7534. unset(self::$_md[$className]);
  7535. }
  7536. public function tableName()
  7537. {
  7538. $tableName = get_class($this);
  7539. if(($pos=strrpos($tableName,'\\')) !== false)
  7540. return substr($tableName,$pos+1);
  7541. return $tableName;
  7542. }
  7543. public function primaryKey()
  7544. {
  7545. }
  7546. public function relations()
  7547. {
  7548. return array();
  7549. }
  7550. public function scopes()
  7551. {
  7552. return array();
  7553. }
  7554. public function attributeNames()
  7555. {
  7556. return array_keys($this->getMetaData()->columns);
  7557. }
  7558. public function getAttributeLabel($attribute)
  7559. {
  7560. $labels=$this->attributeLabels();
  7561. if(isset($labels[$attribute]))
  7562. return $labels[$attribute];
  7563. elseif(strpos($attribute,'.')!==false)
  7564. {
  7565. $segs=explode('.',$attribute);
  7566. $name=array_pop($segs);
  7567. $model=$this;
  7568. foreach($segs as $seg)
  7569. {
  7570. $relations=$model->getMetaData()->relations;
  7571. if(isset($relations[$seg]))
  7572. $model=CActiveRecord::model($relations[$seg]->className);
  7573. else
  7574. break;
  7575. }
  7576. return $model->getAttributeLabel($name);
  7577. }
  7578. else
  7579. return $this->generateAttributeLabel($attribute);
  7580. }
  7581. public function getDbConnection()
  7582. {
  7583. if(self::$db!==null)
  7584. return self::$db;
  7585. else
  7586. {
  7587. self::$db=Yii::app()->getDb();
  7588. if(self::$db instanceof CDbConnection)
  7589. return self::$db;
  7590. else
  7591. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  7592. }
  7593. }
  7594. public function getActiveRelation($name)
  7595. {
  7596. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  7597. }
  7598. public function getTableSchema()
  7599. {
  7600. return $this->getMetaData()->tableSchema;
  7601. }
  7602. public function getCommandBuilder()
  7603. {
  7604. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  7605. }
  7606. public function hasAttribute($name)
  7607. {
  7608. return isset($this->getMetaData()->columns[$name]);
  7609. }
  7610. public function getAttribute($name)
  7611. {
  7612. if(property_exists($this,$name))
  7613. return $this->$name;
  7614. elseif(isset($this->_attributes[$name]))
  7615. return $this->_attributes[$name];
  7616. }
  7617. public function setAttribute($name,$value)
  7618. {
  7619. if(property_exists($this,$name))
  7620. $this->$name=$value;
  7621. elseif(isset($this->getMetaData()->columns[$name]))
  7622. $this->_attributes[$name]=$value;
  7623. else
  7624. return false;
  7625. return true;
  7626. }
  7627. public function addRelatedRecord($name,$record,$index)
  7628. {
  7629. if($index!==false)
  7630. {
  7631. if(!isset($this->_related[$name]))
  7632. $this->_related[$name]=array();
  7633. if($record instanceof CActiveRecord)
  7634. {
  7635. if($index===true)
  7636. $this->_related[$name][]=$record;
  7637. else
  7638. $this->_related[$name][$index]=$record;
  7639. }
  7640. }
  7641. elseif(!isset($this->_related[$name]))
  7642. $this->_related[$name]=$record;
  7643. }
  7644. public function getAttributes($names=true)
  7645. {
  7646. $attributes=$this->_attributes;
  7647. foreach($this->getMetaData()->columns as $name=>$column)
  7648. {
  7649. if(property_exists($this,$name))
  7650. $attributes[$name]=$this->$name;
  7651. elseif($names===true && !isset($attributes[$name]))
  7652. $attributes[$name]=null;
  7653. }
  7654. if(is_array($names))
  7655. {
  7656. $attrs=array();
  7657. foreach($names as $name)
  7658. {
  7659. if(property_exists($this,$name))
  7660. $attrs[$name]=$this->$name;
  7661. else
  7662. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  7663. }
  7664. return $attrs;
  7665. }
  7666. else
  7667. return $attributes;
  7668. }
  7669. public function save($runValidation=true,$attributes=null)
  7670. {
  7671. if(!$runValidation || $this->validate($attributes))
  7672. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  7673. else
  7674. return false;
  7675. }
  7676. public function getIsNewRecord()
  7677. {
  7678. return $this->_new;
  7679. }
  7680. public function setIsNewRecord($value)
  7681. {
  7682. $this->_new=$value;
  7683. }
  7684. public function onBeforeSave($event)
  7685. {
  7686. $this->raiseEvent('onBeforeSave',$event);
  7687. }
  7688. public function onAfterSave($event)
  7689. {
  7690. $this->raiseEvent('onAfterSave',$event);
  7691. }
  7692. public function onBeforeDelete($event)
  7693. {
  7694. $this->raiseEvent('onBeforeDelete',$event);
  7695. }
  7696. public function onAfterDelete($event)
  7697. {
  7698. $this->raiseEvent('onAfterDelete',$event);
  7699. }
  7700. public function onBeforeFind($event)
  7701. {
  7702. $this->raiseEvent('onBeforeFind',$event);
  7703. }
  7704. public function onAfterFind($event)
  7705. {
  7706. $this->raiseEvent('onAfterFind',$event);
  7707. }
  7708. public function getActiveFinder($with)
  7709. {
  7710. return new CActiveFinder($this,$with);
  7711. }
  7712. public function onBeforeCount($event)
  7713. {
  7714. $this->raiseEvent('onBeforeCount',$event);
  7715. }
  7716. protected function beforeSave()
  7717. {
  7718. if($this->hasEventHandler('onBeforeSave'))
  7719. {
  7720. $event=new CModelEvent($this);
  7721. $this->onBeforeSave($event);
  7722. return $event->isValid;
  7723. }
  7724. else
  7725. return true;
  7726. }
  7727. protected function afterSave()
  7728. {
  7729. if($this->hasEventHandler('onAfterSave'))
  7730. $this->onAfterSave(new CEvent($this));
  7731. }
  7732. protected function beforeDelete()
  7733. {
  7734. if($this->hasEventHandler('onBeforeDelete'))
  7735. {
  7736. $event=new CModelEvent($this);
  7737. $this->onBeforeDelete($event);
  7738. return $event->isValid;
  7739. }
  7740. else
  7741. return true;
  7742. }
  7743. protected function afterDelete()
  7744. {
  7745. if($this->hasEventHandler('onAfterDelete'))
  7746. $this->onAfterDelete(new CEvent($this));
  7747. }
  7748. protected function beforeFind()
  7749. {
  7750. if($this->hasEventHandler('onBeforeFind'))
  7751. {
  7752. $event=new CModelEvent($this);
  7753. $this->onBeforeFind($event);
  7754. }
  7755. }
  7756. protected function beforeCount()
  7757. {
  7758. if($this->hasEventHandler('onBeforeCount'))
  7759. $this->onBeforeCount(new CEvent($this));
  7760. }
  7761. protected function afterFind()
  7762. {
  7763. if($this->hasEventHandler('onAfterFind'))
  7764. $this->onAfterFind(new CEvent($this));
  7765. }
  7766. public function beforeFindInternal()
  7767. {
  7768. $this->beforeFind();
  7769. }
  7770. public function afterFindInternal()
  7771. {
  7772. $this->afterFind();
  7773. }
  7774. public function insert($attributes=null)
  7775. {
  7776. if(!$this->getIsNewRecord())
  7777. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  7778. if($this->beforeSave())
  7779. {
  7780. $builder=$this->getCommandBuilder();
  7781. $table=$this->getTableSchema();
  7782. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  7783. if($command->execute())
  7784. {
  7785. $primaryKey=$table->primaryKey;
  7786. if($table->sequenceName!==null)
  7787. {
  7788. if(is_string($primaryKey) && $this->$primaryKey===null)
  7789. $this->$primaryKey=$builder->getLastInsertID($table);
  7790. elseif(is_array($primaryKey))
  7791. {
  7792. foreach($primaryKey as $pk)
  7793. {
  7794. if($this->$pk===null)
  7795. {
  7796. $this->$pk=$builder->getLastInsertID($table);
  7797. break;
  7798. }
  7799. }
  7800. }
  7801. }
  7802. $this->_pk=$this->getPrimaryKey();
  7803. $this->afterSave();
  7804. $this->setIsNewRecord(false);
  7805. $this->setScenario('update');
  7806. return true;
  7807. }
  7808. }
  7809. return false;
  7810. }
  7811. public function update($attributes=null)
  7812. {
  7813. if($this->getIsNewRecord())
  7814. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7815. if($this->beforeSave())
  7816. {
  7817. if($this->_pk===null)
  7818. $this->_pk=$this->getPrimaryKey();
  7819. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  7820. $this->_pk=$this->getPrimaryKey();
  7821. $this->afterSave();
  7822. return true;
  7823. }
  7824. else
  7825. return false;
  7826. }
  7827. public function saveAttributes($attributes)
  7828. {
  7829. if(!$this->getIsNewRecord())
  7830. {
  7831. $values=array();
  7832. foreach($attributes as $name=>$value)
  7833. {
  7834. if(is_integer($name))
  7835. $values[$value]=$this->$value;
  7836. else
  7837. $values[$name]=$this->$name=$value;
  7838. }
  7839. if($this->_pk===null)
  7840. $this->_pk=$this->getPrimaryKey();
  7841. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  7842. {
  7843. $this->_pk=$this->getPrimaryKey();
  7844. return true;
  7845. }
  7846. else
  7847. return false;
  7848. }
  7849. else
  7850. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7851. }
  7852. public function saveCounters($counters)
  7853. {
  7854. $builder=$this->getCommandBuilder();
  7855. $table=$this->getTableSchema();
  7856. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  7857. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7858. if($command->execute())
  7859. {
  7860. foreach($counters as $name=>$value)
  7861. $this->$name=$this->$name+$value;
  7862. return true;
  7863. }
  7864. else
  7865. return false;
  7866. }
  7867. public function delete()
  7868. {
  7869. if(!$this->getIsNewRecord())
  7870. {
  7871. if($this->beforeDelete())
  7872. {
  7873. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  7874. $this->afterDelete();
  7875. return $result;
  7876. }
  7877. else
  7878. return false;
  7879. }
  7880. else
  7881. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  7882. }
  7883. public function refresh()
  7884. {
  7885. if(($record=$this->findByPk($this->getPrimaryKey()))!==null)
  7886. {
  7887. $this->_attributes=array();
  7888. $this->_related=array();
  7889. foreach($this->getMetaData()->columns as $name=>$column)
  7890. {
  7891. if(property_exists($this,$name))
  7892. $this->$name=$record->$name;
  7893. else
  7894. $this->_attributes[$name]=$record->$name;
  7895. }
  7896. return true;
  7897. }
  7898. else
  7899. return false;
  7900. }
  7901. public function equals($record)
  7902. {
  7903. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  7904. }
  7905. public function getPrimaryKey()
  7906. {
  7907. $table=$this->getTableSchema();
  7908. if(is_string($table->primaryKey))
  7909. return $this->{$table->primaryKey};
  7910. elseif(is_array($table->primaryKey))
  7911. {
  7912. $values=array();
  7913. foreach($table->primaryKey as $name)
  7914. $values[$name]=$this->$name;
  7915. return $values;
  7916. }
  7917. else
  7918. return null;
  7919. }
  7920. public function setPrimaryKey($value)
  7921. {
  7922. $this->_pk=$this->getPrimaryKey();
  7923. $table=$this->getTableSchema();
  7924. if(is_string($table->primaryKey))
  7925. $this->{$table->primaryKey}=$value;
  7926. elseif(is_array($table->primaryKey))
  7927. {
  7928. foreach($table->primaryKey as $name)
  7929. $this->$name=$value[$name];
  7930. }
  7931. }
  7932. public function getOldPrimaryKey()
  7933. {
  7934. return $this->_pk;
  7935. }
  7936. public function setOldPrimaryKey($value)
  7937. {
  7938. $this->_pk=$value;
  7939. }
  7940. protected function query($criteria,$all=false)
  7941. {
  7942. $this->beforeFind();
  7943. $this->applyScopes($criteria);
  7944. if(empty($criteria->with))
  7945. {
  7946. if(!$all)
  7947. $criteria->limit=1;
  7948. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  7949. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  7950. }
  7951. else
  7952. {
  7953. $finder=$this->getActiveFinder($criteria->with);
  7954. return $finder->query($criteria,$all);
  7955. }
  7956. }
  7957. public function applyScopes(&$criteria)
  7958. {
  7959. if(!empty($criteria->scopes))
  7960. {
  7961. $scs=$this->scopes();
  7962. $c=$this->getDbCriteria();
  7963. foreach((array)$criteria->scopes as $k=>$v)
  7964. {
  7965. if(is_integer($k))
  7966. {
  7967. if(is_string($v))
  7968. {
  7969. if(isset($scs[$v]))
  7970. {
  7971. $c->mergeWith($scs[$v],true);
  7972. continue;
  7973. }
  7974. $scope=$v;
  7975. $params=array();
  7976. }
  7977. elseif(is_array($v))
  7978. {
  7979. $scope=key($v);
  7980. $params=current($v);
  7981. }
  7982. }
  7983. elseif(is_string($k))
  7984. {
  7985. $scope=$k;
  7986. $params=$v;
  7987. }
  7988. call_user_func_array(array($this,$scope),(array)$params);
  7989. }
  7990. }
  7991. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  7992. {
  7993. $c->mergeWith($criteria);
  7994. $criteria=$c;
  7995. $this->resetScope(false);
  7996. }
  7997. }
  7998. public function getTableAlias($quote=false, $checkScopes=true)
  7999. {
  8000. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  8001. $alias=$criteria->alias;
  8002. else
  8003. $alias=$this->_alias;
  8004. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  8005. }
  8006. public function setTableAlias($alias)
  8007. {
  8008. $this->_alias=$alias;
  8009. }
  8010. public function find($condition='',$params=array())
  8011. {
  8012. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  8013. return $this->query($criteria);
  8014. }
  8015. public function findAll($condition='',$params=array())
  8016. {
  8017. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  8018. return $this->query($criteria,true);
  8019. }
  8020. public function findByPk($pk,$condition='',$params=array())
  8021. {
  8022. $prefix=$this->getTableAlias(true).'.';
  8023. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  8024. return $this->query($criteria);
  8025. }
  8026. public function findAllByPk($pk,$condition='',$params=array())
  8027. {
  8028. $prefix=$this->getTableAlias(true).'.';
  8029. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  8030. return $this->query($criteria,true);
  8031. }
  8032. public function findByAttributes($attributes,$condition='',$params=array())
  8033. {
  8034. $prefix=$this->getTableAlias(true).'.';
  8035. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8036. return $this->query($criteria);
  8037. }
  8038. public function findAllByAttributes($attributes,$condition='',$params=array())
  8039. {
  8040. $prefix=$this->getTableAlias(true).'.';
  8041. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8042. return $this->query($criteria,true);
  8043. }
  8044. public function findBySql($sql,$params=array())
  8045. {
  8046. $this->beforeFind();
  8047. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  8048. {
  8049. $this->resetScope(false);
  8050. $finder=$this->getActiveFinder($criteria->with);
  8051. return $finder->findBySql($sql,$params);
  8052. }
  8053. else
  8054. {
  8055. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  8056. return $this->populateRecord($command->queryRow());
  8057. }
  8058. }
  8059. public function findAllBySql($sql,$params=array())
  8060. {
  8061. $this->beforeFind();
  8062. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  8063. {
  8064. $this->resetScope(false);
  8065. $finder=$this->getActiveFinder($criteria->with);
  8066. return $finder->findAllBySql($sql,$params);
  8067. }
  8068. else
  8069. {
  8070. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  8071. return $this->populateRecords($command->queryAll());
  8072. }
  8073. }
  8074. public function count($condition='',$params=array())
  8075. {
  8076. $this->beforeCount();
  8077. $builder=$this->getCommandBuilder();
  8078. $criteria=$builder->createCriteria($condition,$params);
  8079. $this->applyScopes($criteria);
  8080. if(empty($criteria->with))
  8081. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  8082. else
  8083. {
  8084. $finder=$this->getActiveFinder($criteria->with);
  8085. return $finder->count($criteria);
  8086. }
  8087. }
  8088. public function countByAttributes($attributes,$condition='',$params=array())
  8089. {
  8090. $prefix=$this->getTableAlias(true).'.';
  8091. $builder=$this->getCommandBuilder();
  8092. $this->beforeCount();
  8093. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8094. $this->applyScopes($criteria);
  8095. if(empty($criteria->with))
  8096. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  8097. else
  8098. {
  8099. $finder=$this->getActiveFinder($criteria->with);
  8100. return $finder->count($criteria);
  8101. }
  8102. }
  8103. public function countBySql($sql,$params=array())
  8104. {
  8105. $this->beforeCount();
  8106. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  8107. }
  8108. public function exists($condition='',$params=array())
  8109. {
  8110. $builder=$this->getCommandBuilder();
  8111. $criteria=$builder->createCriteria($condition,$params);
  8112. $table=$this->getTableSchema();
  8113. $criteria->select='1';
  8114. $criteria->limit=1;
  8115. $this->applyScopes($criteria);
  8116. if(empty($criteria->with))
  8117. return $builder->createFindCommand($table,$criteria,$this->getTableAlias(false, false))->queryRow()!==false;
  8118. else
  8119. {
  8120. $criteria->select='*';
  8121. $finder=$this->getActiveFinder($criteria->with);
  8122. return $finder->count($criteria)>0;
  8123. }
  8124. }
  8125. public function with()
  8126. {
  8127. if(func_num_args()>0)
  8128. {
  8129. $with=func_get_args();
  8130. if(is_array($with[0])) // the parameter is given as an array
  8131. $with=$with[0];
  8132. if(!empty($with))
  8133. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  8134. }
  8135. return $this;
  8136. }
  8137. public function together()
  8138. {
  8139. $this->getDbCriteria()->together=true;
  8140. return $this;
  8141. }
  8142. public function updateByPk($pk,$attributes,$condition='',$params=array())
  8143. {
  8144. $builder=$this->getCommandBuilder();
  8145. $table=$this->getTableSchema();
  8146. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  8147. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  8148. return $command->execute();
  8149. }
  8150. public function updateAll($attributes,$condition='',$params=array())
  8151. {
  8152. $builder=$this->getCommandBuilder();
  8153. $criteria=$builder->createCriteria($condition,$params);
  8154. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  8155. return $command->execute();
  8156. }
  8157. public function updateCounters($counters,$condition='',$params=array())
  8158. {
  8159. $builder=$this->getCommandBuilder();
  8160. $criteria=$builder->createCriteria($condition,$params);
  8161. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  8162. return $command->execute();
  8163. }
  8164. public function deleteByPk($pk,$condition='',$params=array())
  8165. {
  8166. $builder=$this->getCommandBuilder();
  8167. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  8168. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  8169. return $command->execute();
  8170. }
  8171. public function deleteAll($condition='',$params=array())
  8172. {
  8173. $builder=$this->getCommandBuilder();
  8174. $criteria=$builder->createCriteria($condition,$params);
  8175. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  8176. return $command->execute();
  8177. }
  8178. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  8179. {
  8180. $builder=$this->getCommandBuilder();
  8181. $table=$this->getTableSchema();
  8182. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  8183. $command=$builder->createDeleteCommand($table,$criteria);
  8184. return $command->execute();
  8185. }
  8186. public function populateRecord($attributes,$callAfterFind=true)
  8187. {
  8188. if($attributes!==false)
  8189. {
  8190. $record=$this->instantiate($attributes);
  8191. $record->setScenario('update');
  8192. $record->init();
  8193. $md=$record->getMetaData();
  8194. foreach($attributes as $name=>$value)
  8195. {
  8196. if(property_exists($record,$name))
  8197. $record->$name=$value;
  8198. elseif(isset($md->columns[$name]))
  8199. $record->_attributes[$name]=$value;
  8200. }
  8201. $record->_pk=$record->getPrimaryKey();
  8202. $record->attachBehaviors($record->behaviors());
  8203. if($callAfterFind)
  8204. $record->afterFind();
  8205. return $record;
  8206. }
  8207. else
  8208. return null;
  8209. }
  8210. public function populateRecords($data,$callAfterFind=true,$index=null)
  8211. {
  8212. $records=array();
  8213. foreach($data as $attributes)
  8214. {
  8215. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  8216. {
  8217. if($index===null)
  8218. $records[]=$record;
  8219. else
  8220. $records[$record->$index]=$record;
  8221. }
  8222. }
  8223. return $records;
  8224. }
  8225. protected function instantiate($attributes)
  8226. {
  8227. $class=get_class($this);
  8228. $model=new $class(null);
  8229. return $model;
  8230. }
  8231. public function offsetExists($offset)
  8232. {
  8233. return $this->__isset($offset);
  8234. }
  8235. }
  8236. class CBaseActiveRelation extends CComponent
  8237. {
  8238. public $name;
  8239. public $className;
  8240. public $foreignKey;
  8241. public $select='*';
  8242. public $condition='';
  8243. public $params=array();
  8244. public $group='';
  8245. public $join='';
  8246. public $joinOptions='';
  8247. public $having='';
  8248. public $order='';
  8249. public function __construct($name,$className,$foreignKey,$options=array())
  8250. {
  8251. $this->name=$name;
  8252. $this->className=$className;
  8253. $this->foreignKey=$foreignKey;
  8254. foreach($options as $name=>$value)
  8255. $this->$name=$value;
  8256. }
  8257. public function mergeWith($criteria,$fromScope=false)
  8258. {
  8259. if($criteria instanceof CDbCriteria)
  8260. $criteria=$criteria->toArray();
  8261. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  8262. {
  8263. if($this->select==='*')
  8264. $this->select=$criteria['select'];
  8265. elseif($criteria['select']!=='*')
  8266. {
  8267. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  8268. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  8269. $this->select=array_merge($select1,array_diff($select2,$select1));
  8270. }
  8271. }
  8272. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  8273. {
  8274. if($this->condition==='')
  8275. $this->condition=$criteria['condition'];
  8276. elseif($criteria['condition']!=='')
  8277. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  8278. }
  8279. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  8280. $this->params=array_merge($this->params,$criteria['params']);
  8281. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  8282. {
  8283. if($this->order==='')
  8284. $this->order=$criteria['order'];
  8285. elseif($criteria['order']!=='')
  8286. $this->order=$criteria['order'].', '.$this->order;
  8287. }
  8288. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  8289. {
  8290. if($this->group==='')
  8291. $this->group=$criteria['group'];
  8292. elseif($criteria['group']!=='')
  8293. $this->group.=', '.$criteria['group'];
  8294. }
  8295. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  8296. {
  8297. if($this->join==='')
  8298. $this->join=$criteria['join'];
  8299. elseif($criteria['join']!=='')
  8300. $this->join.=' '.$criteria['join'];
  8301. }
  8302. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  8303. {
  8304. if($this->having==='')
  8305. $this->having=$criteria['having'];
  8306. elseif($criteria['having']!=='')
  8307. $this->having="({$this->having}) AND ({$criteria['having']})";
  8308. }
  8309. }
  8310. }
  8311. class CStatRelation extends CBaseActiveRelation
  8312. {
  8313. public $select='COUNT(*)';
  8314. public $defaultValue=0;
  8315. public $scopes;
  8316. public function mergeWith($criteria,$fromScope=false)
  8317. {
  8318. if($criteria instanceof CDbCriteria)
  8319. $criteria=$criteria->toArray();
  8320. parent::mergeWith($criteria,$fromScope);
  8321. if(isset($criteria['defaultValue']))
  8322. $this->defaultValue=$criteria['defaultValue'];
  8323. }
  8324. }
  8325. class CActiveRelation extends CBaseActiveRelation
  8326. {
  8327. public $joinType='LEFT OUTER JOIN';
  8328. public $on='';
  8329. public $alias;
  8330. public $with=array();
  8331. public $together;
  8332. public $scopes;
  8333. public $through;
  8334. public function mergeWith($criteria,$fromScope=false)
  8335. {
  8336. if($criteria instanceof CDbCriteria)
  8337. $criteria=$criteria->toArray();
  8338. if($fromScope)
  8339. {
  8340. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  8341. {
  8342. if($this->on==='')
  8343. $this->on=$criteria['condition'];
  8344. elseif($criteria['condition']!=='')
  8345. $this->on="({$this->on}) AND ({$criteria['condition']})";
  8346. }
  8347. unset($criteria['condition']);
  8348. }
  8349. parent::mergeWith($criteria);
  8350. if(isset($criteria['joinType']))
  8351. $this->joinType=$criteria['joinType'];
  8352. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  8353. {
  8354. if($this->on==='')
  8355. $this->on=$criteria['on'];
  8356. elseif($criteria['on']!=='')
  8357. $this->on="({$this->on}) AND ({$criteria['on']})";
  8358. }
  8359. if(isset($criteria['with']))
  8360. $this->with=$criteria['with'];
  8361. if(isset($criteria['alias']))
  8362. $this->alias=$criteria['alias'];
  8363. if(isset($criteria['together']))
  8364. $this->together=$criteria['together'];
  8365. }
  8366. }
  8367. class CBelongsToRelation extends CActiveRelation
  8368. {
  8369. }
  8370. class CHasOneRelation extends CActiveRelation
  8371. {
  8372. }
  8373. class CHasManyRelation extends CActiveRelation
  8374. {
  8375. public $limit=-1;
  8376. public $offset=-1;
  8377. public $index;
  8378. public function mergeWith($criteria,$fromScope=false)
  8379. {
  8380. if($criteria instanceof CDbCriteria)
  8381. $criteria=$criteria->toArray();
  8382. parent::mergeWith($criteria,$fromScope);
  8383. if(isset($criteria['limit']) && $criteria['limit']>0)
  8384. $this->limit=$criteria['limit'];
  8385. if(isset($criteria['offset']) && $criteria['offset']>=0)
  8386. $this->offset=$criteria['offset'];
  8387. if(isset($criteria['index']))
  8388. $this->index=$criteria['index'];
  8389. }
  8390. }
  8391. class CManyManyRelation extends CHasManyRelation
  8392. {
  8393. private $_junctionTableName=null;
  8394. private $_junctionForeignKeys=null;
  8395. public function getJunctionTableName()
  8396. {
  8397. if ($this->_junctionTableName===null)
  8398. $this->initJunctionData();
  8399. return $this->_junctionTableName;
  8400. }
  8401. public function getJunctionForeignKeys()
  8402. {
  8403. if ($this->_junctionForeignKeys===null)
  8404. $this->initJunctionData();
  8405. return $this->_junctionForeignKeys;
  8406. }
  8407. private function initJunctionData()
  8408. {
  8409. if(!preg_match('/^\s*(.*?)\((.*)\)\s*$/',$this->foreignKey,$matches))
  8410. throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key. The format of the foreign key must be "joinTable(fk1,fk2,...)".',
  8411. array('{class}'=>$this->className,'{relation}'=>$this->name)));
  8412. $this->_junctionTableName=$matches[1];
  8413. $this->_junctionForeignKeys=preg_split('/\s*,\s*/',$matches[2],-1,PREG_SPLIT_NO_EMPTY);
  8414. }
  8415. }
  8416. class CActiveRecordMetaData
  8417. {
  8418. public $tableSchema;
  8419. public $columns;
  8420. public $relations=array();
  8421. public $attributeDefaults=array();
  8422. private $_modelClassName;
  8423. public function __construct($model)
  8424. {
  8425. $this->_modelClassName=get_class($model);
  8426. $tableName=$model->tableName();
  8427. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  8428. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  8429. array('{class}'=>$this->_modelClassName,'{table}'=>$tableName)));
  8430. if($table->primaryKey===null)
  8431. {
  8432. $table->primaryKey=$model->primaryKey();
  8433. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  8434. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  8435. elseif(is_array($table->primaryKey))
  8436. {
  8437. foreach($table->primaryKey as $name)
  8438. {
  8439. if(isset($table->columns[$name]))
  8440. $table->columns[$name]->isPrimaryKey=true;
  8441. }
  8442. }
  8443. }
  8444. $this->tableSchema=$table;
  8445. $this->columns=$table->columns;
  8446. foreach($table->columns as $name=>$column)
  8447. {
  8448. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  8449. $this->attributeDefaults[$name]=$column->defaultValue;
  8450. }
  8451. foreach($model->relations() as $name=>$config)
  8452. {
  8453. $this->addRelation($name,$config);
  8454. }
  8455. }
  8456. public function addRelation($name,$config)
  8457. {
  8458. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  8459. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  8460. else
  8461. 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}'=>$this->_modelClassName,'{relation}'=>$name)));
  8462. }
  8463. public function hasRelation($name)
  8464. {
  8465. return isset($this->relations[$name]);
  8466. }
  8467. public function removeRelation($name)
  8468. {
  8469. unset($this->relations[$name]);
  8470. }
  8471. }
  8472. class CDbConnection extends CApplicationComponent
  8473. {
  8474. public $connectionString;
  8475. public $username='';
  8476. public $password='';
  8477. public $schemaCachingDuration=0;
  8478. public $schemaCachingExclude=array();
  8479. public $schemaCacheID='cache';
  8480. public $queryCachingDuration=0;
  8481. public $queryCachingDependency;
  8482. public $queryCachingCount=0;
  8483. public $queryCacheID='cache';
  8484. public $autoConnect=true;
  8485. public $charset;
  8486. public $emulatePrepare;
  8487. public $enableParamLogging=false;
  8488. public $enableProfiling=false;
  8489. public $tablePrefix;
  8490. public $initSQLs;
  8491. public $driverMap=array(
  8492. 'cubrid'=>'CCubridSchema', // CUBRID
  8493. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  8494. 'mysqli'=>'CMysqlSchema', // MySQL
  8495. 'mysql'=>'CMysqlSchema', // MySQL,MariaDB
  8496. 'sqlite'=>'CSqliteSchema', // sqlite 3
  8497. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  8498. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  8499. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  8500. 'sqlsrv'=>'CMssqlSchema', // Mssql
  8501. 'oci'=>'COciSchema', // Oracle driver
  8502. );
  8503. public $pdoClass = 'PDO';
  8504. private $_driverName;
  8505. private $_attributes=array();
  8506. private $_active=false;
  8507. private $_pdo;
  8508. private $_transaction;
  8509. private $_schema;
  8510. public function __construct($dsn='',$username='',$password='')
  8511. {
  8512. $this->connectionString=$dsn;
  8513. $this->username=$username;
  8514. $this->password=$password;
  8515. }
  8516. public function __sleep()
  8517. {
  8518. $this->close();
  8519. return array_keys(get_object_vars($this));
  8520. }
  8521. public static function getAvailableDrivers()
  8522. {
  8523. return PDO::getAvailableDrivers();
  8524. }
  8525. public function init()
  8526. {
  8527. parent::init();
  8528. if($this->autoConnect)
  8529. $this->setActive(true);
  8530. }
  8531. public function getActive()
  8532. {
  8533. return $this->_active;
  8534. }
  8535. public function setActive($value)
  8536. {
  8537. if($value!=$this->_active)
  8538. {
  8539. if($value)
  8540. $this->open();
  8541. else
  8542. $this->close();
  8543. }
  8544. }
  8545. public function cache($duration, $dependency=null, $queryCount=1)
  8546. {
  8547. $this->queryCachingDuration=$duration;
  8548. $this->queryCachingDependency=$dependency;
  8549. $this->queryCachingCount=$queryCount;
  8550. return $this;
  8551. }
  8552. protected function open()
  8553. {
  8554. if($this->_pdo===null)
  8555. {
  8556. if(empty($this->connectionString))
  8557. throw new CDbException('CDbConnection.connectionString cannot be empty.');
  8558. try
  8559. {
  8560. $this->_pdo=$this->createPdoInstance();
  8561. $this->initConnection($this->_pdo);
  8562. $this->_active=true;
  8563. }
  8564. catch(PDOException $e)
  8565. {
  8566. if(YII_DEBUG)
  8567. {
  8568. throw new CDbException('CDbConnection failed to open the DB connection: '.
  8569. $e->getMessage(),(int)$e->getCode(),$e->errorInfo);
  8570. }
  8571. else
  8572. {
  8573. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  8574. throw new CDbException('CDbConnection failed to open the DB connection.',(int)$e->getCode(),$e->errorInfo);
  8575. }
  8576. }
  8577. }
  8578. }
  8579. protected function close()
  8580. {
  8581. $this->_pdo=null;
  8582. $this->_active=false;
  8583. $this->_schema=null;
  8584. }
  8585. protected function createPdoInstance()
  8586. {
  8587. $pdoClass=$this->pdoClass;
  8588. if(($driver=$this->getDriverName())!==null)
  8589. {
  8590. if($driver==='mssql' || $driver==='dblib')
  8591. $pdoClass='CMssqlPdoAdapter';
  8592. elseif($driver==='sqlsrv')
  8593. $pdoClass='CMssqlSqlsrvPdoAdapter';
  8594. }
  8595. if(!class_exists($pdoClass))
  8596. throw new CDbException(Yii::t('yii','CDbConnection is unable to find PDO class "{className}". Make sure PDO is installed correctly.',
  8597. array('{className}'=>$pdoClass)));
  8598. @$instance=new $pdoClass($this->connectionString,$this->username,$this->password,$this->_attributes);
  8599. if(!$instance)
  8600. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'));
  8601. return $instance;
  8602. }
  8603. protected function initConnection($pdo)
  8604. {
  8605. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  8606. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  8607. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  8608. if($this->charset!==null)
  8609. {
  8610. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  8611. if(in_array($driver,array('pgsql','mysql','mysqli')))
  8612. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  8613. }
  8614. if($this->initSQLs!==null)
  8615. {
  8616. foreach($this->initSQLs as $sql)
  8617. $pdo->exec($sql);
  8618. }
  8619. }
  8620. public function getPdoInstance()
  8621. {
  8622. return $this->_pdo;
  8623. }
  8624. public function createCommand($query=null)
  8625. {
  8626. $this->setActive(true);
  8627. return new CDbCommand($this,$query);
  8628. }
  8629. public function getCurrentTransaction()
  8630. {
  8631. if($this->_transaction!==null)
  8632. {
  8633. if($this->_transaction->getActive())
  8634. return $this->_transaction;
  8635. }
  8636. return null;
  8637. }
  8638. public function beginTransaction()
  8639. {
  8640. $this->setActive(true);
  8641. $this->_pdo->beginTransaction();
  8642. return $this->_transaction=new CDbTransaction($this);
  8643. }
  8644. public function getSchema()
  8645. {
  8646. if($this->_schema!==null)
  8647. return $this->_schema;
  8648. else
  8649. {
  8650. $driver=$this->getDriverName();
  8651. if(isset($this->driverMap[$driver]))
  8652. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  8653. else
  8654. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  8655. array('{driver}'=>$driver)));
  8656. }
  8657. }
  8658. public function getCommandBuilder()
  8659. {
  8660. return $this->getSchema()->getCommandBuilder();
  8661. }
  8662. public function getLastInsertID($sequenceName='')
  8663. {
  8664. $this->setActive(true);
  8665. return $this->_pdo->lastInsertId($sequenceName);
  8666. }
  8667. public function quoteValue($str)
  8668. {
  8669. if(is_int($str) || is_float($str))
  8670. return $str;
  8671. $this->setActive(true);
  8672. if(($value=$this->_pdo->quote($str))!==false)
  8673. return $value;
  8674. else // the driver doesn't support quote (e.g. oci)
  8675. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  8676. }
  8677. public function quoteTableName($name)
  8678. {
  8679. return $this->getSchema()->quoteTableName($name);
  8680. }
  8681. public function quoteColumnName($name)
  8682. {
  8683. return $this->getSchema()->quoteColumnName($name);
  8684. }
  8685. public function getPdoType($type)
  8686. {
  8687. static $map=array
  8688. (
  8689. 'boolean'=>PDO::PARAM_BOOL,
  8690. 'integer'=>PDO::PARAM_INT,
  8691. 'string'=>PDO::PARAM_STR,
  8692. 'resource'=>PDO::PARAM_LOB,
  8693. 'NULL'=>PDO::PARAM_NULL,
  8694. );
  8695. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  8696. }
  8697. public function getColumnCase()
  8698. {
  8699. return $this->getAttribute(PDO::ATTR_CASE);
  8700. }
  8701. public function setColumnCase($value)
  8702. {
  8703. $this->setAttribute(PDO::ATTR_CASE,$value);
  8704. }
  8705. public function getNullConversion()
  8706. {
  8707. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  8708. }
  8709. public function setNullConversion($value)
  8710. {
  8711. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  8712. }
  8713. public function getAutoCommit()
  8714. {
  8715. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  8716. }
  8717. public function setAutoCommit($value)
  8718. {
  8719. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  8720. }
  8721. public function getPersistent()
  8722. {
  8723. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  8724. }
  8725. public function setPersistent($value)
  8726. {
  8727. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  8728. }
  8729. public function getDriverName()
  8730. {
  8731. if($this->_driverName!==null)
  8732. return $this->_driverName;
  8733. elseif(($pos=strpos($this->connectionString,':'))!==false)
  8734. return $this->_driverName=strtolower(substr($this->connectionString,0,$pos));
  8735. //return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  8736. }
  8737. public function setDriverName($driverName)
  8738. {
  8739. $this->_driverName=strtolower($driverName);
  8740. }
  8741. public function getClientVersion()
  8742. {
  8743. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  8744. }
  8745. public function getConnectionStatus()
  8746. {
  8747. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  8748. }
  8749. public function getPrefetch()
  8750. {
  8751. return $this->getAttribute(PDO::ATTR_PREFETCH);
  8752. }
  8753. public function getServerInfo()
  8754. {
  8755. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  8756. }
  8757. public function getServerVersion()
  8758. {
  8759. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  8760. }
  8761. public function getTimeout()
  8762. {
  8763. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  8764. }
  8765. public function getAttribute($name)
  8766. {
  8767. $this->setActive(true);
  8768. return $this->_pdo->getAttribute($name);
  8769. }
  8770. public function setAttribute($name,$value)
  8771. {
  8772. if($this->_pdo instanceof PDO)
  8773. $this->_pdo->setAttribute($name,$value);
  8774. else
  8775. $this->_attributes[$name]=$value;
  8776. }
  8777. public function getAttributes()
  8778. {
  8779. return $this->_attributes;
  8780. }
  8781. public function setAttributes($values)
  8782. {
  8783. foreach($values as $name=>$value)
  8784. $this->_attributes[$name]=$value;
  8785. }
  8786. public function getStats()
  8787. {
  8788. $logger=Yii::getLogger();
  8789. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  8790. $count=count($timings);
  8791. $time=array_sum($timings);
  8792. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  8793. $count+=count($timings);
  8794. $time+=array_sum($timings);
  8795. return array($count,$time);
  8796. }
  8797. }
  8798. abstract class CDbSchema extends CComponent
  8799. {
  8800. public $columnTypes=array();
  8801. private $_tableNames=array();
  8802. private $_tables=array();
  8803. private $_connection;
  8804. private $_builder;
  8805. private $_cacheExclude=array();
  8806. abstract protected function loadTable($name);
  8807. public function __construct($conn)
  8808. {
  8809. $this->_connection=$conn;
  8810. foreach($conn->schemaCachingExclude as $name)
  8811. $this->_cacheExclude[$name]=true;
  8812. }
  8813. public function getDbConnection()
  8814. {
  8815. return $this->_connection;
  8816. }
  8817. public function getTable($name,$refresh=false)
  8818. {
  8819. if($refresh===false && isset($this->_tables[$name]))
  8820. return $this->_tables[$name];
  8821. else
  8822. {
  8823. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  8824. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  8825. else
  8826. $realName=$name;
  8827. // temporarily disable query caching
  8828. if($this->_connection->queryCachingDuration>0)
  8829. {
  8830. $qcDuration=$this->_connection->queryCachingDuration;
  8831. $this->_connection->queryCachingDuration=0;
  8832. }
  8833. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8834. {
  8835. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8836. $table=$cache->get($key);
  8837. if($refresh===true || $table===false)
  8838. {
  8839. $table=$this->loadTable($realName);
  8840. if($table!==null)
  8841. $cache->set($key,$table,$duration);
  8842. }
  8843. $this->_tables[$name]=$table;
  8844. }
  8845. else
  8846. $this->_tables[$name]=$table=$this->loadTable($realName);
  8847. if(isset($qcDuration)) // re-enable query caching
  8848. $this->_connection->queryCachingDuration=$qcDuration;
  8849. return $table;
  8850. }
  8851. }
  8852. public function getTables($schema='')
  8853. {
  8854. $tables=array();
  8855. foreach($this->getTableNames($schema) as $name)
  8856. {
  8857. if(($table=$this->getTable($name))!==null)
  8858. $tables[$name]=$table;
  8859. }
  8860. return $tables;
  8861. }
  8862. public function getTableNames($schema='')
  8863. {
  8864. if(!isset($this->_tableNames[$schema]))
  8865. $this->_tableNames[$schema]=$this->findTableNames($schema);
  8866. return $this->_tableNames[$schema];
  8867. }
  8868. public function getCommandBuilder()
  8869. {
  8870. if($this->_builder!==null)
  8871. return $this->_builder;
  8872. else
  8873. return $this->_builder=$this->createCommandBuilder();
  8874. }
  8875. public function refresh()
  8876. {
  8877. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8878. {
  8879. foreach(array_keys($this->_tables) as $name)
  8880. {
  8881. if(!isset($this->_cacheExclude[$name]))
  8882. {
  8883. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8884. $cache->delete($key);
  8885. }
  8886. }
  8887. }
  8888. $this->_tables=array();
  8889. $this->_tableNames=array();
  8890. $this->_builder=null;
  8891. }
  8892. public function quoteTableName($name)
  8893. {
  8894. if(strpos($name,'.')===false)
  8895. return $this->quoteSimpleTableName($name);
  8896. $parts=explode('.',$name);
  8897. foreach($parts as $i=>$part)
  8898. $parts[$i]=$this->quoteSimpleTableName($part);
  8899. return implode('.',$parts);
  8900. }
  8901. public function quoteSimpleTableName($name)
  8902. {
  8903. return "'".$name."'";
  8904. }
  8905. public function quoteColumnName($name)
  8906. {
  8907. if(($pos=strrpos($name,'.'))!==false)
  8908. {
  8909. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  8910. $name=substr($name,$pos+1);
  8911. }
  8912. else
  8913. $prefix='';
  8914. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  8915. }
  8916. public function quoteSimpleColumnName($name)
  8917. {
  8918. return '"'.$name.'"';
  8919. }
  8920. public function compareTableNames($name1,$name2)
  8921. {
  8922. $name1=str_replace(array('"','`',"'"),'',$name1);
  8923. $name2=str_replace(array('"','`',"'"),'',$name2);
  8924. if(($pos=strrpos($name1,'.'))!==false)
  8925. $name1=substr($name1,$pos+1);
  8926. if(($pos=strrpos($name2,'.'))!==false)
  8927. $name2=substr($name2,$pos+1);
  8928. if($this->_connection->tablePrefix!==null)
  8929. {
  8930. if(strpos($name1,'{')!==false)
  8931. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  8932. if(strpos($name2,'{')!==false)
  8933. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  8934. }
  8935. return $name1===$name2;
  8936. }
  8937. public function resetSequence($table,$value=null)
  8938. {
  8939. }
  8940. public function checkIntegrity($check=true,$schema='')
  8941. {
  8942. }
  8943. protected function createCommandBuilder()
  8944. {
  8945. return new CDbCommandBuilder($this);
  8946. }
  8947. protected function findTableNames($schema='')
  8948. {
  8949. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  8950. array('{class}'=>get_class($this))));
  8951. }
  8952. public function getColumnType($type)
  8953. {
  8954. if(isset($this->columnTypes[$type]))
  8955. return $this->columnTypes[$type];
  8956. elseif(($pos=strpos($type,' '))!==false)
  8957. {
  8958. $t=substr($type,0,$pos);
  8959. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  8960. }
  8961. else
  8962. return $type;
  8963. }
  8964. public function createTable($table,$columns,$options=null)
  8965. {
  8966. $cols=array();
  8967. foreach($columns as $name=>$type)
  8968. {
  8969. if(is_string($name))
  8970. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  8971. else
  8972. $cols[]="\t".$type;
  8973. }
  8974. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  8975. return $options===null ? $sql : $sql.' '.$options;
  8976. }
  8977. public function renameTable($table,$newName)
  8978. {
  8979. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  8980. }
  8981. public function dropTable($table)
  8982. {
  8983. return "DROP TABLE ".$this->quoteTableName($table);
  8984. }
  8985. public function truncateTable($table)
  8986. {
  8987. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  8988. }
  8989. public function addColumn($table,$column,$type)
  8990. {
  8991. return 'ALTER TABLE ' . $this->quoteTableName($table)
  8992. . ' ADD ' . $this->quoteColumnName($column) . ' '
  8993. . $this->getColumnType($type);
  8994. }
  8995. public function dropColumn($table,$column)
  8996. {
  8997. return "ALTER TABLE ".$this->quoteTableName($table)
  8998. ." DROP COLUMN ".$this->quoteColumnName($column);
  8999. }
  9000. public function renameColumn($table,$name,$newName)
  9001. {
  9002. return "ALTER TABLE ".$this->quoteTableName($table)
  9003. . " RENAME COLUMN ".$this->quoteColumnName($name)
  9004. . " TO ".$this->quoteColumnName($newName);
  9005. }
  9006. public function alterColumn($table,$column,$type)
  9007. {
  9008. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  9009. . $this->quoteColumnName($column) . ' '
  9010. . $this->quoteColumnName($column) . ' '
  9011. . $this->getColumnType($type);
  9012. }
  9013. public function addForeignKey($name,$table,$columns,$refTable,$refColumns,$delete=null,$update=null)
  9014. {
  9015. if(is_string($columns))
  9016. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9017. foreach($columns as $i=>$col)
  9018. $columns[$i]=$this->quoteColumnName($col);
  9019. if(is_string($refColumns))
  9020. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  9021. foreach($refColumns as $i=>$col)
  9022. $refColumns[$i]=$this->quoteColumnName($col);
  9023. $sql='ALTER TABLE '.$this->quoteTableName($table)
  9024. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  9025. .' FOREIGN KEY ('.implode(', ',$columns).')'
  9026. .' REFERENCES '.$this->quoteTableName($refTable)
  9027. .' ('.implode(', ',$refColumns).')';
  9028. if($delete!==null)
  9029. $sql.=' ON DELETE '.$delete;
  9030. if($update!==null)
  9031. $sql.=' ON UPDATE '.$update;
  9032. return $sql;
  9033. }
  9034. public function dropForeignKey($name,$table)
  9035. {
  9036. return 'ALTER TABLE '.$this->quoteTableName($table)
  9037. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  9038. }
  9039. public function createIndex($name,$table,$columns,$unique=false)
  9040. {
  9041. $cols=array();
  9042. if(is_string($columns))
  9043. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9044. foreach($columns as $col)
  9045. {
  9046. if(strpos($col,'(')!==false)
  9047. $cols[]=$col;
  9048. else
  9049. $cols[]=$this->quoteColumnName($col);
  9050. }
  9051. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  9052. . $this->quoteTableName($name).' ON '
  9053. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  9054. }
  9055. public function dropIndex($name,$table)
  9056. {
  9057. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  9058. }
  9059. public function addPrimaryKey($name,$table,$columns)
  9060. {
  9061. if(is_string($columns))
  9062. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9063. foreach($columns as $i=>$col)
  9064. $columns[$i]=$this->quoteColumnName($col);
  9065. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' ADD CONSTRAINT '
  9066. . $this->quoteColumnName($name) . ' PRIMARY KEY ('
  9067. . implode(', ',$columns). ' )';
  9068. }
  9069. public function dropPrimaryKey($name,$table)
  9070. {
  9071. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' DROP CONSTRAINT '
  9072. . $this->quoteColumnName($name);
  9073. }
  9074. }
  9075. class CSqliteSchema extends CDbSchema
  9076. {
  9077. public $columnTypes=array(
  9078. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  9079. 'bigpk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  9080. 'string' => 'varchar(255)',
  9081. 'text' => 'text',
  9082. 'integer' => 'integer',
  9083. 'bigint' => 'integer',
  9084. 'float' => 'float',
  9085. 'decimal' => 'decimal',
  9086. 'datetime' => 'datetime',
  9087. 'timestamp' => 'timestamp',
  9088. 'time' => 'time',
  9089. 'date' => 'date',
  9090. 'binary' => 'blob',
  9091. 'boolean' => 'tinyint(1)',
  9092. 'money' => 'decimal(19,4)',
  9093. );
  9094. public function resetSequence($table,$value=null)
  9095. {
  9096. if($table->sequenceName===null)
  9097. return;
  9098. if($value!==null)
  9099. $value=(int)($value)-1;
  9100. else
  9101. $value=(int)$this->getDbConnection()
  9102. ->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")
  9103. ->queryScalar();
  9104. try
  9105. {
  9106. // it's possible that 'sqlite_sequence' does not exist
  9107. $this->getDbConnection()
  9108. ->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")
  9109. ->execute();
  9110. }
  9111. catch(Exception $e)
  9112. {
  9113. }
  9114. }
  9115. public function checkIntegrity($check=true,$schema='')
  9116. {
  9117. $this->getDbConnection()->createCommand('PRAGMA foreign_keys='.(int)$check)->execute();
  9118. }
  9119. protected function findTableNames($schema='')
  9120. {
  9121. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  9122. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  9123. }
  9124. protected function createCommandBuilder()
  9125. {
  9126. return new CSqliteCommandBuilder($this);
  9127. }
  9128. protected function loadTable($name)
  9129. {
  9130. $table=new CDbTableSchema;
  9131. $table->name=$name;
  9132. $table->rawName=$this->quoteTableName($name);
  9133. if($this->findColumns($table))
  9134. {
  9135. $this->findConstraints($table);
  9136. return $table;
  9137. }
  9138. else
  9139. return null;
  9140. }
  9141. protected function findColumns($table)
  9142. {
  9143. $sql="PRAGMA table_info({$table->rawName})";
  9144. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  9145. if(empty($columns))
  9146. return false;
  9147. foreach($columns as $column)
  9148. {
  9149. $c=$this->createColumn($column);
  9150. $table->columns[$c->name]=$c;
  9151. if($c->isPrimaryKey)
  9152. {
  9153. if($table->primaryKey===null)
  9154. $table->primaryKey=$c->name;
  9155. elseif(is_string($table->primaryKey))
  9156. $table->primaryKey=array($table->primaryKey,$c->name);
  9157. else
  9158. $table->primaryKey[]=$c->name;
  9159. }
  9160. }
  9161. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  9162. {
  9163. $table->sequenceName='';
  9164. $table->columns[$table->primaryKey]->autoIncrement=true;
  9165. }
  9166. return true;
  9167. }
  9168. protected function findConstraints($table)
  9169. {
  9170. $foreignKeys=array();
  9171. $sql="PRAGMA foreign_key_list({$table->rawName})";
  9172. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  9173. foreach($keys as $key)
  9174. {
  9175. $column=$table->columns[$key['from']];
  9176. $column->isForeignKey=true;
  9177. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  9178. }
  9179. $table->foreignKeys=$foreignKeys;
  9180. }
  9181. protected function createColumn($column)
  9182. {
  9183. $c=new CSqliteColumnSchema;
  9184. $c->name=$column['name'];
  9185. $c->rawName=$this->quoteColumnName($c->name);
  9186. $c->allowNull=!$column['notnull'];
  9187. $c->isPrimaryKey=$column['pk']!=0;
  9188. $c->isForeignKey=false;
  9189. $c->comment=null; // SQLite does not support column comments at all
  9190. $c->init(strtolower($column['type']),$column['dflt_value']);
  9191. return $c;
  9192. }
  9193. public function renameTable($table, $newName)
  9194. {
  9195. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' RENAME TO ' . $this->quoteTableName($newName);
  9196. }
  9197. public function truncateTable($table)
  9198. {
  9199. return "DELETE FROM ".$this->quoteTableName($table);
  9200. }
  9201. public function dropColumn($table, $column)
  9202. {
  9203. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  9204. }
  9205. public function renameColumn($table, $name, $newName)
  9206. {
  9207. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  9208. }
  9209. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9210. {
  9211. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  9212. }
  9213. public function dropForeignKey($name, $table)
  9214. {
  9215. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  9216. }
  9217. public function alterColumn($table, $column, $type)
  9218. {
  9219. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  9220. }
  9221. public function dropIndex($name, $table)
  9222. {
  9223. return 'DROP INDEX '.$this->quoteTableName($name);
  9224. }
  9225. public function addPrimaryKey($name,$table,$columns)
  9226. {
  9227. throw new CDbException(Yii::t('yii', 'Adding a primary key after table has been created is not supported by SQLite.'));
  9228. }
  9229. public function dropPrimaryKey($name,$table)
  9230. {
  9231. throw new CDbException(Yii::t('yii', 'Removing a primary key after table has been created is not supported by SQLite.'));
  9232. }
  9233. }
  9234. class CDbTableSchema extends CComponent
  9235. {
  9236. public $name;
  9237. public $rawName;
  9238. public $primaryKey;
  9239. public $sequenceName;
  9240. public $foreignKeys=array();
  9241. public $columns=array();
  9242. public function getColumn($name)
  9243. {
  9244. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  9245. }
  9246. public function getColumnNames()
  9247. {
  9248. return array_keys($this->columns);
  9249. }
  9250. }
  9251. class CDbCommand extends CComponent
  9252. {
  9253. public $params=array();
  9254. private $_connection;
  9255. private $_text;
  9256. private $_statement;
  9257. private $_paramLog=array();
  9258. private $_query;
  9259. private $_fetchMode = array(PDO::FETCH_ASSOC);
  9260. public function __construct(CDbConnection $connection,$query=null)
  9261. {
  9262. $this->_connection=$connection;
  9263. if(is_array($query))
  9264. {
  9265. foreach($query as $name=>$value)
  9266. $this->$name=$value;
  9267. }
  9268. else
  9269. $this->setText($query);
  9270. }
  9271. public function __sleep()
  9272. {
  9273. $this->_statement=null;
  9274. return array_keys(get_object_vars($this));
  9275. }
  9276. public function setFetchMode($mode)
  9277. {
  9278. $params=func_get_args();
  9279. $this->_fetchMode = $params;
  9280. return $this;
  9281. }
  9282. public function reset()
  9283. {
  9284. $this->_text=null;
  9285. $this->_query=null;
  9286. $this->_statement=null;
  9287. $this->_paramLog=array();
  9288. $this->params=array();
  9289. return $this;
  9290. }
  9291. public function getText()
  9292. {
  9293. if($this->_text=='' && !empty($this->_query))
  9294. $this->setText($this->buildQuery($this->_query));
  9295. return $this->_text;
  9296. }
  9297. public function setText($value)
  9298. {
  9299. if($this->_connection->tablePrefix!==null && $value!='')
  9300. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  9301. else
  9302. $this->_text=$value;
  9303. $this->cancel();
  9304. return $this;
  9305. }
  9306. public function getConnection()
  9307. {
  9308. return $this->_connection;
  9309. }
  9310. public function getPdoStatement()
  9311. {
  9312. return $this->_statement;
  9313. }
  9314. public function prepare()
  9315. {
  9316. if($this->_statement==null)
  9317. {
  9318. try
  9319. {
  9320. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  9321. $this->_paramLog=array();
  9322. }
  9323. catch(Exception $e)
  9324. {
  9325. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9326. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9327. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  9328. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  9329. }
  9330. }
  9331. }
  9332. public function cancel()
  9333. {
  9334. $this->_statement=null;
  9335. }
  9336. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  9337. {
  9338. $this->prepare();
  9339. if($dataType===null)
  9340. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  9341. elseif($length===null)
  9342. $this->_statement->bindParam($name,$value,$dataType);
  9343. elseif($driverOptions===null)
  9344. $this->_statement->bindParam($name,$value,$dataType,$length);
  9345. else
  9346. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  9347. $this->_paramLog[$name]=&$value;
  9348. return $this;
  9349. }
  9350. public function bindValue($name, $value, $dataType=null)
  9351. {
  9352. $this->prepare();
  9353. if($dataType===null)
  9354. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  9355. else
  9356. $this->_statement->bindValue($name,$value,$dataType);
  9357. $this->_paramLog[$name]=$value;
  9358. return $this;
  9359. }
  9360. public function bindValues($values)
  9361. {
  9362. $this->prepare();
  9363. foreach($values as $name=>$value)
  9364. {
  9365. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  9366. $this->_paramLog[$name]=$value;
  9367. }
  9368. return $this;
  9369. }
  9370. public function execute($params=array())
  9371. {
  9372. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  9373. {
  9374. $p=array();
  9375. foreach($pars as $name=>$value)
  9376. $p[$name]=$name.'='.var_export($value,true);
  9377. $par='. Bound with ' .implode(', ',$p);
  9378. }
  9379. else
  9380. $par='';
  9381. try
  9382. {
  9383. if($this->_connection->enableProfiling)
  9384. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9385. $this->prepare();
  9386. if($params===array())
  9387. $this->_statement->execute();
  9388. else
  9389. $this->_statement->execute($params);
  9390. $n=$this->_statement->rowCount();
  9391. if($this->_connection->enableProfiling)
  9392. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9393. return $n;
  9394. }
  9395. catch(Exception $e)
  9396. {
  9397. if($this->_connection->enableProfiling)
  9398. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9399. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9400. $message=$e->getMessage();
  9401. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  9402. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9403. if(YII_DEBUG)
  9404. $message.='. The SQL statement executed was: '.$this->getText().$par;
  9405. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  9406. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  9407. }
  9408. }
  9409. public function query($params=array())
  9410. {
  9411. return $this->queryInternal('',0,$params);
  9412. }
  9413. public function queryAll($fetchAssociative=true,$params=array())
  9414. {
  9415. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  9416. }
  9417. public function queryRow($fetchAssociative=true,$params=array())
  9418. {
  9419. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  9420. }
  9421. public function queryScalar($params=array())
  9422. {
  9423. $result=$this->queryInternal('fetchColumn',0,$params);
  9424. if(is_resource($result) && get_resource_type($result)==='stream')
  9425. return stream_get_contents($result);
  9426. else
  9427. return $result;
  9428. }
  9429. public function queryColumn($params=array())
  9430. {
  9431. return $this->queryInternal('fetchAll',array(PDO::FETCH_COLUMN, 0),$params);
  9432. }
  9433. private function queryInternal($method,$mode,$params=array())
  9434. {
  9435. $params=array_merge($this->params,$params);
  9436. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  9437. {
  9438. $p=array();
  9439. foreach($pars as $name=>$value)
  9440. $p[$name]=$name.'='.var_export($value,true);
  9441. $par='. Bound with '.implode(', ',$p);
  9442. }
  9443. else
  9444. $par='';
  9445. if($this->_connection->queryCachingCount>0 && $method!==''
  9446. && $this->_connection->queryCachingDuration>0
  9447. && $this->_connection->queryCacheID!==false
  9448. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  9449. {
  9450. $this->_connection->queryCachingCount--;
  9451. $cacheKey='yii:dbquery'.':'.$method.':'.$this->_connection->connectionString.':'.$this->_connection->username;
  9452. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  9453. if(($result=$cache->get($cacheKey))!==false)
  9454. {
  9455. return $result[0];
  9456. }
  9457. }
  9458. try
  9459. {
  9460. if($this->_connection->enableProfiling)
  9461. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9462. $this->prepare();
  9463. if($params===array())
  9464. $this->_statement->execute();
  9465. else
  9466. $this->_statement->execute($params);
  9467. if($method==='')
  9468. $result=new CDbDataReader($this);
  9469. else
  9470. {
  9471. $mode=(array)$mode;
  9472. call_user_func_array(array($this->_statement, 'setFetchMode'), $mode);
  9473. $result=$this->_statement->$method();
  9474. $this->_statement->closeCursor();
  9475. }
  9476. if($this->_connection->enableProfiling)
  9477. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9478. if(isset($cache,$cacheKey))
  9479. $cache->set($cacheKey, array($result), $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  9480. return $result;
  9481. }
  9482. catch(Exception $e)
  9483. {
  9484. if($this->_connection->enableProfiling)
  9485. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9486. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9487. $message=$e->getMessage();
  9488. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  9489. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9490. if(YII_DEBUG)
  9491. $message.='. The SQL statement executed was: '.$this->getText().$par;
  9492. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  9493. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  9494. }
  9495. }
  9496. public function buildQuery($query)
  9497. {
  9498. $sql=!empty($query['distinct']) ? 'SELECT DISTINCT' : 'SELECT';
  9499. $sql.=' '.(!empty($query['select']) ? $query['select'] : '*');
  9500. if(!empty($query['from']))
  9501. $sql.="\nFROM ".$query['from'];
  9502. if(!empty($query['join']))
  9503. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  9504. if(!empty($query['where']))
  9505. $sql.="\nWHERE ".$query['where'];
  9506. if(!empty($query['group']))
  9507. $sql.="\nGROUP BY ".$query['group'];
  9508. if(!empty($query['having']))
  9509. $sql.="\nHAVING ".$query['having'];
  9510. if(!empty($query['union']))
  9511. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  9512. if(!empty($query['order']))
  9513. $sql.="\nORDER BY ".$query['order'];
  9514. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  9515. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  9516. if($limit>=0 || $offset>0)
  9517. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  9518. return $sql;
  9519. }
  9520. public function select($columns='*', $option='')
  9521. {
  9522. if(is_string($columns) && strpos($columns,'(')!==false)
  9523. $this->_query['select']=$columns;
  9524. else
  9525. {
  9526. if(!is_array($columns))
  9527. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9528. foreach($columns as $i=>$column)
  9529. {
  9530. if(is_object($column))
  9531. $columns[$i]=(string)$column;
  9532. elseif(strpos($column,'(')===false)
  9533. {
  9534. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  9535. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  9536. else
  9537. $columns[$i]=$this->_connection->quoteColumnName($column);
  9538. }
  9539. }
  9540. $this->_query['select']=implode(', ',$columns);
  9541. }
  9542. if($option!='')
  9543. $this->_query['select']=$option.' '.$this->_query['select'];
  9544. return $this;
  9545. }
  9546. public function getSelect()
  9547. {
  9548. return isset($this->_query['select']) ? $this->_query['select'] : '';
  9549. }
  9550. public function setSelect($value)
  9551. {
  9552. $this->select($value);
  9553. }
  9554. public function selectDistinct($columns='*')
  9555. {
  9556. $this->_query['distinct']=true;
  9557. return $this->select($columns);
  9558. }
  9559. public function getDistinct()
  9560. {
  9561. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  9562. }
  9563. public function setDistinct($value)
  9564. {
  9565. $this->_query['distinct']=$value;
  9566. }
  9567. public function from($tables)
  9568. {
  9569. if(is_string($tables) && strpos($tables,'(')!==false)
  9570. $this->_query['from']=$tables;
  9571. else
  9572. {
  9573. if(!is_array($tables))
  9574. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  9575. foreach($tables as $i=>$table)
  9576. {
  9577. if(strpos($table,'(')===false)
  9578. {
  9579. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9580. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9581. else
  9582. $tables[$i]=$this->_connection->quoteTableName($table);
  9583. }
  9584. }
  9585. $this->_query['from']=implode(', ',$tables);
  9586. }
  9587. return $this;
  9588. }
  9589. public function getFrom()
  9590. {
  9591. return isset($this->_query['from']) ? $this->_query['from'] : '';
  9592. }
  9593. public function setFrom($value)
  9594. {
  9595. $this->from($value);
  9596. }
  9597. public function where($conditions, $params=array())
  9598. {
  9599. $this->_query['where']=$this->processConditions($conditions);
  9600. foreach($params as $name=>$value)
  9601. $this->params[$name]=$value;
  9602. return $this;
  9603. }
  9604. public function andWhere($conditions,$params=array())
  9605. {
  9606. if(isset($this->_query['where']))
  9607. $this->_query['where']=$this->processConditions(array('AND',$this->_query['where'],$conditions));
  9608. else
  9609. $this->_query['where']=$this->processConditions($conditions);
  9610. foreach($params as $name=>$value)
  9611. $this->params[$name]=$value;
  9612. return $this;
  9613. }
  9614. public function orWhere($conditions,$params=array())
  9615. {
  9616. if(isset($this->_query['where']))
  9617. $this->_query['where']=$this->processConditions(array('OR',$this->_query['where'],$conditions));
  9618. else
  9619. $this->_query['where']=$this->processConditions($conditions);
  9620. foreach($params as $name=>$value)
  9621. $this->params[$name]=$value;
  9622. return $this;
  9623. }
  9624. public function getWhere()
  9625. {
  9626. return isset($this->_query['where']) ? $this->_query['where'] : '';
  9627. }
  9628. public function setWhere($value)
  9629. {
  9630. $this->where($value);
  9631. }
  9632. public function join($table, $conditions, $params=array())
  9633. {
  9634. return $this->joinInternal('join', $table, $conditions, $params);
  9635. }
  9636. public function getJoin()
  9637. {
  9638. return isset($this->_query['join']) ? $this->_query['join'] : '';
  9639. }
  9640. public function setJoin($value)
  9641. {
  9642. $this->_query['join']=$value;
  9643. }
  9644. public function leftJoin($table, $conditions, $params=array())
  9645. {
  9646. return $this->joinInternal('left join', $table, $conditions, $params);
  9647. }
  9648. public function rightJoin($table, $conditions, $params=array())
  9649. {
  9650. return $this->joinInternal('right join', $table, $conditions, $params);
  9651. }
  9652. public function crossJoin($table)
  9653. {
  9654. return $this->joinInternal('cross join', $table);
  9655. }
  9656. public function naturalJoin($table)
  9657. {
  9658. return $this->joinInternal('natural join', $table);
  9659. }
  9660. public function naturalLeftJoin($table)
  9661. {
  9662. return $this->joinInternal('natural left join', $table);
  9663. }
  9664. public function naturalRightJoin($table)
  9665. {
  9666. return $this->joinInternal('natural right join', $table);
  9667. }
  9668. public function group($columns)
  9669. {
  9670. if(is_string($columns) && strpos($columns,'(')!==false)
  9671. $this->_query['group']=$columns;
  9672. else
  9673. {
  9674. if(!is_array($columns))
  9675. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9676. foreach($columns as $i=>$column)
  9677. {
  9678. if(is_object($column))
  9679. $columns[$i]=(string)$column;
  9680. elseif(strpos($column,'(')===false)
  9681. $columns[$i]=$this->_connection->quoteColumnName($column);
  9682. }
  9683. $this->_query['group']=implode(', ',$columns);
  9684. }
  9685. return $this;
  9686. }
  9687. public function getGroup()
  9688. {
  9689. return isset($this->_query['group']) ? $this->_query['group'] : '';
  9690. }
  9691. public function setGroup($value)
  9692. {
  9693. $this->group($value);
  9694. }
  9695. public function having($conditions, $params=array())
  9696. {
  9697. $this->_query['having']=$this->processConditions($conditions);
  9698. foreach($params as $name=>$value)
  9699. $this->params[$name]=$value;
  9700. return $this;
  9701. }
  9702. public function getHaving()
  9703. {
  9704. return isset($this->_query['having']) ? $this->_query['having'] : '';
  9705. }
  9706. public function setHaving($value)
  9707. {
  9708. $this->having($value);
  9709. }
  9710. public function order($columns)
  9711. {
  9712. if(is_string($columns) && strpos($columns,'(')!==false)
  9713. $this->_query['order']=$columns;
  9714. else
  9715. {
  9716. if(!is_array($columns))
  9717. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9718. foreach($columns as $i=>$column)
  9719. {
  9720. if(is_object($column))
  9721. $columns[$i]=(string)$column;
  9722. elseif(strpos($column,'(')===false)
  9723. {
  9724. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  9725. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  9726. else
  9727. $columns[$i]=$this->_connection->quoteColumnName($column);
  9728. }
  9729. }
  9730. $this->_query['order']=implode(', ',$columns);
  9731. }
  9732. return $this;
  9733. }
  9734. public function getOrder()
  9735. {
  9736. return isset($this->_query['order']) ? $this->_query['order'] : '';
  9737. }
  9738. public function setOrder($value)
  9739. {
  9740. $this->order($value);
  9741. }
  9742. public function limit($limit, $offset=null)
  9743. {
  9744. $this->_query['limit']=(int)$limit;
  9745. if($offset!==null)
  9746. $this->offset($offset);
  9747. return $this;
  9748. }
  9749. public function getLimit()
  9750. {
  9751. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  9752. }
  9753. public function setLimit($value)
  9754. {
  9755. $this->limit($value);
  9756. }
  9757. public function offset($offset)
  9758. {
  9759. $this->_query['offset']=(int)$offset;
  9760. return $this;
  9761. }
  9762. public function getOffset()
  9763. {
  9764. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  9765. }
  9766. public function setOffset($value)
  9767. {
  9768. $this->offset($value);
  9769. }
  9770. public function union($sql)
  9771. {
  9772. if(isset($this->_query['union']) && is_string($this->_query['union']))
  9773. $this->_query['union']=array($this->_query['union']);
  9774. $this->_query['union'][]=$sql;
  9775. return $this;
  9776. }
  9777. public function getUnion()
  9778. {
  9779. return isset($this->_query['union']) ? $this->_query['union'] : '';
  9780. }
  9781. public function setUnion($value)
  9782. {
  9783. $this->_query['union']=$value;
  9784. }
  9785. public function insert($table, $columns)
  9786. {
  9787. $params=array();
  9788. $names=array();
  9789. $placeholders=array();
  9790. foreach($columns as $name=>$value)
  9791. {
  9792. $names[]=$this->_connection->quoteColumnName($name);
  9793. if($value instanceof CDbExpression)
  9794. {
  9795. $placeholders[] = $value->expression;
  9796. foreach($value->params as $n => $v)
  9797. $params[$n] = $v;
  9798. }
  9799. else
  9800. {
  9801. $placeholders[] = ':' . $name;
  9802. $params[':' . $name] = $value;
  9803. }
  9804. }
  9805. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  9806. . ' (' . implode(', ',$names) . ') VALUES ('
  9807. . implode(', ', $placeholders) . ')';
  9808. return $this->setText($sql)->execute($params);
  9809. }
  9810. public function update($table, $columns, $conditions='', $params=array())
  9811. {
  9812. $lines=array();
  9813. foreach($columns as $name=>$value)
  9814. {
  9815. if($value instanceof CDbExpression)
  9816. {
  9817. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  9818. foreach($value->params as $n => $v)
  9819. $params[$n] = $v;
  9820. }
  9821. else
  9822. {
  9823. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  9824. $params[':' . $name]=$value;
  9825. }
  9826. }
  9827. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  9828. if(($where=$this->processConditions($conditions))!='')
  9829. $sql.=' WHERE '.$where;
  9830. return $this->setText($sql)->execute($params);
  9831. }
  9832. public function delete($table, $conditions='', $params=array())
  9833. {
  9834. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  9835. if(($where=$this->processConditions($conditions))!='')
  9836. $sql.=' WHERE '.$where;
  9837. return $this->setText($sql)->execute($params);
  9838. }
  9839. public function createTable($table, $columns, $options=null)
  9840. {
  9841. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  9842. }
  9843. public function renameTable($table, $newName)
  9844. {
  9845. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  9846. }
  9847. public function dropTable($table)
  9848. {
  9849. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  9850. }
  9851. public function truncateTable($table)
  9852. {
  9853. $schema=$this->getConnection()->getSchema();
  9854. $n=$this->setText($schema->truncateTable($table))->execute();
  9855. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  9856. $schema->resetSequence($schema->getTable($table));
  9857. return $n;
  9858. }
  9859. public function addColumn($table, $column, $type)
  9860. {
  9861. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  9862. }
  9863. public function dropColumn($table, $column)
  9864. {
  9865. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  9866. }
  9867. public function renameColumn($table, $name, $newName)
  9868. {
  9869. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  9870. }
  9871. public function alterColumn($table, $column, $type)
  9872. {
  9873. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  9874. }
  9875. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9876. {
  9877. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  9878. }
  9879. public function dropForeignKey($name, $table)
  9880. {
  9881. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  9882. }
  9883. public function createIndex($name, $table, $columns, $unique=false)
  9884. {
  9885. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $columns, $unique))->execute();
  9886. }
  9887. public function dropIndex($name, $table)
  9888. {
  9889. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  9890. }
  9891. private function processConditions($conditions)
  9892. {
  9893. if(!is_array($conditions))
  9894. return $conditions;
  9895. elseif($conditions===array())
  9896. return '';
  9897. $n=count($conditions);
  9898. $operator=strtoupper($conditions[0]);
  9899. if($operator==='OR' || $operator==='AND')
  9900. {
  9901. $parts=array();
  9902. for($i=1;$i<$n;++$i)
  9903. {
  9904. $condition=$this->processConditions($conditions[$i]);
  9905. if($condition!=='')
  9906. $parts[]='('.$condition.')';
  9907. }
  9908. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  9909. }
  9910. if(!isset($conditions[1],$conditions[2]))
  9911. return '';
  9912. $column=$conditions[1];
  9913. if(strpos($column,'(')===false)
  9914. $column=$this->_connection->quoteColumnName($column);
  9915. $values=$conditions[2];
  9916. if(!is_array($values))
  9917. $values=array($values);
  9918. if($operator==='IN' || $operator==='NOT IN')
  9919. {
  9920. if($values===array())
  9921. return $operator==='IN' ? '0=1' : '';
  9922. foreach($values as $i=>$value)
  9923. {
  9924. if(is_string($value))
  9925. $values[$i]=$this->_connection->quoteValue($value);
  9926. else
  9927. $values[$i]=(string)$value;
  9928. }
  9929. return $column.' '.$operator.' ('.implode(', ',$values).')';
  9930. }
  9931. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  9932. {
  9933. if($values===array())
  9934. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  9935. if($operator==='LIKE' || $operator==='NOT LIKE')
  9936. $andor=' AND ';
  9937. else
  9938. {
  9939. $andor=' OR ';
  9940. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  9941. }
  9942. $expressions=array();
  9943. foreach($values as $value)
  9944. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  9945. return implode($andor,$expressions);
  9946. }
  9947. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  9948. }
  9949. private function joinInternal($type, $table, $conditions='', $params=array())
  9950. {
  9951. if(strpos($table,'(')===false)
  9952. {
  9953. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9954. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9955. else
  9956. $table=$this->_connection->quoteTableName($table);
  9957. }
  9958. $conditions=$this->processConditions($conditions);
  9959. if($conditions!='')
  9960. $conditions=' ON '.$conditions;
  9961. if(isset($this->_query['join']) && is_string($this->_query['join']))
  9962. $this->_query['join']=array($this->_query['join']);
  9963. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  9964. foreach($params as $name=>$value)
  9965. $this->params[$name]=$value;
  9966. return $this;
  9967. }
  9968. public function addPrimaryKey($name,$table,$columns)
  9969. {
  9970. return $this->setText($this->getConnection()->getSchema()->addPrimaryKey($name,$table,$columns))->execute();
  9971. }
  9972. public function dropPrimaryKey($name,$table)
  9973. {
  9974. return $this->setText($this->getConnection()->getSchema()->dropPrimaryKey($name,$table))->execute();
  9975. }
  9976. }
  9977. class CDbColumnSchema extends CComponent
  9978. {
  9979. public $name;
  9980. public $rawName;
  9981. public $allowNull;
  9982. public $dbType;
  9983. public $type;
  9984. public $defaultValue;
  9985. public $size;
  9986. public $precision;
  9987. public $scale;
  9988. public $isPrimaryKey;
  9989. public $isForeignKey;
  9990. public $autoIncrement=false;
  9991. public $comment='';
  9992. public function init($dbType, $defaultValue)
  9993. {
  9994. $this->dbType=$dbType;
  9995. $this->extractType($dbType);
  9996. $this->extractLimit($dbType);
  9997. if($defaultValue!==null)
  9998. $this->extractDefault($defaultValue);
  9999. }
  10000. protected function extractType($dbType)
  10001. {
  10002. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  10003. $this->type='integer';
  10004. elseif(stripos($dbType,'bool')!==false)
  10005. $this->type='boolean';
  10006. elseif(preg_match('/(real|floa|doub)/i',$dbType))
  10007. $this->type='double';
  10008. else
  10009. $this->type='string';
  10010. }
  10011. protected function extractLimit($dbType)
  10012. {
  10013. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  10014. {
  10015. $values=explode(',',$matches[1]);
  10016. $this->size=$this->precision=(int)$values[0];
  10017. if(isset($values[1]))
  10018. $this->scale=(int)$values[1];
  10019. }
  10020. }
  10021. protected function extractDefault($defaultValue)
  10022. {
  10023. $this->defaultValue=$this->typecast($defaultValue);
  10024. }
  10025. public function typecast($value)
  10026. {
  10027. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  10028. return $value;
  10029. if($value==='' && $this->allowNull)
  10030. return $this->type==='string' ? '' : null;
  10031. switch($this->type)
  10032. {
  10033. case 'string': return (string)$value;
  10034. case 'integer': return (integer)$value;
  10035. case 'boolean': return (boolean)$value;
  10036. case 'double':
  10037. default: return $value;
  10038. }
  10039. }
  10040. }
  10041. class CSqliteColumnSchema extends CDbColumnSchema
  10042. {
  10043. protected function extractDefault($defaultValue)
  10044. {
  10045. if($this->dbType==='timestamp' && $defaultValue==='CURRENT_TIMESTAMP')
  10046. $this->defaultValue=null;
  10047. else
  10048. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  10049. if($this->type==='string' && $this->defaultValue!==null) // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  10050. $this->defaultValue=trim($this->defaultValue,"'\"");
  10051. }
  10052. }
  10053. abstract class CValidator extends CComponent
  10054. {
  10055. public static $builtInValidators=array(
  10056. 'required'=>'CRequiredValidator',
  10057. 'filter'=>'CFilterValidator',
  10058. 'match'=>'CRegularExpressionValidator',
  10059. 'email'=>'CEmailValidator',
  10060. 'url'=>'CUrlValidator',
  10061. 'unique'=>'CUniqueValidator',
  10062. 'compare'=>'CCompareValidator',
  10063. 'length'=>'CStringValidator',
  10064. 'in'=>'CRangeValidator',
  10065. 'numerical'=>'CNumberValidator',
  10066. 'captcha'=>'CCaptchaValidator',
  10067. 'type'=>'CTypeValidator',
  10068. 'file'=>'CFileValidator',
  10069. 'default'=>'CDefaultValueValidator',
  10070. 'exist'=>'CExistValidator',
  10071. 'boolean'=>'CBooleanValidator',
  10072. 'safe'=>'CSafeValidator',
  10073. 'unsafe'=>'CUnsafeValidator',
  10074. 'date'=>'CDateValidator',
  10075. );
  10076. public $attributes;
  10077. public $message;
  10078. public $skipOnError=false;
  10079. public $on;
  10080. public $except;
  10081. public $safe=true;
  10082. public $enableClientValidation=true;
  10083. abstract protected function validateAttribute($object,$attribute);
  10084. public static function createValidator($name,$object,$attributes,$params=array())
  10085. {
  10086. if(is_string($attributes))
  10087. $attributes=preg_split('/\s*,\s*/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  10088. if(isset($params['on']))
  10089. {
  10090. if(is_array($params['on']))
  10091. $on=$params['on'];
  10092. else
  10093. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  10094. }
  10095. else
  10096. $on=array();
  10097. if(isset($params['except']))
  10098. {
  10099. if(is_array($params['except']))
  10100. $except=$params['except'];
  10101. else
  10102. $except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
  10103. }
  10104. else
  10105. $except=array();
  10106. if(method_exists($object,$name))
  10107. {
  10108. $validator=new CInlineValidator;
  10109. $validator->attributes=$attributes;
  10110. $validator->method=$name;
  10111. if(isset($params['clientValidate']))
  10112. {
  10113. $validator->clientValidate=$params['clientValidate'];
  10114. unset($params['clientValidate']);
  10115. }
  10116. $validator->params=$params;
  10117. if(isset($params['skipOnError']))
  10118. $validator->skipOnError=$params['skipOnError'];
  10119. }
  10120. else
  10121. {
  10122. $params['attributes']=$attributes;
  10123. if(isset(self::$builtInValidators[$name]))
  10124. $className=Yii::import(self::$builtInValidators[$name],true);
  10125. else
  10126. $className=Yii::import($name,true);
  10127. $validator=new $className;
  10128. foreach($params as $name=>$value)
  10129. $validator->$name=$value;
  10130. }
  10131. $validator->on=empty($on) ? array() : array_combine($on,$on);
  10132. $validator->except=empty($except) ? array() : array_combine($except,$except);
  10133. return $validator;
  10134. }
  10135. public function validate($object,$attributes=null)
  10136. {
  10137. if(is_array($attributes))
  10138. $attributes=array_intersect($this->attributes,$attributes);
  10139. else
  10140. $attributes=$this->attributes;
  10141. foreach($attributes as $attribute)
  10142. {
  10143. if(!$this->skipOnError || !$object->hasErrors($attribute))
  10144. $this->validateAttribute($object,$attribute);
  10145. }
  10146. }
  10147. public function clientValidateAttribute($object,$attribute)
  10148. {
  10149. }
  10150. public function applyTo($scenario)
  10151. {
  10152. if(isset($this->except[$scenario]))
  10153. return false;
  10154. return empty($this->on) || isset($this->on[$scenario]);
  10155. }
  10156. protected function addError($object,$attribute,$message,$params=array())
  10157. {
  10158. $params['{attribute}']=$object->getAttributeLabel($attribute);
  10159. $object->addError($attribute,strtr($message,$params));
  10160. }
  10161. protected function isEmpty($value,$trim=false)
  10162. {
  10163. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  10164. }
  10165. }
  10166. class CStringValidator extends CValidator
  10167. {
  10168. public $max;
  10169. public $min;
  10170. public $is;
  10171. public $tooShort;
  10172. public $tooLong;
  10173. public $allowEmpty=true;
  10174. public $encoding;
  10175. protected function validateAttribute($object,$attribute)
  10176. {
  10177. $value=$object->$attribute;
  10178. if($this->allowEmpty && $this->isEmpty($value))
  10179. return;
  10180. if(is_array($value))
  10181. {
  10182. // https://github.com/yiisoft/yii/issues/1955
  10183. $this->addError($object,$attribute,Yii::t('yii','{attribute} is invalid.'));
  10184. return;
  10185. }
  10186. if(function_exists('mb_strlen') && $this->encoding!==false)
  10187. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  10188. else
  10189. $length=strlen($value);
  10190. if($this->min!==null && $length<$this->min)
  10191. {
  10192. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  10193. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  10194. }
  10195. if($this->max!==null && $length>$this->max)
  10196. {
  10197. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  10198. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  10199. }
  10200. if($this->is!==null && $length!==$this->is)
  10201. {
  10202. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  10203. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  10204. }
  10205. }
  10206. public function clientValidateAttribute($object,$attribute)
  10207. {
  10208. $label=$object->getAttributeLabel($attribute);
  10209. if(($message=$this->message)===null)
  10210. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  10211. $message=strtr($message, array(
  10212. '{attribute}'=>$label,
  10213. '{length}'=>$this->is,
  10214. ));
  10215. if(($tooShort=$this->tooShort)===null)
  10216. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  10217. $tooShort=strtr($tooShort, array(
  10218. '{attribute}'=>$label,
  10219. '{min}'=>$this->min,
  10220. ));
  10221. if(($tooLong=$this->tooLong)===null)
  10222. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  10223. $tooLong=strtr($tooLong, array(
  10224. '{attribute}'=>$label,
  10225. '{max}'=>$this->max,
  10226. ));
  10227. $js='';
  10228. if($this->min!==null)
  10229. {
  10230. $js.="
  10231. if(value.length<{$this->min}) {
  10232. messages.push(".CJSON::encode($tooShort).");
  10233. }
  10234. ";
  10235. }
  10236. if($this->max!==null)
  10237. {
  10238. $js.="
  10239. if(value.length>{$this->max}) {
  10240. messages.push(".CJSON::encode($tooLong).");
  10241. }
  10242. ";
  10243. }
  10244. if($this->is!==null)
  10245. {
  10246. $js.="
  10247. if(value.length!={$this->is}) {
  10248. messages.push(".CJSON::encode($message).");
  10249. }
  10250. ";
  10251. }
  10252. if($this->allowEmpty)
  10253. {
  10254. $js="
  10255. if(jQuery.trim(value)!='') {
  10256. $js
  10257. }
  10258. ";
  10259. }
  10260. return $js;
  10261. }
  10262. }
  10263. class CRequiredValidator extends CValidator
  10264. {
  10265. public $requiredValue;
  10266. public $strict=false;
  10267. public $trim=true;
  10268. protected function validateAttribute($object,$attribute)
  10269. {
  10270. $value=$object->$attribute;
  10271. if($this->requiredValue!==null)
  10272. {
  10273. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  10274. {
  10275. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  10276. array('{value}'=>$this->requiredValue));
  10277. $this->addError($object,$attribute,$message);
  10278. }
  10279. }
  10280. elseif($this->isEmpty($value,$this->trim))
  10281. {
  10282. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  10283. $this->addError($object,$attribute,$message);
  10284. }
  10285. }
  10286. public function clientValidateAttribute($object,$attribute)
  10287. {
  10288. $message=$this->message;
  10289. if($this->requiredValue!==null)
  10290. {
  10291. if($message===null)
  10292. $message=Yii::t('yii','{attribute} must be {value}.');
  10293. $message=strtr($message, array(
  10294. '{value}'=>$this->requiredValue,
  10295. '{attribute}'=>$object->getAttributeLabel($attribute),
  10296. ));
  10297. return "
  10298. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  10299. messages.push(".CJSON::encode($message).");
  10300. }
  10301. ";
  10302. }
  10303. else
  10304. {
  10305. if($message===null)
  10306. $message=Yii::t('yii','{attribute} cannot be blank.');
  10307. $message=strtr($message, array(
  10308. '{attribute}'=>$object->getAttributeLabel($attribute),
  10309. ));
  10310. if($this->trim)
  10311. $emptyCondition = "jQuery.trim(value)==''";
  10312. else
  10313. $emptyCondition = "value==''";
  10314. return "
  10315. if({$emptyCondition}) {
  10316. messages.push(".CJSON::encode($message).");
  10317. }
  10318. ";
  10319. }
  10320. }
  10321. }
  10322. class CNumberValidator extends CValidator
  10323. {
  10324. public $integerOnly=false;
  10325. public $allowEmpty=true;
  10326. public $max;
  10327. public $min;
  10328. public $tooBig;
  10329. public $tooSmall;
  10330. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  10331. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  10332. protected function validateAttribute($object,$attribute)
  10333. {
  10334. $value=$object->$attribute;
  10335. if($this->allowEmpty && $this->isEmpty($value))
  10336. return;
  10337. if(!is_numeric($value))
  10338. {
  10339. // https://github.com/yiisoft/yii/issues/1955
  10340. // https://github.com/yiisoft/yii/issues/1669
  10341. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  10342. $this->addError($object,$attribute,$message);
  10343. return;
  10344. }
  10345. if($this->integerOnly)
  10346. {
  10347. if(!preg_match($this->integerPattern,"$value"))
  10348. {
  10349. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  10350. $this->addError($object,$attribute,$message);
  10351. }
  10352. }
  10353. else
  10354. {
  10355. if(!preg_match($this->numberPattern,"$value"))
  10356. {
  10357. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  10358. $this->addError($object,$attribute,$message);
  10359. }
  10360. }
  10361. if($this->min!==null && $value<$this->min)
  10362. {
  10363. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  10364. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  10365. }
  10366. if($this->max!==null && $value>$this->max)
  10367. {
  10368. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  10369. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  10370. }
  10371. }
  10372. public function clientValidateAttribute($object,$attribute)
  10373. {
  10374. $label=$object->getAttributeLabel($attribute);
  10375. if(($message=$this->message)===null)
  10376. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  10377. $message=strtr($message, array(
  10378. '{attribute}'=>$label,
  10379. ));
  10380. if(($tooBig=$this->tooBig)===null)
  10381. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  10382. $tooBig=strtr($tooBig, array(
  10383. '{attribute}'=>$label,
  10384. '{max}'=>$this->max,
  10385. ));
  10386. if(($tooSmall=$this->tooSmall)===null)
  10387. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  10388. $tooSmall=strtr($tooSmall, array(
  10389. '{attribute}'=>$label,
  10390. '{min}'=>$this->min,
  10391. ));
  10392. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  10393. $js="
  10394. if(!value.match($pattern)) {
  10395. messages.push(".CJSON::encode($message).");
  10396. }
  10397. ";
  10398. if($this->min!==null)
  10399. {
  10400. $js.="
  10401. if(value<{$this->min}) {
  10402. messages.push(".CJSON::encode($tooSmall).");
  10403. }
  10404. ";
  10405. }
  10406. if($this->max!==null)
  10407. {
  10408. $js.="
  10409. if(value>{$this->max}) {
  10410. messages.push(".CJSON::encode($tooBig).");
  10411. }
  10412. ";
  10413. }
  10414. if($this->allowEmpty)
  10415. {
  10416. $js="
  10417. if(jQuery.trim(value)!='') {
  10418. $js
  10419. }
  10420. ";
  10421. }
  10422. return $js;
  10423. }
  10424. }
  10425. class CListIterator implements Iterator
  10426. {
  10427. private $_d;
  10428. private $_i;
  10429. private $_c;
  10430. public function __construct(&$data)
  10431. {
  10432. $this->_d=&$data;
  10433. $this->_i=0;
  10434. $this->_c=count($this->_d);
  10435. }
  10436. public function rewind()
  10437. {
  10438. $this->_i=0;
  10439. }
  10440. public function key()
  10441. {
  10442. return $this->_i;
  10443. }
  10444. public function current()
  10445. {
  10446. return $this->_d[$this->_i];
  10447. }
  10448. public function next()
  10449. {
  10450. $this->_i++;
  10451. }
  10452. public function valid()
  10453. {
  10454. return $this->_i<$this->_c;
  10455. }
  10456. }
  10457. interface IApplicationComponent
  10458. {
  10459. public function init();
  10460. public function getIsInitialized();
  10461. }
  10462. interface ICache
  10463. {
  10464. public function get($id);
  10465. public function mget($ids);
  10466. public function set($id,$value,$expire=0,$dependency=null);
  10467. public function add($id,$value,$expire=0,$dependency=null);
  10468. public function delete($id);
  10469. public function flush();
  10470. }
  10471. interface ICacheDependency
  10472. {
  10473. public function evaluateDependency();
  10474. public function getHasChanged();
  10475. }
  10476. interface IStatePersister
  10477. {
  10478. public function load();
  10479. public function save($state);
  10480. }
  10481. interface IFilter
  10482. {
  10483. public function filter($filterChain);
  10484. }
  10485. interface IAction
  10486. {
  10487. public function getId();
  10488. public function getController();
  10489. }
  10490. interface IWebServiceProvider
  10491. {
  10492. public function beforeWebMethod($service);
  10493. public function afterWebMethod($service);
  10494. }
  10495. interface IViewRenderer
  10496. {
  10497. public function renderFile($context,$file,$data,$return);
  10498. }
  10499. interface IUserIdentity
  10500. {
  10501. public function authenticate();
  10502. public function getIsAuthenticated();
  10503. public function getId();
  10504. public function getName();
  10505. public function getPersistentStates();
  10506. }
  10507. interface IWebUser
  10508. {
  10509. public function getId();
  10510. public function getName();
  10511. public function getIsGuest();
  10512. public function checkAccess($operation,$params=array());
  10513. public function loginRequired();
  10514. }
  10515. interface IAuthManager
  10516. {
  10517. public function checkAccess($itemName,$userId,$params=array());
  10518. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  10519. public function removeAuthItem($name);
  10520. public function getAuthItems($type=null,$userId=null);
  10521. public function getAuthItem($name);
  10522. public function saveAuthItem($item,$oldName=null);
  10523. public function addItemChild($itemName,$childName);
  10524. public function removeItemChild($itemName,$childName);
  10525. public function hasItemChild($itemName,$childName);
  10526. public function getItemChildren($itemName);
  10527. public function assign($itemName,$userId,$bizRule=null,$data=null);
  10528. public function revoke($itemName,$userId);
  10529. public function isAssigned($itemName,$userId);
  10530. public function getAuthAssignment($itemName,$userId);
  10531. public function getAuthAssignments($userId);
  10532. public function saveAuthAssignment($assignment);
  10533. public function clearAll();
  10534. public function clearAuthAssignments();
  10535. public function save();
  10536. public function executeBizRule($bizRule,$params,$data);
  10537. }
  10538. interface IBehavior
  10539. {
  10540. public function attach($component);
  10541. public function detach($component);
  10542. public function getEnabled();
  10543. public function setEnabled($value);
  10544. }
  10545. interface IWidgetFactory
  10546. {
  10547. public function createWidget($owner,$className,$properties=array());
  10548. }
  10549. interface IDataProvider
  10550. {
  10551. public function getId();
  10552. public function getItemCount($refresh=false);
  10553. public function getTotalItemCount($refresh=false);
  10554. public function getData($refresh=false);
  10555. public function getKeys($refresh=false);
  10556. public function getSort();
  10557. public function getPagination();
  10558. }
  10559. interface ILogFilter
  10560. {
  10561. public function filter(&$logs);
  10562. }
  10563. ?>