PageRenderTime 124ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 1ms

/framework/yiilite.php

https://github.com/trofimovm/fa2014
PHP | 10406 lines | 10329 code | 2 blank | 75 comment | 1129 complexity | 00631d0e0ee93645a598b971ee7e863c MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-2-Clause, LGPL-3.0, GPL-2.0, BSD-3-Clause, Apache-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.14';
  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. if($forceInclude && self::autoload($alias))
  147. self::$_imports[$alias]=$alias;
  148. return $alias;
  149. }
  150. $className=(string)substr($alias,$pos+1);
  151. $isClass=$className!=='*';
  152. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  153. return self::$_imports[$alias]=$className;
  154. if(($path=self::getPathOfAlias($alias))!==false)
  155. {
  156. if($isClass)
  157. {
  158. if($forceInclude)
  159. {
  160. if(is_file($path.'.php'))
  161. require($path.'.php');
  162. else
  163. 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)));
  164. self::$_imports[$alias]=$className;
  165. }
  166. else
  167. self::$classMap[$className]=$path.'.php';
  168. return $className;
  169. }
  170. else // a directory
  171. {
  172. if(self::$_includePaths===null)
  173. {
  174. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  175. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  176. unset(self::$_includePaths[$pos]);
  177. }
  178. array_unshift(self::$_includePaths,$path);
  179. if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  180. self::$enableIncludePath=false;
  181. return self::$_imports[$alias]=$path;
  182. }
  183. }
  184. else
  185. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  186. array('{alias}'=>$alias)));
  187. }
  188. public static function getPathOfAlias($alias)
  189. {
  190. if(isset(self::$_aliases[$alias]))
  191. return self::$_aliases[$alias];
  192. elseif(($pos=strpos($alias,'.'))!==false)
  193. {
  194. $rootAlias=substr($alias,0,$pos);
  195. if(isset(self::$_aliases[$rootAlias]))
  196. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  197. elseif(self::$_app instanceof CWebApplication)
  198. {
  199. if(self::$_app->findModule($rootAlias)!==null)
  200. return self::getPathOfAlias($alias);
  201. }
  202. }
  203. return false;
  204. }
  205. public static function setPathOfAlias($alias,$path)
  206. {
  207. if(empty($path))
  208. unset(self::$_aliases[$alias]);
  209. else
  210. self::$_aliases[$alias]=rtrim($path,'\\/');
  211. }
  212. public static function autoload($className)
  213. {
  214. // use include so that the error PHP file may appear
  215. if(isset(self::$classMap[$className]))
  216. include(self::$classMap[$className]);
  217. elseif(isset(self::$_coreClasses[$className]))
  218. include(YII_PATH.self::$_coreClasses[$className]);
  219. else
  220. {
  221. // include class file relying on include_path
  222. if(strpos($className,'\\')===false) // class without namespace
  223. {
  224. if(self::$enableIncludePath===false)
  225. {
  226. foreach(self::$_includePaths as $path)
  227. {
  228. $classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
  229. if(is_file($classFile))
  230. {
  231. include($classFile);
  232. if(YII_DEBUG && basename(realpath($classFile))!==$className.'.php')
  233. throw new CException(Yii::t('yii','Class name "{class}" does not match class file "{file}".', array(
  234. '{class}'=>$className,
  235. '{file}'=>$classFile,
  236. )));
  237. break;
  238. }
  239. }
  240. }
  241. else
  242. include($className.'.php');
  243. }
  244. else // class name with namespace in PHP 5.3
  245. {
  246. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  247. if(($path=self::getPathOfAlias($namespace))!==false)
  248. include($path.'.php');
  249. else
  250. return false;
  251. }
  252. return class_exists($className,false) || interface_exists($className,false);
  253. }
  254. return true;
  255. }
  256. public static function trace($msg,$category='application')
  257. {
  258. if(YII_DEBUG)
  259. self::log($msg,CLogger::LEVEL_TRACE,$category);
  260. }
  261. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  262. {
  263. if(self::$_logger===null)
  264. self::$_logger=new CLogger;
  265. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  266. {
  267. $traces=debug_backtrace();
  268. $count=0;
  269. foreach($traces as $trace)
  270. {
  271. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  272. {
  273. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  274. if(++$count>=YII_TRACE_LEVEL)
  275. break;
  276. }
  277. }
  278. }
  279. self::$_logger->log($msg,$level,$category);
  280. }
  281. public static function beginProfile($token,$category='application')
  282. {
  283. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  284. }
  285. public static function endProfile($token,$category='application')
  286. {
  287. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  288. }
  289. public static function getLogger()
  290. {
  291. if(self::$_logger!==null)
  292. return self::$_logger;
  293. else
  294. return self::$_logger=new CLogger;
  295. }
  296. public static function setLogger($logger)
  297. {
  298. self::$_logger=$logger;
  299. }
  300. public static function powered()
  301. {
  302. return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
  303. }
  304. public static function t($category,$message,$params=array(),$source=null,$language=null)
  305. {
  306. if(self::$_app!==null)
  307. {
  308. if($source===null)
  309. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  310. if(($source=self::$_app->getComponent($source))!==null)
  311. $message=$source->translate($category,$message,$language);
  312. }
  313. if($params===array())
  314. return $message;
  315. if(!is_array($params))
  316. $params=array($params);
  317. if(isset($params[0])) // number choice
  318. {
  319. if(strpos($message,'|')!==false)
  320. {
  321. if(strpos($message,'#')===false)
  322. {
  323. $chunks=explode('|',$message);
  324. $expressions=self::$_app->getLocale($language)->getPluralRules();
  325. if($n=min(count($chunks),count($expressions)))
  326. {
  327. for($i=0;$i<$n;$i++)
  328. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  329. $message=implode('|',$chunks);
  330. }
  331. }
  332. $message=CChoiceFormat::format($message,$params[0]);
  333. }
  334. if(!isset($params['{n}']))
  335. $params['{n}']=$params[0];
  336. unset($params[0]);
  337. }
  338. return $params!==array() ? strtr($message,$params) : $message;
  339. }
  340. public static function registerAutoloader($callback, $append=false)
  341. {
  342. if($append)
  343. {
  344. self::$enableIncludePath=false;
  345. spl_autoload_register($callback);
  346. }
  347. else
  348. {
  349. spl_autoload_unregister(array('YiiBase','autoload'));
  350. spl_autoload_register($callback);
  351. spl_autoload_register(array('YiiBase','autoload'));
  352. }
  353. }
  354. private static $_coreClasses=array(
  355. 'CApplication' => '/base/CApplication.php',
  356. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  357. 'CBehavior' => '/base/CBehavior.php',
  358. 'CComponent' => '/base/CComponent.php',
  359. 'CErrorEvent' => '/base/CErrorEvent.php',
  360. 'CErrorHandler' => '/base/CErrorHandler.php',
  361. 'CException' => '/base/CException.php',
  362. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  363. 'CHttpException' => '/base/CHttpException.php',
  364. 'CModel' => '/base/CModel.php',
  365. 'CModelBehavior' => '/base/CModelBehavior.php',
  366. 'CModelEvent' => '/base/CModelEvent.php',
  367. 'CModule' => '/base/CModule.php',
  368. 'CSecurityManager' => '/base/CSecurityManager.php',
  369. 'CStatePersister' => '/base/CStatePersister.php',
  370. 'CApcCache' => '/caching/CApcCache.php',
  371. 'CCache' => '/caching/CCache.php',
  372. 'CDbCache' => '/caching/CDbCache.php',
  373. 'CDummyCache' => '/caching/CDummyCache.php',
  374. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  375. 'CFileCache' => '/caching/CFileCache.php',
  376. 'CMemCache' => '/caching/CMemCache.php',
  377. 'CRedisCache' => '/caching/CRedisCache.php',
  378. 'CWinCache' => '/caching/CWinCache.php',
  379. 'CXCache' => '/caching/CXCache.php',
  380. 'CZendDataCache' => '/caching/CZendDataCache.php',
  381. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  382. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  383. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  384. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  385. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  386. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  387. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  388. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  389. 'CConfiguration' => '/collections/CConfiguration.php',
  390. 'CList' => '/collections/CList.php',
  391. 'CListIterator' => '/collections/CListIterator.php',
  392. 'CMap' => '/collections/CMap.php',
  393. 'CMapIterator' => '/collections/CMapIterator.php',
  394. 'CQueue' => '/collections/CQueue.php',
  395. 'CQueueIterator' => '/collections/CQueueIterator.php',
  396. 'CStack' => '/collections/CStack.php',
  397. 'CStackIterator' => '/collections/CStackIterator.php',
  398. 'CTypedList' => '/collections/CTypedList.php',
  399. 'CTypedMap' => '/collections/CTypedMap.php',
  400. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  401. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  402. 'CConsoleCommandBehavior' => '/console/CConsoleCommandBehavior.php',
  403. 'CConsoleCommandEvent' => '/console/CConsoleCommandEvent.php',
  404. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  405. 'CHelpCommand' => '/console/CHelpCommand.php',
  406. 'CDbCommand' => '/db/CDbCommand.php',
  407. 'CDbConnection' => '/db/CDbConnection.php',
  408. 'CDbDataReader' => '/db/CDbDataReader.php',
  409. 'CDbException' => '/db/CDbException.php',
  410. 'CDbMigration' => '/db/CDbMigration.php',
  411. 'CDbTransaction' => '/db/CDbTransaction.php',
  412. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  413. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  414. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  415. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  416. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  417. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  418. 'CDbExpression' => '/db/schema/CDbExpression.php',
  419. 'CDbSchema' => '/db/schema/CDbSchema.php',
  420. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  421. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  422. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  423. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  424. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  425. 'CMssqlSqlsrvPdoAdapter' => '/db/schema/mssql/CMssqlSqlsrvPdoAdapter.php',
  426. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  427. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  428. 'CMysqlCommandBuilder' => '/db/schema/mysql/CMysqlCommandBuilder.php',
  429. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  430. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  431. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  432. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  433. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  434. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  435. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  436. 'CPgsqlCommandBuilder' => '/db/schema/pgsql/CPgsqlCommandBuilder.php',
  437. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  438. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  439. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  440. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  441. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  442. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  443. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  444. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  445. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  446. 'CLocale' => '/i18n/CLocale.php',
  447. 'CMessageSource' => '/i18n/CMessageSource.php',
  448. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  449. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  450. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  451. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  452. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  453. 'CChainedLogFilter' => '/logging/CChainedLogFilter.php',
  454. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  455. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  456. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  457. 'CLogFilter' => '/logging/CLogFilter.php',
  458. 'CLogRoute' => '/logging/CLogRoute.php',
  459. 'CLogRouter' => '/logging/CLogRouter.php',
  460. 'CLogger' => '/logging/CLogger.php',
  461. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  462. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  463. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  464. 'CFileHelper' => '/utils/CFileHelper.php',
  465. 'CFormatter' => '/utils/CFormatter.php',
  466. 'CLocalizedFormatter' => '/utils/CLocalizedFormatter.php',
  467. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  468. 'CPasswordHelper' => '/utils/CPasswordHelper.php',
  469. 'CPropertyValue' => '/utils/CPropertyValue.php',
  470. 'CTimestamp' => '/utils/CTimestamp.php',
  471. 'CVarDumper' => '/utils/CVarDumper.php',
  472. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  473. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  474. 'CCompareValidator' => '/validators/CCompareValidator.php',
  475. 'CDateValidator' => '/validators/CDateValidator.php',
  476. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  477. 'CEmailValidator' => '/validators/CEmailValidator.php',
  478. 'CExistValidator' => '/validators/CExistValidator.php',
  479. 'CFileValidator' => '/validators/CFileValidator.php',
  480. 'CFilterValidator' => '/validators/CFilterValidator.php',
  481. 'CInlineValidator' => '/validators/CInlineValidator.php',
  482. 'CNumberValidator' => '/validators/CNumberValidator.php',
  483. 'CRangeValidator' => '/validators/CRangeValidator.php',
  484. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  485. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  486. 'CSafeValidator' => '/validators/CSafeValidator.php',
  487. 'CStringValidator' => '/validators/CStringValidator.php',
  488. 'CTypeValidator' => '/validators/CTypeValidator.php',
  489. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  490. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  491. 'CUrlValidator' => '/validators/CUrlValidator.php',
  492. 'CValidator' => '/validators/CValidator.php',
  493. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  494. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  495. 'CAssetManager' => '/web/CAssetManager.php',
  496. 'CBaseController' => '/web/CBaseController.php',
  497. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  498. 'CClientScript' => '/web/CClientScript.php',
  499. 'CController' => '/web/CController.php',
  500. 'CDataProvider' => '/web/CDataProvider.php',
  501. 'CDataProviderIterator' => '/web/CDataProviderIterator.php',
  502. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  503. 'CExtController' => '/web/CExtController.php',
  504. 'CFormModel' => '/web/CFormModel.php',
  505. 'CHttpCookie' => '/web/CHttpCookie.php',
  506. 'CHttpRequest' => '/web/CHttpRequest.php',
  507. 'CHttpSession' => '/web/CHttpSession.php',
  508. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  509. 'COutputEvent' => '/web/COutputEvent.php',
  510. 'CPagination' => '/web/CPagination.php',
  511. 'CSort' => '/web/CSort.php',
  512. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  513. 'CTheme' => '/web/CTheme.php',
  514. 'CThemeManager' => '/web/CThemeManager.php',
  515. 'CUploadedFile' => '/web/CUploadedFile.php',
  516. 'CUrlManager' => '/web/CUrlManager.php',
  517. 'CWebApplication' => '/web/CWebApplication.php',
  518. 'CWebModule' => '/web/CWebModule.php',
  519. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  520. 'CAction' => '/web/actions/CAction.php',
  521. 'CInlineAction' => '/web/actions/CInlineAction.php',
  522. 'CViewAction' => '/web/actions/CViewAction.php',
  523. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  524. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  525. 'CAuthItem' => '/web/auth/CAuthItem.php',
  526. 'CAuthManager' => '/web/auth/CAuthManager.php',
  527. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  528. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  529. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  530. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  531. 'CWebUser' => '/web/auth/CWebUser.php',
  532. 'CFilter' => '/web/filters/CFilter.php',
  533. 'CFilterChain' => '/web/filters/CFilterChain.php',
  534. 'CHttpCacheFilter' => '/web/filters/CHttpCacheFilter.php',
  535. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  536. 'CForm' => '/web/form/CForm.php',
  537. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  538. 'CFormElement' => '/web/form/CFormElement.php',
  539. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  540. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  541. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  542. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  543. 'CHtml' => '/web/helpers/CHtml.php',
  544. 'CJSON' => '/web/helpers/CJSON.php',
  545. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  546. 'CJavaScriptExpression' => '/web/helpers/CJavaScriptExpression.php',
  547. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  548. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  549. 'CWebService' => '/web/services/CWebService.php',
  550. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  551. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  552. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  553. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  554. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  555. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  556. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  557. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  558. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  559. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  560. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  561. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  562. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  563. 'COutputCache' => '/web/widgets/COutputCache.php',
  564. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  565. 'CStarRating' => '/web/widgets/CStarRating.php',
  566. 'CTabView' => '/web/widgets/CTabView.php',
  567. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  568. 'CTreeView' => '/web/widgets/CTreeView.php',
  569. 'CWidget' => '/web/widgets/CWidget.php',
  570. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  571. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  572. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  573. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  574. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  575. );
  576. }
  577. spl_autoload_register(array('YiiBase','autoload'));
  578. class Yii extends YiiBase
  579. {
  580. }
  581. class CComponent
  582. {
  583. private $_e;
  584. private $_m;
  585. public function __get($name)
  586. {
  587. $getter='get'.$name;
  588. if(method_exists($this,$getter))
  589. return $this->$getter();
  590. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  591. {
  592. // duplicating getEventHandlers() here for performance
  593. $name=strtolower($name);
  594. if(!isset($this->_e[$name]))
  595. $this->_e[$name]=new CList;
  596. return $this->_e[$name];
  597. }
  598. elseif(isset($this->_m[$name]))
  599. return $this->_m[$name];
  600. elseif(is_array($this->_m))
  601. {
  602. foreach($this->_m as $object)
  603. {
  604. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  605. return $object->$name;
  606. }
  607. }
  608. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  609. array('{class}'=>get_class($this), '{property}'=>$name)));
  610. }
  611. public function __set($name,$value)
  612. {
  613. $setter='set'.$name;
  614. if(method_exists($this,$setter))
  615. return $this->$setter($value);
  616. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  617. {
  618. // duplicating getEventHandlers() here for performance
  619. $name=strtolower($name);
  620. if(!isset($this->_e[$name]))
  621. $this->_e[$name]=new CList;
  622. return $this->_e[$name]->add($value);
  623. }
  624. elseif(is_array($this->_m))
  625. {
  626. foreach($this->_m as $object)
  627. {
  628. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  629. return $object->$name=$value;
  630. }
  631. }
  632. if(method_exists($this,'get'.$name))
  633. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  634. array('{class}'=>get_class($this), '{property}'=>$name)));
  635. else
  636. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  637. array('{class}'=>get_class($this), '{property}'=>$name)));
  638. }
  639. public function __isset($name)
  640. {
  641. $getter='get'.$name;
  642. if(method_exists($this,$getter))
  643. return $this->$getter()!==null;
  644. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  645. {
  646. $name=strtolower($name);
  647. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  648. }
  649. elseif(is_array($this->_m))
  650. {
  651. if(isset($this->_m[$name]))
  652. return true;
  653. foreach($this->_m as $object)
  654. {
  655. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  656. return $object->$name!==null;
  657. }
  658. }
  659. return false;
  660. }
  661. public function __unset($name)
  662. {
  663. $setter='set'.$name;
  664. if(method_exists($this,$setter))
  665. $this->$setter(null);
  666. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  667. unset($this->_e[strtolower($name)]);
  668. elseif(is_array($this->_m))
  669. {
  670. if(isset($this->_m[$name]))
  671. $this->detachBehavior($name);
  672. else
  673. {
  674. foreach($this->_m as $object)
  675. {
  676. if($object->getEnabled())
  677. {
  678. if(property_exists($object,$name))
  679. return $object->$name=null;
  680. elseif($object->canSetProperty($name))
  681. return $object->$setter(null);
  682. }
  683. }
  684. }
  685. }
  686. elseif(method_exists($this,'get'.$name))
  687. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  688. array('{class}'=>get_class($this), '{property}'=>$name)));
  689. }
  690. public function __call($name,$parameters)
  691. {
  692. if($this->_m!==null)
  693. {
  694. foreach($this->_m as $object)
  695. {
  696. if($object->getEnabled() && method_exists($object,$name))
  697. return call_user_func_array(array($object,$name),$parameters);
  698. }
  699. }
  700. if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)
  701. return call_user_func_array($this->$name, $parameters);
  702. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  703. array('{class}'=>get_class($this), '{name}'=>$name)));
  704. }
  705. public function asa($behavior)
  706. {
  707. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  708. }
  709. public function attachBehaviors($behaviors)
  710. {
  711. foreach($behaviors as $name=>$behavior)
  712. $this->attachBehavior($name,$behavior);
  713. }
  714. public function detachBehaviors()
  715. {
  716. if($this->_m!==null)
  717. {
  718. foreach($this->_m as $name=>$behavior)
  719. $this->detachBehavior($name);
  720. $this->_m=null;
  721. }
  722. }
  723. public function attachBehavior($name,$behavior)
  724. {
  725. if(!($behavior instanceof IBehavior))
  726. $behavior=Yii::createComponent($behavior);
  727. $behavior->setEnabled(true);
  728. $behavior->attach($this);
  729. return $this->_m[$name]=$behavior;
  730. }
  731. public function detachBehavior($name)
  732. {
  733. if(isset($this->_m[$name]))
  734. {
  735. $this->_m[$name]->detach($this);
  736. $behavior=$this->_m[$name];
  737. unset($this->_m[$name]);
  738. return $behavior;
  739. }
  740. }
  741. public function enableBehaviors()
  742. {
  743. if($this->_m!==null)
  744. {
  745. foreach($this->_m as $behavior)
  746. $behavior->setEnabled(true);
  747. }
  748. }
  749. public function disableBehaviors()
  750. {
  751. if($this->_m!==null)
  752. {
  753. foreach($this->_m as $behavior)
  754. $behavior->setEnabled(false);
  755. }
  756. }
  757. public function enableBehavior($name)
  758. {
  759. if(isset($this->_m[$name]))
  760. $this->_m[$name]->setEnabled(true);
  761. }
  762. public function disableBehavior($name)
  763. {
  764. if(isset($this->_m[$name]))
  765. $this->_m[$name]->setEnabled(false);
  766. }
  767. public function hasProperty($name)
  768. {
  769. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  770. }
  771. public function canGetProperty($name)
  772. {
  773. return method_exists($this,'get'.$name);
  774. }
  775. public function canSetProperty($name)
  776. {
  777. return method_exists($this,'set'.$name);
  778. }
  779. public function hasEvent($name)
  780. {
  781. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  782. }
  783. public function hasEventHandler($name)
  784. {
  785. $name=strtolower($name);
  786. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  787. }
  788. public function getEventHandlers($name)
  789. {
  790. if($this->hasEvent($name))
  791. {
  792. $name=strtolower($name);
  793. if(!isset($this->_e[$name]))
  794. $this->_e[$name]=new CList;
  795. return $this->_e[$name];
  796. }
  797. else
  798. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  799. array('{class}'=>get_class($this), '{event}'=>$name)));
  800. }
  801. public function attachEventHandler($name,$handler)
  802. {
  803. $this->getEventHandlers($name)->add($handler);
  804. }
  805. public function detachEventHandler($name,$handler)
  806. {
  807. if($this->hasEventHandler($name))
  808. return $this->getEventHandlers($name)->remove($handler)!==false;
  809. else
  810. return false;
  811. }
  812. public function raiseEvent($name,$event)
  813. {
  814. $name=strtolower($name);
  815. if(isset($this->_e[$name]))
  816. {
  817. foreach($this->_e[$name] as $handler)
  818. {
  819. if(is_string($handler))
  820. call_user_func($handler,$event);
  821. elseif(is_callable($handler,true))
  822. {
  823. if(is_array($handler))
  824. {
  825. // an array: 0 - object, 1 - method name
  826. list($object,$method)=$handler;
  827. if(is_string($object)) // static method call
  828. call_user_func($handler,$event);
  829. elseif(method_exists($object,$method))
  830. $object->$method($event);
  831. else
  832. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  833. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  834. }
  835. else // PHP 5.3: anonymous function
  836. call_user_func($handler,$event);
  837. }
  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}'=>gettype($handler))));
  841. // stop further handling if param.handled is set true
  842. if(($event instanceof CEvent) && $event->handled)
  843. return;
  844. }
  845. }
  846. elseif(YII_DEBUG && !$this->hasEvent($name))
  847. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  848. array('{class}'=>get_class($this), '{event}'=>$name)));
  849. }
  850. public function evaluateExpression($_expression_,$_data_=array())
  851. {
  852. if(is_string($_expression_))
  853. {
  854. extract($_data_);
  855. return eval('return '.$_expression_.';');
  856. }
  857. else
  858. {
  859. $_data_[]=$this;
  860. return call_user_func_array($_expression_, $_data_);
  861. }
  862. }
  863. }
  864. class CEvent extends CComponent
  865. {
  866. public $sender;
  867. public $handled=false;
  868. public $params;
  869. public function __construct($sender=null,$params=null)
  870. {
  871. $this->sender=$sender;
  872. $this->params=$params;
  873. }
  874. }
  875. class CEnumerable
  876. {
  877. }
  878. abstract class CModule extends CComponent
  879. {
  880. public $preload=array();
  881. public $behaviors=array();
  882. private $_id;
  883. private $_parentModule;
  884. private $_basePath;
  885. private $_modulePath;
  886. private $_params;
  887. private $_modules=array();
  888. private $_moduleConfig=array();
  889. private $_components=array();
  890. private $_componentConfig=array();
  891. public function __construct($id,$parent,$config=null)
  892. {
  893. $this->_id=$id;
  894. $this->_parentModule=$parent;
  895. // set basePath at early as possible to avoid trouble
  896. if(is_string($config))
  897. $config=require($config);
  898. if(isset($config['basePath']))
  899. {
  900. $this->setBasePath($config['basePath']);
  901. unset($config['basePath']);
  902. }
  903. Yii::setPathOfAlias($id,$this->getBasePath());
  904. $this->preinit();
  905. $this->configure($config);
  906. $this->attachBehaviors($this->behaviors);
  907. $this->preloadComponents();
  908. $this->init();
  909. }
  910. public function __get($name)
  911. {
  912. if($this->hasComponent($name))
  913. return $this->getComponent($name);
  914. else
  915. return parent::__get($name);
  916. }
  917. public function __isset($name)
  918. {
  919. if($this->hasComponent($name))
  920. return $this->getComponent($name)!==null;
  921. else
  922. return parent::__isset($name);
  923. }
  924. public function getId()
  925. {
  926. return $this->_id;
  927. }
  928. public function setId($id)
  929. {
  930. $this->_id=$id;
  931. }
  932. public function getBasePath()
  933. {
  934. if($this->_basePath===null)
  935. {
  936. $class=new ReflectionClass(get_class($this));
  937. $this->_basePath=dirname($class->getFileName());
  938. }
  939. return $this->_basePath;
  940. }
  941. public function setBasePath($path)
  942. {
  943. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  944. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  945. array('{path}'=>$path)));
  946. }
  947. public function getParams()
  948. {
  949. if($this->_params!==null)
  950. return $this->_params;
  951. else
  952. {
  953. $this->_params=new CAttributeCollection;
  954. $this->_params->caseSensitive=true;
  955. return $this->_params;
  956. }
  957. }
  958. public function setParams($value)
  959. {
  960. $params=$this->getParams();
  961. foreach($value as $k=>$v)
  962. $params->add($k,$v);
  963. }
  964. public function getModulePath()
  965. {
  966. if($this->_modulePath!==null)
  967. return $this->_modulePath;
  968. else
  969. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  970. }
  971. public function setModulePath($value)
  972. {
  973. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  974. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  975. array('{path}'=>$value)));
  976. }
  977. public function setImport($aliases)
  978. {
  979. foreach($aliases as $alias)
  980. Yii::import($alias);
  981. }
  982. public function setAliases($mappings)
  983. {
  984. foreach($mappings as $name=>$alias)
  985. {
  986. if(($path=Yii::getPathOfAlias($alias))!==false)
  987. Yii::setPathOfAlias($name,$path);
  988. else
  989. Yii::setPathOfAlias($name,$alias);
  990. }
  991. }
  992. public function getParentModule()
  993. {
  994. return $this->_parentModule;
  995. }
  996. public function getModule($id)
  997. {
  998. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  999. return $this->_modules[$id];
  1000. elseif(isset($this->_moduleConfig[$id]))
  1001. {
  1002. $config=$this->_moduleConfig[$id];
  1003. if(!isset($config['enabled']) || $config['enabled'])
  1004. {
  1005. $class=$config['class'];
  1006. unset($config['class'], $config['enabled']);
  1007. if($this===Yii::app())
  1008. $module=Yii::createComponent($class,$id,null,$config);
  1009. else
  1010. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  1011. return $this->_modules[$id]=$module;
  1012. }
  1013. }
  1014. }
  1015. public function hasModule($id)
  1016. {
  1017. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  1018. }
  1019. public function getModules()
  1020. {
  1021. return $this->_moduleConfig;
  1022. }
  1023. public function setModules($modules)
  1024. {
  1025. foreach($modules as $id=>$module)
  1026. {
  1027. if(is_int($id))
  1028. {
  1029. $id=$module;
  1030. $module=array();
  1031. }
  1032. if(!isset($module['class']))
  1033. {
  1034. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1035. $module['class']=$id.'.'.ucfirst($id).'Module';
  1036. }
  1037. if(isset($this->_moduleConfig[$id]))
  1038. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1039. else
  1040. $this->_moduleConfig[$id]=$module;
  1041. }
  1042. }
  1043. public function hasComponent($id)
  1044. {
  1045. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1046. }
  1047. public function getComponent($id,$createIfNull=true)
  1048. {
  1049. if(isset($this->_components[$id]))
  1050. return $this->_components[$id];
  1051. elseif(isset($this->_componentConfig[$id]) && $createIfNull)
  1052. {
  1053. $config=$this->_componentConfig[$id];
  1054. if(!isset($config['enabled']) || $config['enabled'])
  1055. {
  1056. unset($config['enabled']);
  1057. $component=Yii::createComponent($config);
  1058. $component->init();
  1059. return $this->_components[$id]=$component;
  1060. }
  1061. }
  1062. }
  1063. public function setComponent($id,$component,$merge=true)
  1064. {
  1065. if($component===null)
  1066. {
  1067. unset($this->_components[$id]);
  1068. return;
  1069. }
  1070. elseif($component instanceof IApplicationComponent)
  1071. {
  1072. $this->_components[$id]=$component;
  1073. if(!$component->getIsInitialized())
  1074. $component->init();
  1075. return;
  1076. }
  1077. elseif(isset($this->_components[$id]))
  1078. {
  1079. if(isset($component['class']) && get_class($this->_components[$id])!==$component['class'])
  1080. {
  1081. unset($this->_components[$id]);
  1082. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1083. return;
  1084. }
  1085. foreach($component as $key=>$value)
  1086. {
  1087. if($key!=='class')
  1088. $this->_components[$id]->$key=$value;
  1089. }
  1090. }
  1091. elseif(isset($this->_componentConfig[$id]['class'],$component['class'])
  1092. && $this->_componentConfig[$id]['class']!==$component['class'])
  1093. {
  1094. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1095. return;
  1096. }
  1097. if(isset($this->_componentConfig[$id]) && $merge)
  1098. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1099. else
  1100. $this->_componentConfig[$id]=$component;
  1101. }
  1102. public function getComponents($loadedOnly=true)
  1103. {
  1104. if($loadedOnly)
  1105. return $this->_components;
  1106. else
  1107. return array_merge($this->_componentConfig, $this->_components);
  1108. }
  1109. public function setComponents($components,$merge=true)
  1110. {
  1111. foreach($components as $id=>$component)
  1112. $this->setComponent($id,$component,$merge);
  1113. }
  1114. public function configure($config)
  1115. {
  1116. if(is_array($config))
  1117. {
  1118. foreach($config as $key=>$value)
  1119. $this->$key=$value;
  1120. }
  1121. }
  1122. protected function preloadComponents()
  1123. {
  1124. foreach($this->preload as $id)
  1125. $this->getComponent($id);
  1126. }
  1127. protected function preinit()
  1128. {
  1129. }
  1130. protected function init()
  1131. {
  1132. }
  1133. }
  1134. abstract class CApplication extends CModule
  1135. {
  1136. public $name='My Application';
  1137. public $charset='UTF-8';
  1138. public $sourceLanguage='en_us';
  1139. private $_id;
  1140. private $_basePath;
  1141. private $_runtimePath;
  1142. private $_extensionPath;
  1143. private $_globalState;
  1144. private $_stateChanged;
  1145. private $_ended=false;
  1146. private $_language;
  1147. private $_homeUrl;
  1148. abstract public function processRequest();
  1149. public function __construct($config=null)
  1150. {
  1151. Yii::setApplication($this);
  1152. // set basePath at early as possible to avoid trouble
  1153. if(is_string($config))
  1154. $config=require($config);
  1155. if(isset($config['basePath']))
  1156. {
  1157. $this->setBasePath($config['basePath']);
  1158. unset($config['basePath']);
  1159. }
  1160. else
  1161. $this->setBasePath('protected');
  1162. Yii::setPathOfAlias('application',$this->getBasePath());
  1163. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1164. if(isset($config['extensionPath']))
  1165. {
  1166. $this->setExtensionPath($config['extensionPath']);
  1167. unset($config['extensionPath']);
  1168. }
  1169. else
  1170. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1171. if(isset($config['aliases']))
  1172. {
  1173. $this->setAliases($config['aliases']);
  1174. unset($config['aliases']);
  1175. }
  1176. $this->preinit();
  1177. $this->initSystemHandlers();
  1178. $this->registerCoreComponents();
  1179. $this->configure($config);
  1180. $this->attachBehaviors($this->behaviors);
  1181. $this->preloadComponents();
  1182. $this->init();
  1183. }
  1184. public function run()
  1185. {
  1186. if($this->hasEventHandler('onBeginRequest'))
  1187. $this->onBeginRequest(new CEvent($this));
  1188. register_shutdown_function(array($this,'end'),0,false);
  1189. $this->processRequest();
  1190. if($this->hasEventHandler('onEndRequest'))
  1191. $this->onEndRequest(new CEvent($this));
  1192. }
  1193. public function end($status=0,$exit=true)
  1194. {
  1195. if($this->hasEventHandler('onEndRequest'))
  1196. $this->onEndRequest(new CEvent($this));
  1197. if($exit)
  1198. exit($status);
  1199. }
  1200. public function onBeginRequest($event)
  1201. {
  1202. $this->raiseEvent('onBeginRequest',$event);
  1203. }
  1204. public function onEndRequest($event)
  1205. {
  1206. if(!$this->_ended)
  1207. {
  1208. $this->_ended=true;
  1209. $this->raiseEvent('onEndRequest',$event);
  1210. }
  1211. }
  1212. public function getId()
  1213. {
  1214. if($this->_id!==null)
  1215. return $this->_id;
  1216. else
  1217. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1218. }
  1219. public function setId($id)
  1220. {
  1221. $this->_id=$id;
  1222. }
  1223. public function getBasePath()
  1224. {
  1225. return $this->_basePath;
  1226. }
  1227. public function setBasePath($path)
  1228. {
  1229. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1230. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1231. array('{path}'=>$path)));
  1232. }
  1233. public function getRuntimePath()
  1234. {
  1235. if($this->_runtimePath!==null)
  1236. return $this->_runtimePath;
  1237. else
  1238. {
  1239. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1240. return $this->_runtimePath;
  1241. }
  1242. }
  1243. public function setRuntimePath($path)
  1244. {
  1245. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1246. 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.',
  1247. array('{path}'=>$path)));
  1248. $this->_runtimePath=$runtimePath;
  1249. }
  1250. public function getExtensionPath()
  1251. {
  1252. return Yii::getPathOfAlias('ext');
  1253. }
  1254. public function setExtensionPath($path)
  1255. {
  1256. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1257. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1258. array('{path}'=>$path)));
  1259. Yii::setPathOfAlias('ext',$extensionPath);
  1260. }
  1261. public function getLanguage()
  1262. {
  1263. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1264. }
  1265. public function setLanguage($language)
  1266. {
  1267. $this->_language=$language;
  1268. }
  1269. public function getTimeZone()
  1270. {
  1271. return date_default_timezone_get();
  1272. }
  1273. public function setTimeZone($value)
  1274. {
  1275. date_default_timezone_set($value);
  1276. }
  1277. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1278. {
  1279. if($srcLanguage===null)
  1280. $srcLanguage=$this->sourceLanguage;
  1281. if($language===null)
  1282. $language=$this->getLanguage();
  1283. if($language===$srcLanguage)
  1284. return $srcFile;
  1285. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1286. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1287. }
  1288. public function getLocale($localeID=null)
  1289. {
  1290. return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID);
  1291. }
  1292. public function getLocaleDataPath()
  1293. {
  1294. return CLocale::$dataPath===null ? Yii::getPathOfAlias('system.i18n.data') : CLocale::$dataPath;
  1295. }
  1296. public function setLocaleDataPath($value)
  1297. {
  1298. CLocale::$dataPath=$value;
  1299. }
  1300. public function getNumberFormatter()
  1301. {
  1302. return $this->getLocale()->getNumberFormatter();
  1303. }
  1304. public function getDateFormatter()
  1305. {
  1306. return $this->getLocale()->getDateFormatter();
  1307. }
  1308. public function getDb()
  1309. {
  1310. return $this->getComponent('db');
  1311. }
  1312. public function getErrorHandler()
  1313. {
  1314. return $this->getComponent('errorHandler');
  1315. }
  1316. public function getSecurityManager()
  1317. {
  1318. return $this->getComponent('securityManager');
  1319. }
  1320. public function getStatePersister()
  1321. {
  1322. return $this->getComponent('statePersister');
  1323. }
  1324. public function getCache()
  1325. {
  1326. return $this->getComponent('cache');
  1327. }
  1328. public function getCoreMessages()
  1329. {
  1330. return $this->getComponent('coreMessages');
  1331. }
  1332. public function getMessages()
  1333. {
  1334. return $this->getComponent('messages');
  1335. }
  1336. public function getRequest()
  1337. {
  1338. return $this->getComponent('request');
  1339. }
  1340. public function getUrlManager()
  1341. {
  1342. return $this->getComponent('urlManager');
  1343. }
  1344. public function getController()
  1345. {
  1346. return null;
  1347. }
  1348. public function createUrl($route,$params=array(),$ampersand='&')
  1349. {
  1350. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1351. }
  1352. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1353. {
  1354. $url=$this->createUrl($route,$params,$ampersand);
  1355. if(strpos($url,'http')===0)
  1356. return $url;
  1357. else
  1358. return $this->getRequest()->getHostInfo($schema).$url;
  1359. }
  1360. public function getBaseUrl($absolute=false)
  1361. {
  1362. return $this->getRequest()->getBaseUrl($absolute);
  1363. }
  1364. public function getHomeUrl()
  1365. {
  1366. if($this->_homeUrl===null)
  1367. {
  1368. if($this->getUrlManager()->showScriptName)
  1369. return $this->getRequest()->getScriptUrl();
  1370. else
  1371. return $this->getRequest()->getBaseUrl().'/';
  1372. }
  1373. else
  1374. return $this->_homeUrl;
  1375. }
  1376. public function setHomeUrl($value)
  1377. {
  1378. $this->_homeUrl=$value;
  1379. }
  1380. public function getGlobalState($key,$defaultValue=null)
  1381. {
  1382. if($this->_globalState===null)
  1383. $this->loadGlobalState();
  1384. if(isset($this->_globalState[$key]))
  1385. return $this->_globalState[$key];
  1386. else
  1387. return $defaultValue;
  1388. }
  1389. public function setGlobalState($key,$value,$defaultValue=null)
  1390. {
  1391. if($this->_globalState===null)
  1392. $this->loadGlobalState();
  1393. $changed=$this->_stateChanged;
  1394. if($value===$defaultValue)
  1395. {
  1396. if(isset($this->_globalState[$key]))
  1397. {
  1398. unset($this->_globalState[$key]);
  1399. $this->_stateChanged=true;
  1400. }
  1401. }
  1402. elseif(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1403. {
  1404. $this->_globalState[$key]=$value;
  1405. $this->_stateChanged=true;
  1406. }
  1407. if($this->_stateChanged!==$changed)
  1408. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1409. }
  1410. public function clearGlobalState($key)
  1411. {
  1412. $this->setGlobalState($key,true,true);
  1413. }
  1414. public function loadGlobalState()
  1415. {
  1416. $persister=$this->getStatePersister();
  1417. if(($this->_globalState=$persister->load())===null)
  1418. $this->_globalState=array();
  1419. $this->_stateChanged=false;
  1420. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1421. }
  1422. public function saveGlobalState()
  1423. {
  1424. if($this->_stateChanged)
  1425. {
  1426. $this->_stateChanged=false;
  1427. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1428. $this->getStatePersister()->save($this->_globalState);
  1429. }
  1430. }
  1431. public function handleException($exception)
  1432. {
  1433. // disable error capturing to avoid recursive errors
  1434. restore_error_handler();
  1435. restore_exception_handler();
  1436. $category='exception.'.get_class($exception);
  1437. if($exception instanceof CHttpException)
  1438. $category.='.'.$exception->statusCode;
  1439. // php <5.2 doesn't support string conversion auto-magically
  1440. $message=$exception->__toString();
  1441. if(isset($_SERVER['REQUEST_URI']))
  1442. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  1443. if(isset($_SERVER['HTTP_REFERER']))
  1444. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  1445. $message.="\n---";
  1446. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1447. try
  1448. {
  1449. $event=new CExceptionEvent($this,$exception);
  1450. $this->onException($event);
  1451. if(!$event->handled)
  1452. {
  1453. // try an error handler
  1454. if(($handler=$this->getErrorHandler())!==null)
  1455. $handler->handle($event);
  1456. else
  1457. $this->displayException($exception);
  1458. }
  1459. }
  1460. catch(Exception $e)
  1461. {
  1462. $this->displayException($e);
  1463. }
  1464. try
  1465. {
  1466. $this->end(1);
  1467. }
  1468. catch(Exception $e)
  1469. {
  1470. // use the most primitive way to log error
  1471. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1472. $msg .= $e->getTraceAsString()."\n";
  1473. $msg .= "Previous exception:\n";
  1474. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1475. $msg .= $exception->getTraceAsString()."\n";
  1476. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1477. error_log($msg);
  1478. exit(1);
  1479. }
  1480. }
  1481. public function handleError($code,$message,$file,$line)
  1482. {
  1483. if($code & error_reporting())
  1484. {
  1485. // disable error capturing to avoid recursive errors
  1486. restore_error_handler();
  1487. restore_exception_handler();
  1488. $log="$message ($file:$line)\nStack trace:\n";
  1489. $trace=debug_backtrace();
  1490. // skip the first 3 stacks as they do not tell the error position
  1491. if(count($trace)>3)
  1492. $trace=array_slice($trace,3);
  1493. foreach($trace as $i=>$t)
  1494. {
  1495. if(!isset($t['file']))
  1496. $t['file']='unknown';
  1497. if(!isset($t['line']))
  1498. $t['line']=0;
  1499. if(!isset($t['function']))
  1500. $t['function']='unknown';
  1501. $log.="#$i {$t['file']}({$t['line']}): ";
  1502. if(isset($t['object']) && is_object($t['object']))
  1503. $log.=get_class($t['object']).'->';
  1504. $log.="{$t['function']}()\n";
  1505. }
  1506. if(isset($_SERVER['REQUEST_URI']))
  1507. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1508. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1509. try
  1510. {
  1511. Yii::import('CErrorEvent',true);
  1512. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1513. $this->onError($event);
  1514. if(!$event->handled)
  1515. {
  1516. // try an error handler
  1517. if(($handler=$this->getErrorHandler())!==null)
  1518. $handler->handle($event);
  1519. else
  1520. $this->displayError($code,$message,$file,$line);
  1521. }
  1522. }
  1523. catch(Exception $e)
  1524. {
  1525. $this->displayException($e);
  1526. }
  1527. try
  1528. {
  1529. $this->end(1);
  1530. }
  1531. catch(Exception $e)
  1532. {
  1533. // use the most primitive way to log error
  1534. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1535. $msg .= $e->getTraceAsString()."\n";
  1536. $msg .= "Previous error:\n";
  1537. $msg .= $log."\n";
  1538. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1539. error_log($msg);
  1540. exit(1);
  1541. }
  1542. }
  1543. }
  1544. public function onException($event)
  1545. {
  1546. $this->raiseEvent('onException',$event);
  1547. }
  1548. public function onError($event)
  1549. {
  1550. $this->raiseEvent('onError',$event);
  1551. }
  1552. public function displayError($code,$message,$file,$line)
  1553. {
  1554. if(YII_DEBUG)
  1555. {
  1556. echo "<h1>PHP Error [$code]</h1>\n";
  1557. echo "<p>$message ($file:$line)</p>\n";
  1558. echo '<pre>';
  1559. $trace=debug_backtrace();
  1560. // skip the first 3 stacks as they do not tell the error position
  1561. if(count($trace)>3)
  1562. $trace=array_slice($trace,3);
  1563. foreach($trace as $i=>$t)
  1564. {
  1565. if(!isset($t['file']))
  1566. $t['file']='unknown';
  1567. if(!isset($t['line']))
  1568. $t['line']=0;
  1569. if(!isset($t['function']))
  1570. $t['function']='unknown';
  1571. echo "#$i {$t['file']}({$t['line']}): ";
  1572. if(isset($t['object']) && is_object($t['object']))
  1573. echo get_class($t['object']).'->';
  1574. echo "{$t['function']}()\n";
  1575. }
  1576. echo '</pre>';
  1577. }
  1578. else
  1579. {
  1580. echo "<h1>PHP Error [$code]</h1>\n";
  1581. echo "<p>$message</p>\n";
  1582. }
  1583. }
  1584. public function displayException($exception)
  1585. {
  1586. if(YII_DEBUG)
  1587. {
  1588. echo '<h1>'.get_class($exception)."</h1>\n";
  1589. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1590. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1591. }
  1592. else
  1593. {
  1594. echo '<h1>'.get_class($exception)."</h1>\n";
  1595. echo '<p>'.$exception->getMessage().'</p>';
  1596. }
  1597. }
  1598. protected function initSystemHandlers()
  1599. {
  1600. if(YII_ENABLE_EXCEPTION_HANDLER)
  1601. set_exception_handler(array($this,'handleException'));
  1602. if(YII_ENABLE_ERROR_HANDLER)
  1603. set_error_handler(array($this,'handleError'),error_reporting());
  1604. }
  1605. protected function registerCoreComponents()
  1606. {
  1607. $components=array(
  1608. 'coreMessages'=>array(
  1609. 'class'=>'CPhpMessageSource',
  1610. 'language'=>'en_us',
  1611. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1612. ),
  1613. 'db'=>array(
  1614. 'class'=>'CDbConnection',
  1615. ),
  1616. 'messages'=>array(
  1617. 'class'=>'CPhpMessageSource',
  1618. ),
  1619. 'errorHandler'=>array(
  1620. 'class'=>'CErrorHandler',
  1621. ),
  1622. 'securityManager'=>array(
  1623. 'class'=>'CSecurityManager',
  1624. ),
  1625. 'statePersister'=>array(
  1626. 'class'=>'CStatePersister',
  1627. ),
  1628. 'urlManager'=>array(
  1629. 'class'=>'CUrlManager',
  1630. ),
  1631. 'request'=>array(
  1632. 'class'=>'CHttpRequest',
  1633. ),
  1634. 'format'=>array(
  1635. 'class'=>'CFormatter',
  1636. ),
  1637. );
  1638. $this->setComponents($components);
  1639. }
  1640. }
  1641. class CWebApplication extends CApplication
  1642. {
  1643. public $defaultController='site';
  1644. public $layout='main';
  1645. public $controllerMap=array();
  1646. public $catchAllRequest;
  1647. public $controllerNamespace;
  1648. private $_controllerPath;
  1649. private $_viewPath;
  1650. private $_systemViewPath;
  1651. private $_layoutPath;
  1652. private $_controller;
  1653. private $_theme;
  1654. public function processRequest()
  1655. {
  1656. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1657. {
  1658. $route=$this->catchAllRequest[0];
  1659. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1660. $_GET[$name]=$value;
  1661. }
  1662. else
  1663. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1664. $this->runController($route);
  1665. }
  1666. protected function registerCoreComponents()
  1667. {
  1668. parent::registerCoreComponents();
  1669. $components=array(
  1670. 'session'=>array(
  1671. 'class'=>'CHttpSession',
  1672. ),
  1673. 'assetManager'=>array(
  1674. 'class'=>'CAssetManager',
  1675. ),
  1676. 'user'=>array(
  1677. 'class'=>'CWebUser',
  1678. ),
  1679. 'themeManager'=>array(
  1680. 'class'=>'CThemeManager',
  1681. ),
  1682. 'authManager'=>array(
  1683. 'class'=>'CPhpAuthManager',
  1684. ),
  1685. 'clientScript'=>array(
  1686. 'class'=>'CClientScript',
  1687. ),
  1688. 'widgetFactory'=>array(
  1689. 'class'=>'CWidgetFactory',
  1690. ),
  1691. );
  1692. $this->setComponents($components);
  1693. }
  1694. public function getAuthManager()
  1695. {
  1696. return $this->getComponent('authManager');
  1697. }
  1698. public function getAssetManager()
  1699. {
  1700. return $this->getComponent('assetManager');
  1701. }
  1702. public function getSession()
  1703. {
  1704. return $this->getComponent('session');
  1705. }
  1706. public function getUser()
  1707. {
  1708. return $this->getComponent('user');
  1709. }
  1710. public function getViewRenderer()
  1711. {
  1712. return $this->getComponent('viewRenderer');
  1713. }
  1714. public function getClientScript()
  1715. {
  1716. return $this->getComponent('clientScript');
  1717. }
  1718. public function getWidgetFactory()
  1719. {
  1720. return $this->getComponent('widgetFactory');
  1721. }
  1722. public function getThemeManager()
  1723. {
  1724. return $this->getComponent('themeManager');
  1725. }
  1726. public function getTheme()
  1727. {
  1728. if(is_string($this->_theme))
  1729. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1730. return $this->_theme;
  1731. }
  1732. public function setTheme($value)
  1733. {
  1734. $this->_theme=$value;
  1735. }
  1736. public function runController($route)
  1737. {
  1738. if(($ca=$this->createController($route))!==null)
  1739. {
  1740. list($controller,$actionID)=$ca;
  1741. $oldController=$this->_controller;
  1742. $this->_controller=$controller;
  1743. $controller->init();
  1744. $controller->run($actionID);
  1745. $this->_controller=$oldController;
  1746. }
  1747. else
  1748. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1749. array('{route}'=>$route===''?$this->defaultController:$route)));
  1750. }
  1751. public function createController($route,$owner=null)
  1752. {
  1753. if($owner===null)
  1754. $owner=$this;
  1755. if(($route=trim($route,'/'))==='')
  1756. $route=$owner->defaultController;
  1757. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1758. $route.='/';
  1759. while(($pos=strpos($route,'/'))!==false)
  1760. {
  1761. $id=substr($route,0,$pos);
  1762. if(!preg_match('/^\w+$/',$id))
  1763. return null;
  1764. if(!$caseSensitive)
  1765. $id=strtolower($id);
  1766. $route=(string)substr($route,$pos+1);
  1767. if(!isset($basePath)) // first segment
  1768. {
  1769. if(isset($owner->controllerMap[$id]))
  1770. {
  1771. return array(
  1772. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1773. $this->parseActionParams($route),
  1774. );
  1775. }
  1776. if(($module=$owner->getModule($id))!==null)
  1777. return $this->createController($route,$module);
  1778. $basePath=$owner->getControllerPath();
  1779. $controllerID='';
  1780. }
  1781. else
  1782. $controllerID.='/';
  1783. $className=ucfirst($id).'Controller';
  1784. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1785. if($owner->controllerNamespace!==null)
  1786. $className=$owner->controllerNamespace.'\\'.$className;
  1787. if(is_file($classFile))
  1788. {
  1789. if(!class_exists($className,false))
  1790. require($classFile);
  1791. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1792. {
  1793. $id[0]=strtolower($id[0]);
  1794. return array(
  1795. new $className($controllerID.$id,$owner===$this?null:$owner),
  1796. $this->parseActionParams($route),
  1797. );
  1798. }
  1799. return null;
  1800. }
  1801. $controllerID.=$id;
  1802. $basePath.=DIRECTORY_SEPARATOR.$id;
  1803. }
  1804. }
  1805. protected function parseActionParams($pathInfo)
  1806. {
  1807. if(($pos=strpos($pathInfo,'/'))!==false)
  1808. {
  1809. $manager=$this->getUrlManager();
  1810. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1811. $actionID=substr($pathInfo,0,$pos);
  1812. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1813. }
  1814. else
  1815. return $pathInfo;
  1816. }
  1817. public function getController()
  1818. {
  1819. return $this->_controller;
  1820. }
  1821. public function setController($value)
  1822. {
  1823. $this->_controller=$value;
  1824. }
  1825. public function getControllerPath()
  1826. {
  1827. if($this->_controllerPath!==null)
  1828. return $this->_controllerPath;
  1829. else
  1830. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1831. }
  1832. public function setControllerPath($value)
  1833. {
  1834. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1835. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1836. array('{path}'=>$value)));
  1837. }
  1838. public function getViewPath()
  1839. {
  1840. if($this->_viewPath!==null)
  1841. return $this->_viewPath;
  1842. else
  1843. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1844. }
  1845. public function setViewPath($path)
  1846. {
  1847. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1848. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1849. array('{path}'=>$path)));
  1850. }
  1851. public function getSystemViewPath()
  1852. {
  1853. if($this->_systemViewPath!==null)
  1854. return $this->_systemViewPath;
  1855. else
  1856. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1857. }
  1858. public function setSystemViewPath($path)
  1859. {
  1860. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1861. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1862. array('{path}'=>$path)));
  1863. }
  1864. public function getLayoutPath()
  1865. {
  1866. if($this->_layoutPath!==null)
  1867. return $this->_layoutPath;
  1868. else
  1869. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1870. }
  1871. public function setLayoutPath($path)
  1872. {
  1873. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1874. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1875. array('{path}'=>$path)));
  1876. }
  1877. public function beforeControllerAction($controller,$action)
  1878. {
  1879. return true;
  1880. }
  1881. public function afterControllerAction($controller,$action)
  1882. {
  1883. }
  1884. public function findModule($id)
  1885. {
  1886. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1887. {
  1888. do
  1889. {
  1890. if(($m=$module->getModule($id))!==null)
  1891. return $m;
  1892. } while(($module=$module->getParentModule())!==null);
  1893. }
  1894. if(($m=$this->getModule($id))!==null)
  1895. return $m;
  1896. }
  1897. protected function init()
  1898. {
  1899. parent::init();
  1900. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1901. $this->getRequest();
  1902. }
  1903. }
  1904. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1905. {
  1906. private $_d=array();
  1907. private $_r=false;
  1908. public function __construct($data=null,$readOnly=false)
  1909. {
  1910. if($data!==null)
  1911. $this->copyFrom($data);
  1912. $this->setReadOnly($readOnly);
  1913. }
  1914. public function getReadOnly()
  1915. {
  1916. return $this->_r;
  1917. }
  1918. protected function setReadOnly($value)
  1919. {
  1920. $this->_r=$value;
  1921. }
  1922. public function getIterator()
  1923. {
  1924. return new CMapIterator($this->_d);
  1925. }
  1926. public function count()
  1927. {
  1928. return $this->getCount();
  1929. }
  1930. public function getCount()
  1931. {
  1932. return count($this->_d);
  1933. }
  1934. public function getKeys()
  1935. {
  1936. return array_keys($this->_d);
  1937. }
  1938. public function itemAt($key)
  1939. {
  1940. if(isset($this->_d[$key]))
  1941. return $this->_d[$key];
  1942. else
  1943. return null;
  1944. }
  1945. public function add($key,$value)
  1946. {
  1947. if(!$this->_r)
  1948. {
  1949. if($key===null)
  1950. $this->_d[]=$value;
  1951. else
  1952. $this->_d[$key]=$value;
  1953. }
  1954. else
  1955. throw new CException(Yii::t('yii','The map is read only.'));
  1956. }
  1957. public function remove($key)
  1958. {
  1959. if(!$this->_r)
  1960. {
  1961. if(isset($this->_d[$key]))
  1962. {
  1963. $value=$this->_d[$key];
  1964. unset($this->_d[$key]);
  1965. return $value;
  1966. }
  1967. else
  1968. {
  1969. // it is possible the value is null, which is not detected by isset
  1970. unset($this->_d[$key]);
  1971. return null;
  1972. }
  1973. }
  1974. else
  1975. throw new CException(Yii::t('yii','The map is read only.'));
  1976. }
  1977. public function clear()
  1978. {
  1979. foreach(array_keys($this->_d) as $key)
  1980. $this->remove($key);
  1981. }
  1982. public function contains($key)
  1983. {
  1984. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  1985. }
  1986. public function toArray()
  1987. {
  1988. return $this->_d;
  1989. }
  1990. public function copyFrom($data)
  1991. {
  1992. if(is_array($data) || $data instanceof Traversable)
  1993. {
  1994. if($this->getCount()>0)
  1995. $this->clear();
  1996. if($data instanceof CMap)
  1997. $data=$data->_d;
  1998. foreach($data as $key=>$value)
  1999. $this->add($key,$value);
  2000. }
  2001. elseif($data!==null)
  2002. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  2003. }
  2004. public function mergeWith($data,$recursive=true)
  2005. {
  2006. if(is_array($data) || $data instanceof Traversable)
  2007. {
  2008. if($data instanceof CMap)
  2009. $data=$data->_d;
  2010. if($recursive)
  2011. {
  2012. if($data instanceof Traversable)
  2013. {
  2014. $d=array();
  2015. foreach($data as $key=>$value)
  2016. $d[$key]=$value;
  2017. $this->_d=self::mergeArray($this->_d,$d);
  2018. }
  2019. else
  2020. $this->_d=self::mergeArray($this->_d,$data);
  2021. }
  2022. else
  2023. {
  2024. foreach($data as $key=>$value)
  2025. $this->add($key,$value);
  2026. }
  2027. }
  2028. elseif($data!==null)
  2029. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  2030. }
  2031. public static function mergeArray($a,$b)
  2032. {
  2033. $args=func_get_args();
  2034. $res=array_shift($args);
  2035. while(!empty($args))
  2036. {
  2037. $next=array_shift($args);
  2038. foreach($next as $k => $v)
  2039. {
  2040. if(is_integer($k))
  2041. isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
  2042. elseif(is_array($v) && isset($res[$k]) && is_array($res[$k]))
  2043. $res[$k]=self::mergeArray($res[$k],$v);
  2044. else
  2045. $res[$k]=$v;
  2046. }
  2047. }
  2048. return $res;
  2049. }
  2050. public function offsetExists($offset)
  2051. {
  2052. return $this->contains($offset);
  2053. }
  2054. public function offsetGet($offset)
  2055. {
  2056. return $this->itemAt($offset);
  2057. }
  2058. public function offsetSet($offset,$item)
  2059. {
  2060. $this->add($offset,$item);
  2061. }
  2062. public function offsetUnset($offset)
  2063. {
  2064. $this->remove($offset);
  2065. }
  2066. }
  2067. class CLogger extends CComponent
  2068. {
  2069. const LEVEL_TRACE='trace';
  2070. const LEVEL_WARNING='warning';
  2071. const LEVEL_ERROR='error';
  2072. const LEVEL_INFO='info';
  2073. const LEVEL_PROFILE='profile';
  2074. public $autoFlush=10000;
  2075. public $autoDump=false;
  2076. private $_logs=array();
  2077. private $_logCount=0;
  2078. private $_levels;
  2079. private $_categories;
  2080. private $_except=array();
  2081. private $_timings;
  2082. private $_processing=false;
  2083. public function log($message,$level='info',$category='application')
  2084. {
  2085. $this->_logs[]=array($message,$level,$category,microtime(true));
  2086. $this->_logCount++;
  2087. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
  2088. {
  2089. $this->_processing=true;
  2090. $this->flush($this->autoDump);
  2091. $this->_processing=false;
  2092. }
  2093. }
  2094. public function getLogs($levels='',$categories=array(), $except=array())
  2095. {
  2096. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2097. if (is_string($categories))
  2098. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2099. else
  2100. $this->_categories=array_filter(array_map('strtolower',$categories));
  2101. if (is_string($except))
  2102. $this->_except=preg_split('/[\s,]+/',strtolower($except),-1,PREG_SPLIT_NO_EMPTY);
  2103. else
  2104. $this->_except=array_filter(array_map('strtolower',$except));
  2105. $ret=$this->_logs;
  2106. if(!empty($levels))
  2107. $ret=array_values(array_filter($ret,array($this,'filterByLevel')));
  2108. if(!empty($this->_categories) || !empty($this->_except))
  2109. $ret=array_values(array_filter($ret,array($this,'filterByCategory')));
  2110. return $ret;
  2111. }
  2112. private function filterByCategory($value)
  2113. {
  2114. return $this->filterAllCategories($value, 2);
  2115. }
  2116. private function filterTimingByCategory($value)
  2117. {
  2118. return $this->filterAllCategories($value, 1);
  2119. }
  2120. private function filterAllCategories($value, $index)
  2121. {
  2122. $cat=strtolower($value[$index]);
  2123. $ret=empty($this->_categories);
  2124. foreach($this->_categories as $category)
  2125. {
  2126. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2127. $ret=true;
  2128. }
  2129. if($ret)
  2130. {
  2131. foreach($this->_except as $category)
  2132. {
  2133. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2134. $ret=false;
  2135. }
  2136. }
  2137. return $ret;
  2138. }
  2139. private function filterByLevel($value)
  2140. {
  2141. return in_array(strtolower($value[1]),$this->_levels);
  2142. }
  2143. public function getExecutionTime()
  2144. {
  2145. return microtime(true)-YII_BEGIN_TIME;
  2146. }
  2147. public function getMemoryUsage()
  2148. {
  2149. if(function_exists('memory_get_usage'))
  2150. return memory_get_usage();
  2151. else
  2152. {
  2153. $output=array();
  2154. if(strncmp(PHP_OS,'WIN',3)===0)
  2155. {
  2156. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2157. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2158. }
  2159. else
  2160. {
  2161. $pid=getmypid();
  2162. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2163. $output=explode(" ",$output[0]);
  2164. return isset($output[1]) ? $output[1]*1024 : 0;
  2165. }
  2166. }
  2167. }
  2168. public function getProfilingResults($token=null,$categories=null,$refresh=false)
  2169. {
  2170. if($this->_timings===null || $refresh)
  2171. $this->calculateTimings();
  2172. if($token===null && $categories===null)
  2173. return $this->_timings;
  2174. $timings = $this->_timings;
  2175. if($categories!==null) {
  2176. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2177. $timings=array_filter($timings,array($this,'filterTimingByCategory'));
  2178. }
  2179. $results=array();
  2180. foreach($timings as $timing)
  2181. {
  2182. if($token===null || $timing[0]===$token)
  2183. $results[]=$timing[2];
  2184. }
  2185. return $results;
  2186. }
  2187. private function calculateTimings()
  2188. {
  2189. $this->_timings=array();
  2190. $stack=array();
  2191. foreach($this->_logs as $log)
  2192. {
  2193. if($log[1]!==CLogger::LEVEL_PROFILE)
  2194. continue;
  2195. list($message,$level,$category,$timestamp)=$log;
  2196. if(!strncasecmp($message,'begin:',6))
  2197. {
  2198. $log[0]=substr($message,6);
  2199. $stack[]=$log;
  2200. }
  2201. elseif(!strncasecmp($message,'end:',4))
  2202. {
  2203. $token=substr($message,4);
  2204. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2205. {
  2206. $delta=$log[3]-$last[3];
  2207. $this->_timings[]=array($message,$category,$delta);
  2208. }
  2209. else
  2210. 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.',
  2211. array('{token}'=>$token)));
  2212. }
  2213. }
  2214. $now=microtime(true);
  2215. while(($last=array_pop($stack))!==null)
  2216. {
  2217. $delta=$now-$last[3];
  2218. $this->_timings[]=array($last[0],$last[2],$delta);
  2219. }
  2220. }
  2221. public function flush($dumpLogs=false)
  2222. {
  2223. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2224. $this->_logs=array();
  2225. $this->_logCount=0;
  2226. }
  2227. public function onFlush($event)
  2228. {
  2229. $this->raiseEvent('onFlush', $event);
  2230. }
  2231. }
  2232. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2233. {
  2234. public $behaviors=array();
  2235. private $_initialized=false;
  2236. public function init()
  2237. {
  2238. $this->attachBehaviors($this->behaviors);
  2239. $this->_initialized=true;
  2240. }
  2241. public function getIsInitialized()
  2242. {
  2243. return $this->_initialized;
  2244. }
  2245. }
  2246. class CHttpRequest extends CApplicationComponent
  2247. {
  2248. public $enableCookieValidation=false;
  2249. public $enableCsrfValidation=false;
  2250. public $csrfTokenName='YII_CSRF_TOKEN';
  2251. public $csrfCookie;
  2252. private $_requestUri;
  2253. private $_pathInfo;
  2254. private $_scriptFile;
  2255. private $_scriptUrl;
  2256. private $_hostInfo;
  2257. private $_baseUrl;
  2258. private $_cookies;
  2259. private $_preferredAcceptTypes;
  2260. private $_preferredLanguages;
  2261. private $_csrfToken;
  2262. private $_restParams;
  2263. public function init()
  2264. {
  2265. parent::init();
  2266. $this->normalizeRequest();
  2267. }
  2268. protected function normalizeRequest()
  2269. {
  2270. // normalize request
  2271. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2272. {
  2273. if(isset($_GET))
  2274. $_GET=$this->stripSlashes($_GET);
  2275. if(isset($_POST))
  2276. $_POST=$this->stripSlashes($_POST);
  2277. if(isset($_REQUEST))
  2278. $_REQUEST=$this->stripSlashes($_REQUEST);
  2279. if(isset($_COOKIE))
  2280. $_COOKIE=$this->stripSlashes($_COOKIE);
  2281. }
  2282. if($this->enableCsrfValidation)
  2283. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2284. }
  2285. public function stripSlashes(&$data)
  2286. {
  2287. if(is_array($data))
  2288. {
  2289. if(count($data) == 0)
  2290. return $data;
  2291. $keys=array_map('stripslashes',array_keys($data));
  2292. $data=array_combine($keys,array_values($data));
  2293. return array_map(array($this,'stripSlashes'),$data);
  2294. }
  2295. else
  2296. return stripslashes($data);
  2297. }
  2298. public function getParam($name,$defaultValue=null)
  2299. {
  2300. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2301. }
  2302. public function getQuery($name,$defaultValue=null)
  2303. {
  2304. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2305. }
  2306. public function getPost($name,$defaultValue=null)
  2307. {
  2308. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2309. }
  2310. public function getDelete($name,$defaultValue=null)
  2311. {
  2312. if($this->getIsDeleteViaPostRequest())
  2313. return $this->getPost($name, $defaultValue);
  2314. if($this->getIsDeleteRequest())
  2315. {
  2316. $restParams=$this->getRestParams();
  2317. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2318. }
  2319. else
  2320. return $defaultValue;
  2321. }
  2322. public function getPut($name,$defaultValue=null)
  2323. {
  2324. if($this->getIsPutViaPostRequest())
  2325. return $this->getPost($name, $defaultValue);
  2326. if($this->getIsPutRequest())
  2327. {
  2328. $restParams=$this->getRestParams();
  2329. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2330. }
  2331. else
  2332. return $defaultValue;
  2333. }
  2334. public function getRestParams()
  2335. {
  2336. if($this->_restParams===null)
  2337. {
  2338. $result=array();
  2339. if(function_exists('mb_parse_str'))
  2340. mb_parse_str($this->getRawBody(), $result);
  2341. else
  2342. parse_str($this->getRawBody(), $result);
  2343. $this->_restParams=$result;
  2344. }
  2345. return $this->_restParams;
  2346. }
  2347. public function getRawBody()
  2348. {
  2349. static $rawBody;
  2350. if($rawBody===null)
  2351. $rawBody=file_get_contents('php://input');
  2352. return $rawBody;
  2353. }
  2354. public function getUrl()
  2355. {
  2356. return $this->getRequestUri();
  2357. }
  2358. public function getHostInfo($schema='')
  2359. {
  2360. if($this->_hostInfo===null)
  2361. {
  2362. if($secure=$this->getIsSecureConnection())
  2363. $http='https';
  2364. else
  2365. $http='http';
  2366. if(isset($_SERVER['HTTP_HOST']))
  2367. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2368. else
  2369. {
  2370. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2371. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2372. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2373. $this->_hostInfo.=':'.$port;
  2374. }
  2375. }
  2376. if($schema!=='')
  2377. {
  2378. $secure=$this->getIsSecureConnection();
  2379. if($secure && $schema==='https' || !$secure && $schema==='http')
  2380. return $this->_hostInfo;
  2381. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2382. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2383. $port=':'.$port;
  2384. else
  2385. $port='';
  2386. $pos=strpos($this->_hostInfo,':');
  2387. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2388. }
  2389. else
  2390. return $this->_hostInfo;
  2391. }
  2392. public function setHostInfo($value)
  2393. {
  2394. $this->_hostInfo=rtrim($value,'/');
  2395. }
  2396. public function getBaseUrl($absolute=false)
  2397. {
  2398. if($this->_baseUrl===null)
  2399. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2400. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2401. }
  2402. public function setBaseUrl($value)
  2403. {
  2404. $this->_baseUrl=$value;
  2405. }
  2406. public function getScriptUrl()
  2407. {
  2408. if($this->_scriptUrl===null)
  2409. {
  2410. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2411. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2412. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2413. elseif(basename($_SERVER['PHP_SELF'])===$scriptName)
  2414. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2415. elseif(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2416. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2417. elseif(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2418. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2419. elseif(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2420. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2421. else
  2422. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2423. }
  2424. return $this->_scriptUrl;
  2425. }
  2426. public function setScriptUrl($value)
  2427. {
  2428. $this->_scriptUrl='/'.trim($value,'/');
  2429. }
  2430. public function getPathInfo()
  2431. {
  2432. if($this->_pathInfo===null)
  2433. {
  2434. $pathInfo=$this->getRequestUri();
  2435. if(($pos=strpos($pathInfo,'?'))!==false)
  2436. $pathInfo=substr($pathInfo,0,$pos);
  2437. $pathInfo=$this->decodePathInfo($pathInfo);
  2438. $scriptUrl=$this->getScriptUrl();
  2439. $baseUrl=$this->getBaseUrl();
  2440. if(strpos($pathInfo,$scriptUrl)===0)
  2441. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2442. elseif($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2443. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2444. elseif(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2445. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2446. else
  2447. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2448. $this->_pathInfo=trim($pathInfo,'/');
  2449. }
  2450. return $this->_pathInfo;
  2451. }
  2452. protected function decodePathInfo($pathInfo)
  2453. {
  2454. $pathInfo = urldecode($pathInfo);
  2455. // is it UTF-8?
  2456. // http://w3.org/International/questions/qa-forms-utf-8.html
  2457. if(preg_match('%^(?:
  2458. [\x09\x0A\x0D\x20-\x7E] # ASCII
  2459. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  2460. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  2461. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  2462. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  2463. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  2464. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  2465. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  2466. )*$%xs', $pathInfo))
  2467. {
  2468. return $pathInfo;
  2469. }
  2470. else
  2471. {
  2472. return utf8_encode($pathInfo);
  2473. }
  2474. }
  2475. public function getRequestUri()
  2476. {
  2477. if($this->_requestUri===null)
  2478. {
  2479. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2480. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2481. elseif(isset($_SERVER['REQUEST_URI']))
  2482. {
  2483. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2484. if(!empty($_SERVER['HTTP_HOST']))
  2485. {
  2486. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2487. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2488. }
  2489. else
  2490. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2491. }
  2492. elseif(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2493. {
  2494. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2495. if(!empty($_SERVER['QUERY_STRING']))
  2496. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2497. }
  2498. else
  2499. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2500. }
  2501. return $this->_requestUri;
  2502. }
  2503. public function getQueryString()
  2504. {
  2505. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2506. }
  2507. public function getIsSecureConnection()
  2508. {
  2509. return isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']=='on' || $_SERVER['HTTPS']==1)
  2510. || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO']=='https';
  2511. }
  2512. public function getRequestType()
  2513. {
  2514. if(isset($_POST['_method']))
  2515. return strtoupper($_POST['_method']);
  2516. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2517. }
  2518. public function getIsPostRequest()
  2519. {
  2520. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2521. }
  2522. public function getIsDeleteRequest()
  2523. {
  2524. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE')) || $this->getIsDeleteViaPostRequest();
  2525. }
  2526. protected function getIsDeleteViaPostRequest()
  2527. {
  2528. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'DELETE');
  2529. }
  2530. public function getIsPutRequest()
  2531. {
  2532. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT')) || $this->getIsPutViaPostRequest();
  2533. }
  2534. protected function getIsPutViaPostRequest()
  2535. {
  2536. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PUT');
  2537. }
  2538. public function getIsAjaxRequest()
  2539. {
  2540. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2541. }
  2542. public function getIsFlashRequest()
  2543. {
  2544. return isset($_SERVER['HTTP_USER_AGENT']) && (stripos($_SERVER['HTTP_USER_AGENT'],'Shockwave')!==false || stripos($_SERVER['HTTP_USER_AGENT'],'Flash')!==false);
  2545. }
  2546. public function getServerName()
  2547. {
  2548. return $_SERVER['SERVER_NAME'];
  2549. }
  2550. public function getServerPort()
  2551. {
  2552. return $_SERVER['SERVER_PORT'];
  2553. }
  2554. public function getUrlReferrer()
  2555. {
  2556. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2557. }
  2558. public function getUserAgent()
  2559. {
  2560. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2561. }
  2562. public function getUserHostAddress()
  2563. {
  2564. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2565. }
  2566. public function getUserHost()
  2567. {
  2568. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2569. }
  2570. public function getScriptFile()
  2571. {
  2572. if($this->_scriptFile!==null)
  2573. return $this->_scriptFile;
  2574. else
  2575. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2576. }
  2577. public function getBrowser($userAgent=null)
  2578. {
  2579. return get_browser($userAgent,true);
  2580. }
  2581. public function getAcceptTypes()
  2582. {
  2583. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2584. }
  2585. private $_port;
  2586. public function getPort()
  2587. {
  2588. if($this->_port===null)
  2589. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2590. return $this->_port;
  2591. }
  2592. public function setPort($value)
  2593. {
  2594. $this->_port=(int)$value;
  2595. $this->_hostInfo=null;
  2596. }
  2597. private $_securePort;
  2598. public function getSecurePort()
  2599. {
  2600. if($this->_securePort===null)
  2601. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2602. return $this->_securePort;
  2603. }
  2604. public function setSecurePort($value)
  2605. {
  2606. $this->_securePort=(int)$value;
  2607. $this->_hostInfo=null;
  2608. }
  2609. public function getCookies()
  2610. {
  2611. if($this->_cookies!==null)
  2612. return $this->_cookies;
  2613. else
  2614. return $this->_cookies=new CCookieCollection($this);
  2615. }
  2616. public function redirect($url,$terminate=true,$statusCode=302)
  2617. {
  2618. if(strpos($url,'/')===0 && strpos($url,'//')!==0)
  2619. $url=$this->getHostInfo().$url;
  2620. header('Location: '.$url, true, $statusCode);
  2621. if($terminate)
  2622. Yii::app()->end();
  2623. }
  2624. public static function parseAcceptHeader($header)
  2625. {
  2626. $matches=array();
  2627. $accepts=array();
  2628. // get individual entries with their type, subtype, basetype and params
  2629. preg_match_all('/(?:\G\s?,\s?|^)(\w+|\*)\/(\w+|\*)(?:\+(\w+))?|(?<!^)\G(?:\s?;\s?(\w+)=([\w\.]+))/',$header,$matches);
  2630. // the regexp should (in theory) always return an array of 6 arrays
  2631. if(count($matches)===6)
  2632. {
  2633. $i=0;
  2634. $itemLen=count($matches[1]);
  2635. while($i<$itemLen)
  2636. {
  2637. // fill out a content type
  2638. $accept=array(
  2639. 'type'=>$matches[1][$i],
  2640. 'subType'=>$matches[2][$i],
  2641. 'baseType'=>null,
  2642. 'params'=>array(),
  2643. );
  2644. // fill in the base type if it exists
  2645. if($matches[3][$i]!==null && $matches[3][$i]!=='')
  2646. $accept['baseType']=$matches[3][$i];
  2647. // continue looping while there is no new content type, to fill in all accompanying params
  2648. for($i++;$i<$itemLen;$i++)
  2649. {
  2650. // if the next content type is null, then the item is a param for the current content type
  2651. if($matches[1][$i]===null || $matches[1][$i]==='')
  2652. {
  2653. // if this is the quality param, convert it to a double
  2654. if($matches[4][$i]==='q')
  2655. {
  2656. // sanity check on q value
  2657. $q=(double)$matches[5][$i];
  2658. if($q>1)
  2659. $q=(double)1;
  2660. elseif($q<0)
  2661. $q=(double)0;
  2662. $accept['params'][$matches[4][$i]]=$q;
  2663. }
  2664. else
  2665. $accept['params'][$matches[4][$i]]=$matches[5][$i];
  2666. }
  2667. else
  2668. break;
  2669. }
  2670. // q defaults to 1 if not explicitly given
  2671. if(!isset($accept['params']['q']))
  2672. $accept['params']['q']=(double)1;
  2673. $accepts[] = $accept;
  2674. }
  2675. }
  2676. return $accepts;
  2677. }
  2678. public static function compareAcceptTypes($a,$b)
  2679. {
  2680. // check for equal quality first
  2681. if($a['params']['q']===$b['params']['q'])
  2682. if(!($a['type']==='*' xor $b['type']==='*'))
  2683. if (!($a['subType']==='*' xor $b['subType']==='*'))
  2684. // finally, higher number of parameters counts as greater precedence
  2685. if(count($a['params'])===count($b['params']))
  2686. return 0;
  2687. else
  2688. return count($a['params'])<count($b['params']) ? 1 : -1;
  2689. // more specific takes precedence - whichever one doesn't have a * subType
  2690. else
  2691. return $a['subType']==='*' ? 1 : -1;
  2692. // more specific takes precedence - whichever one doesn't have a * type
  2693. else
  2694. return $a['type']==='*' ? 1 : -1;
  2695. else
  2696. return ($a['params']['q']<$b['params']['q']) ? 1 : -1;
  2697. }
  2698. public function getPreferredAcceptTypes()
  2699. {
  2700. if($this->_preferredAcceptTypes===null)
  2701. {
  2702. $accepts=self::parseAcceptHeader($this->getAcceptTypes());
  2703. usort($accepts,array(get_class($this),'compareAcceptTypes'));
  2704. $this->_preferredAcceptTypes=$accepts;
  2705. }
  2706. return $this->_preferredAcceptTypes;
  2707. }
  2708. public function getPreferredAcceptType()
  2709. {
  2710. $preferredAcceptTypes=$this->getPreferredAcceptTypes();
  2711. return empty($preferredAcceptTypes) ? false : $preferredAcceptTypes[0];
  2712. }
  2713. public function getPreferredLanguages()
  2714. {
  2715. if($this->_preferredLanguages===null)
  2716. {
  2717. $sortedLanguages=array();
  2718. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $n=preg_match_all('/([\w\-_]+)(?:\s*;\s*q\s*=\s*(\d*\.?\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))
  2719. {
  2720. $languages=array();
  2721. for($i=0;$i<$n;++$i)
  2722. {
  2723. $q=$matches[2][$i];
  2724. if($q==='')
  2725. $q=1;
  2726. if($q)
  2727. $languages[]=array((float)$q,$matches[1][$i]);
  2728. }
  2729. usort($languages,create_function('$a,$b','if($a[0]==$b[0]) {return 0;} return ($a[0]<$b[0]) ? 1 : -1;'));
  2730. foreach($languages as $language)
  2731. $sortedLanguages[]=$language[1];
  2732. }
  2733. $this->_preferredLanguages=$sortedLanguages;
  2734. }
  2735. return $this->_preferredLanguages;
  2736. }
  2737. public function getPreferredLanguage()
  2738. {
  2739. $preferredLanguages=$this->getPreferredLanguages();
  2740. return !empty($preferredLanguages) ? CLocale::getCanonicalID($preferredLanguages[0]) : false;
  2741. }
  2742. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2743. {
  2744. if($mimeType===null)
  2745. {
  2746. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2747. $mimeType='text/plain';
  2748. }
  2749. $fileSize=(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content));
  2750. $contentStart=0;
  2751. $contentEnd=$fileSize-1;
  2752. if(isset($_SERVER['HTTP_RANGE']))
  2753. {
  2754. header('Accept-Ranges: bytes');
  2755. //client sent us a multibyte range, can not hold this one for now
  2756. if(strpos($_SERVER['HTTP_RANGE'],',')!==false)
  2757. {
  2758. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2759. throw new CHttpException(416,'Requested Range Not Satisfiable');
  2760. }
  2761. $range=str_replace('bytes=','',$_SERVER['HTTP_RANGE']);
  2762. //range requests starts from "-", so it means that data must be dumped the end point.
  2763. if($range[0]==='-')
  2764. $contentStart=$fileSize-substr($range,1);
  2765. else
  2766. {
  2767. $range=explode('-',$range);
  2768. $contentStart=$range[0];
  2769. // check if the last-byte-pos presents in header
  2770. if((isset($range[1]) && is_numeric($range[1])))
  2771. $contentEnd=$range[1];
  2772. }
  2773. /* Check the range and make sure it's treated according to the specs.
  2774. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  2775. */
  2776. // End bytes can not be larger than $end.
  2777. $contentEnd=($contentEnd > $fileSize) ? $fileSize-1 : $contentEnd;
  2778. // Validate the requested range and return an error if it's not correct.
  2779. $wrongContentStart=($contentStart>$contentEnd || $contentStart>$fileSize-1 || $contentStart<0);
  2780. if($wrongContentStart)
  2781. {
  2782. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2783. throw new CHttpException(416,'Requested Range Not Satisfiable');
  2784. }
  2785. header('HTTP/1.1 206 Partial Content');
  2786. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2787. }
  2788. else
  2789. header('HTTP/1.1 200 OK');
  2790. $length=$contentEnd-$contentStart+1; // Calculate new content length
  2791. header('Pragma: public');
  2792. header('Expires: 0');
  2793. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2794. header("Content-Type: $mimeType");
  2795. header('Content-Length: '.$length);
  2796. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2797. header('Content-Transfer-Encoding: binary');
  2798. $content=function_exists('mb_substr') ? mb_substr($content,$contentStart,$length) : substr($content,$contentStart,$length);
  2799. if($terminate)
  2800. {
  2801. // clean up the application first because the file downloading could take long time
  2802. // which may cause timeout of some resources (such as DB connection)
  2803. ob_start();
  2804. Yii::app()->end(0,false);
  2805. ob_end_clean();
  2806. echo $content;
  2807. exit(0);
  2808. }
  2809. else
  2810. echo $content;
  2811. }
  2812. public function xSendFile($filePath, $options=array())
  2813. {
  2814. if(!isset($options['forceDownload']) || $options['forceDownload'])
  2815. $disposition='attachment';
  2816. else
  2817. $disposition='inline';
  2818. if(!isset($options['saveName']))
  2819. $options['saveName']=basename($filePath);
  2820. if(!isset($options['mimeType']))
  2821. {
  2822. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2823. $options['mimeType']='text/plain';
  2824. }
  2825. if(!isset($options['xHeader']))
  2826. $options['xHeader']='X-Sendfile';
  2827. if($options['mimeType']!==null)
  2828. header('Content-Type: '.$options['mimeType']);
  2829. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  2830. if(isset($options['addHeaders']))
  2831. {
  2832. foreach($options['addHeaders'] as $header=>$value)
  2833. header($header.': '.$value);
  2834. }
  2835. header(trim($options['xHeader']).': '.$filePath);
  2836. if(!isset($options['terminate']) || $options['terminate'])
  2837. Yii::app()->end();
  2838. }
  2839. public function getCsrfToken()
  2840. {
  2841. if($this->_csrfToken===null)
  2842. {
  2843. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2844. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2845. {
  2846. $cookie=$this->createCsrfCookie();
  2847. $this->_csrfToken=$cookie->value;
  2848. $this->getCookies()->add($cookie->name,$cookie);
  2849. }
  2850. }
  2851. return $this->_csrfToken;
  2852. }
  2853. protected function createCsrfCookie()
  2854. {
  2855. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2856. if(is_array($this->csrfCookie))
  2857. {
  2858. foreach($this->csrfCookie as $name=>$value)
  2859. $cookie->$name=$value;
  2860. }
  2861. return $cookie;
  2862. }
  2863. public function validateCsrfToken($event)
  2864. {
  2865. if ($this->getIsPostRequest() ||
  2866. $this->getIsPutRequest() ||
  2867. $this->getIsDeleteRequest())
  2868. {
  2869. $cookies=$this->getCookies();
  2870. $method=$this->getRequestType();
  2871. switch($method)
  2872. {
  2873. case 'POST':
  2874. $userToken=$this->getPost($this->csrfTokenName);
  2875. break;
  2876. case 'PUT':
  2877. $userToken=$this->getPut($this->csrfTokenName);
  2878. break;
  2879. case 'DELETE':
  2880. $userToken=$this->getDelete($this->csrfTokenName);
  2881. }
  2882. if (!empty($userToken) && $cookies->contains($this->csrfTokenName))
  2883. {
  2884. $cookieToken=$cookies->itemAt($this->csrfTokenName)->value;
  2885. $valid=$cookieToken===$userToken;
  2886. }
  2887. else
  2888. $valid = false;
  2889. if (!$valid)
  2890. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2891. }
  2892. }
  2893. }
  2894. class CCookieCollection extends CMap
  2895. {
  2896. private $_request;
  2897. private $_initialized=false;
  2898. public function __construct(CHttpRequest $request)
  2899. {
  2900. $this->_request=$request;
  2901. $this->copyfrom($this->getCookies());
  2902. $this->_initialized=true;
  2903. }
  2904. public function getRequest()
  2905. {
  2906. return $this->_request;
  2907. }
  2908. protected function getCookies()
  2909. {
  2910. $cookies=array();
  2911. if($this->_request->enableCookieValidation)
  2912. {
  2913. $sm=Yii::app()->getSecurityManager();
  2914. foreach($_COOKIE as $name=>$value)
  2915. {
  2916. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  2917. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  2918. }
  2919. }
  2920. else
  2921. {
  2922. foreach($_COOKIE as $name=>$value)
  2923. $cookies[$name]=new CHttpCookie($name,$value);
  2924. }
  2925. return $cookies;
  2926. }
  2927. public function add($name,$cookie)
  2928. {
  2929. if($cookie instanceof CHttpCookie)
  2930. {
  2931. $this->remove($name);
  2932. parent::add($name,$cookie);
  2933. if($this->_initialized)
  2934. $this->addCookie($cookie);
  2935. }
  2936. else
  2937. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  2938. }
  2939. public function remove($name,$options=array())
  2940. {
  2941. if(($cookie=parent::remove($name))!==null)
  2942. {
  2943. if($this->_initialized)
  2944. {
  2945. $cookie->configure($options);
  2946. $this->removeCookie($cookie);
  2947. }
  2948. }
  2949. return $cookie;
  2950. }
  2951. protected function addCookie($cookie)
  2952. {
  2953. $value=$cookie->value;
  2954. if($this->_request->enableCookieValidation)
  2955. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  2956. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2957. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2958. else
  2959. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  2960. }
  2961. protected function removeCookie($cookie)
  2962. {
  2963. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2964. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2965. else
  2966. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure);
  2967. }
  2968. }
  2969. class CUrlManager extends CApplicationComponent
  2970. {
  2971. const CACHE_KEY='Yii.CUrlManager.rules';
  2972. const GET_FORMAT='get';
  2973. const PATH_FORMAT='path';
  2974. public $rules=array();
  2975. public $urlSuffix='';
  2976. public $showScriptName=true;
  2977. public $appendParams=true;
  2978. public $routeVar='r';
  2979. public $caseSensitive=true;
  2980. public $matchValue=false;
  2981. public $cacheID='cache';
  2982. public $useStrictParsing=false;
  2983. public $urlRuleClass='CUrlRule';
  2984. private $_urlFormat=self::GET_FORMAT;
  2985. private $_rules=array();
  2986. private $_baseUrl;
  2987. public function init()
  2988. {
  2989. parent::init();
  2990. $this->processRules();
  2991. }
  2992. protected function processRules()
  2993. {
  2994. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  2995. return;
  2996. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  2997. {
  2998. $hash=md5(serialize($this->rules));
  2999. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  3000. {
  3001. $this->_rules=$data[0];
  3002. return;
  3003. }
  3004. }
  3005. foreach($this->rules as $pattern=>$route)
  3006. $this->_rules[]=$this->createUrlRule($route,$pattern);
  3007. if(isset($cache))
  3008. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  3009. }
  3010. public function addRules($rules,$append=true)
  3011. {
  3012. if ($append)
  3013. {
  3014. foreach($rules as $pattern=>$route)
  3015. $this->_rules[]=$this->createUrlRule($route,$pattern);
  3016. }
  3017. else
  3018. {
  3019. $rules=array_reverse($rules);
  3020. foreach($rules as $pattern=>$route)
  3021. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  3022. }
  3023. }
  3024. protected function createUrlRule($route,$pattern)
  3025. {
  3026. if(is_array($route) && isset($route['class']))
  3027. return $route;
  3028. else
  3029. {
  3030. $urlRuleClass=Yii::import($this->urlRuleClass,true);
  3031. return new $urlRuleClass($route,$pattern);
  3032. }
  3033. }
  3034. public function createUrl($route,$params=array(),$ampersand='&')
  3035. {
  3036. unset($params[$this->routeVar]);
  3037. foreach($params as $i=>$param)
  3038. if($param===null)
  3039. $params[$i]='';
  3040. if(isset($params['#']))
  3041. {
  3042. $anchor='#'.$params['#'];
  3043. unset($params['#']);
  3044. }
  3045. else
  3046. $anchor='';
  3047. $route=trim($route,'/');
  3048. foreach($this->_rules as $i=>$rule)
  3049. {
  3050. if(is_array($rule))
  3051. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  3052. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  3053. {
  3054. if($rule->hasHostInfo)
  3055. return $url==='' ? '/'.$anchor : $url.$anchor;
  3056. else
  3057. return $this->getBaseUrl().'/'.$url.$anchor;
  3058. }
  3059. }
  3060. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  3061. }
  3062. protected function createUrlDefault($route,$params,$ampersand)
  3063. {
  3064. if($this->getUrlFormat()===self::PATH_FORMAT)
  3065. {
  3066. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  3067. if($this->appendParams)
  3068. {
  3069. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  3070. return $route==='' ? $url : $url.$this->urlSuffix;
  3071. }
  3072. else
  3073. {
  3074. if($route!=='')
  3075. $url.=$this->urlSuffix;
  3076. $query=$this->createPathInfo($params,'=',$ampersand);
  3077. return $query==='' ? $url : $url.'?'.$query;
  3078. }
  3079. }
  3080. else
  3081. {
  3082. $url=$this->getBaseUrl();
  3083. if(!$this->showScriptName)
  3084. $url.='/';
  3085. if($route!=='')
  3086. {
  3087. $url.='?'.$this->routeVar.'='.$route;
  3088. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  3089. $url.=$ampersand.$query;
  3090. }
  3091. elseif(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  3092. $url.='?'.$query;
  3093. return $url;
  3094. }
  3095. }
  3096. public function parseUrl($request)
  3097. {
  3098. if($this->getUrlFormat()===self::PATH_FORMAT)
  3099. {
  3100. $rawPathInfo=$request->getPathInfo();
  3101. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3102. foreach($this->_rules as $i=>$rule)
  3103. {
  3104. if(is_array($rule))
  3105. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  3106. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  3107. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  3108. }
  3109. if($this->useStrictParsing)
  3110. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  3111. array('{route}'=>$pathInfo)));
  3112. else
  3113. return $pathInfo;
  3114. }
  3115. elseif(isset($_GET[$this->routeVar]))
  3116. return $_GET[$this->routeVar];
  3117. elseif(isset($_POST[$this->routeVar]))
  3118. return $_POST[$this->routeVar];
  3119. else
  3120. return '';
  3121. }
  3122. public function parsePathInfo($pathInfo)
  3123. {
  3124. if($pathInfo==='')
  3125. return;
  3126. $segs=explode('/',$pathInfo.'/');
  3127. $n=count($segs);
  3128. for($i=0;$i<$n-1;$i+=2)
  3129. {
  3130. $key=$segs[$i];
  3131. if($key==='') continue;
  3132. $value=$segs[$i+1];
  3133. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  3134. {
  3135. $name=substr($key,0,$pos);
  3136. for($j=$m-1;$j>=0;--$j)
  3137. {
  3138. if($matches[1][$j]==='')
  3139. $value=array($value);
  3140. else
  3141. $value=array($matches[1][$j]=>$value);
  3142. }
  3143. if(isset($_GET[$name]) && is_array($_GET[$name]))
  3144. $value=CMap::mergeArray($_GET[$name],$value);
  3145. $_REQUEST[$name]=$_GET[$name]=$value;
  3146. }
  3147. else
  3148. $_REQUEST[$key]=$_GET[$key]=$value;
  3149. }
  3150. }
  3151. public function createPathInfo($params,$equal,$ampersand, $key=null)
  3152. {
  3153. $pairs = array();
  3154. foreach($params as $k => $v)
  3155. {
  3156. if ($key!==null)
  3157. $k = $key.'['.$k.']';
  3158. if (is_array($v))
  3159. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  3160. else
  3161. $pairs[]=urlencode($k).$equal.urlencode($v);
  3162. }
  3163. return implode($ampersand,$pairs);
  3164. }
  3165. public function removeUrlSuffix($pathInfo,$urlSuffix)
  3166. {
  3167. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  3168. return substr($pathInfo,0,-strlen($urlSuffix));
  3169. else
  3170. return $pathInfo;
  3171. }
  3172. public function getBaseUrl()
  3173. {
  3174. if($this->_baseUrl!==null)
  3175. return $this->_baseUrl;
  3176. else
  3177. {
  3178. if($this->showScriptName)
  3179. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  3180. else
  3181. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  3182. return $this->_baseUrl;
  3183. }
  3184. }
  3185. public function setBaseUrl($value)
  3186. {
  3187. $this->_baseUrl=$value;
  3188. }
  3189. public function getUrlFormat()
  3190. {
  3191. return $this->_urlFormat;
  3192. }
  3193. public function setUrlFormat($value)
  3194. {
  3195. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  3196. $this->_urlFormat=$value;
  3197. else
  3198. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  3199. }
  3200. }
  3201. abstract class CBaseUrlRule extends CComponent
  3202. {
  3203. public $hasHostInfo=false;
  3204. abstract public function createUrl($manager,$route,$params,$ampersand);
  3205. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  3206. }
  3207. class CUrlRule extends CBaseUrlRule
  3208. {
  3209. public $urlSuffix;
  3210. public $caseSensitive;
  3211. public $defaultParams=array();
  3212. public $matchValue;
  3213. public $verb;
  3214. public $parsingOnly=false;
  3215. public $route;
  3216. public $references=array();
  3217. public $routePattern;
  3218. public $pattern;
  3219. public $template;
  3220. public $params=array();
  3221. public $append;
  3222. public $hasHostInfo;
  3223. public function __construct($route,$pattern)
  3224. {
  3225. if(is_array($route))
  3226. {
  3227. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  3228. {
  3229. if(isset($route[$name]))
  3230. $this->$name=$route[$name];
  3231. }
  3232. if(isset($route['pattern']))
  3233. $pattern=$route['pattern'];
  3234. $route=$route[0];
  3235. }
  3236. $this->route=trim($route,'/');
  3237. $tr2['/']=$tr['/']='\\/';
  3238. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  3239. {
  3240. foreach($matches2[1] as $name)
  3241. $this->references[$name]="<$name>";
  3242. }
  3243. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  3244. if($this->verb!==null)
  3245. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  3246. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  3247. {
  3248. $tokens=array_combine($matches[1],$matches[2]);
  3249. foreach($tokens as $name=>$value)
  3250. {
  3251. if($value==='')
  3252. $value='[^\/]+';
  3253. $tr["<$name>"]="(?P<$name>$value)";
  3254. if(isset($this->references[$name]))
  3255. $tr2["<$name>"]=$tr["<$name>"];
  3256. else
  3257. $this->params[$name]=$value;
  3258. }
  3259. }
  3260. $p=rtrim($pattern,'*');
  3261. $this->append=$p!==$pattern;
  3262. $p=trim($p,'/');
  3263. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  3264. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  3265. if($this->append)
  3266. $this->pattern.='/u';
  3267. else
  3268. $this->pattern.='$/u';
  3269. if($this->references!==array())
  3270. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  3271. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  3272. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  3273. array('{route}'=>$route,'{pattern}'=>$pattern)));
  3274. }
  3275. public function createUrl($manager,$route,$params,$ampersand)
  3276. {
  3277. if($this->parsingOnly)
  3278. return false;
  3279. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3280. $case='';
  3281. else
  3282. $case='i';
  3283. $tr=array();
  3284. if($route!==$this->route)
  3285. {
  3286. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  3287. {
  3288. foreach($this->references as $key=>$name)
  3289. $tr[$name]=$matches[$key];
  3290. }
  3291. else
  3292. return false;
  3293. }
  3294. foreach($this->defaultParams as $key=>$value)
  3295. {
  3296. if(isset($params[$key]))
  3297. {
  3298. if($params[$key]==$value)
  3299. unset($params[$key]);
  3300. else
  3301. return false;
  3302. }
  3303. }
  3304. foreach($this->params as $key=>$value)
  3305. if(!isset($params[$key]))
  3306. return false;
  3307. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  3308. {
  3309. foreach($this->params as $key=>$value)
  3310. {
  3311. if(!preg_match('/\A'.$value.'\z/u'.$case,$params[$key]))
  3312. return false;
  3313. }
  3314. }
  3315. foreach($this->params as $key=>$value)
  3316. {
  3317. $tr["<$key>"]=urlencode($params[$key]);
  3318. unset($params[$key]);
  3319. }
  3320. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3321. $url=strtr($this->template,$tr);
  3322. if($this->hasHostInfo)
  3323. {
  3324. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  3325. if(stripos($url,$hostInfo)===0)
  3326. $url=substr($url,strlen($hostInfo));
  3327. }
  3328. if(empty($params))
  3329. return $url!=='' ? $url.$suffix : $url;
  3330. if($this->append)
  3331. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  3332. else
  3333. {
  3334. if($url!=='')
  3335. $url.=$suffix;
  3336. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  3337. }
  3338. return $url;
  3339. }
  3340. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  3341. {
  3342. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  3343. return false;
  3344. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3345. $case='';
  3346. else
  3347. $case='i';
  3348. if($this->urlSuffix!==null)
  3349. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3350. // URL suffix required, but not found in the requested URL
  3351. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3352. {
  3353. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3354. if($urlSuffix!='' && $urlSuffix!=='/')
  3355. return false;
  3356. }
  3357. if($this->hasHostInfo)
  3358. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3359. $pathInfo.='/';
  3360. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3361. {
  3362. foreach($this->defaultParams as $name=>$value)
  3363. {
  3364. if(!isset($_GET[$name]))
  3365. $_REQUEST[$name]=$_GET[$name]=$value;
  3366. }
  3367. $tr=array();
  3368. foreach($matches as $key=>$value)
  3369. {
  3370. if(isset($this->references[$key]))
  3371. $tr[$this->references[$key]]=$value;
  3372. elseif(isset($this->params[$key]))
  3373. $_REQUEST[$key]=$_GET[$key]=$value;
  3374. }
  3375. if($pathInfo!==$matches[0]) // there're additional GET params
  3376. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3377. if($this->routePattern!==null)
  3378. return strtr($this->route,$tr);
  3379. else
  3380. return $this->route;
  3381. }
  3382. else
  3383. return false;
  3384. }
  3385. }
  3386. abstract class CBaseController extends CComponent
  3387. {
  3388. private $_widgetStack=array();
  3389. abstract public function getViewFile($viewName);
  3390. public function renderFile($viewFile,$data=null,$return=false)
  3391. {
  3392. $widgetCount=count($this->_widgetStack);
  3393. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3394. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3395. else
  3396. $content=$this->renderInternal($viewFile,$data,$return);
  3397. if(count($this->_widgetStack)===$widgetCount)
  3398. return $content;
  3399. else
  3400. {
  3401. $widget=end($this->_widgetStack);
  3402. 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.',
  3403. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3404. }
  3405. }
  3406. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3407. {
  3408. // we use special variable names here to avoid conflict when extracting data
  3409. if(is_array($_data_))
  3410. extract($_data_,EXTR_PREFIX_SAME,'data');
  3411. else
  3412. $data=$_data_;
  3413. if($_return_)
  3414. {
  3415. ob_start();
  3416. ob_implicit_flush(false);
  3417. require($_viewFile_);
  3418. return ob_get_clean();
  3419. }
  3420. else
  3421. require($_viewFile_);
  3422. }
  3423. public function createWidget($className,$properties=array())
  3424. {
  3425. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3426. $widget->init();
  3427. return $widget;
  3428. }
  3429. public function widget($className,$properties=array(),$captureOutput=false)
  3430. {
  3431. if($captureOutput)
  3432. {
  3433. ob_start();
  3434. ob_implicit_flush(false);
  3435. $widget=$this->createWidget($className,$properties);
  3436. $widget->run();
  3437. return ob_get_clean();
  3438. }
  3439. else
  3440. {
  3441. $widget=$this->createWidget($className,$properties);
  3442. $widget->run();
  3443. return $widget;
  3444. }
  3445. }
  3446. public function beginWidget($className,$properties=array())
  3447. {
  3448. $widget=$this->createWidget($className,$properties);
  3449. $this->_widgetStack[]=$widget;
  3450. return $widget;
  3451. }
  3452. public function endWidget($id='')
  3453. {
  3454. if(($widget=array_pop($this->_widgetStack))!==null)
  3455. {
  3456. $widget->run();
  3457. return $widget;
  3458. }
  3459. else
  3460. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3461. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3462. }
  3463. public function beginClip($id,$properties=array())
  3464. {
  3465. $properties['id']=$id;
  3466. $this->beginWidget('CClipWidget',$properties);
  3467. }
  3468. public function endClip()
  3469. {
  3470. $this->endWidget('CClipWidget');
  3471. }
  3472. public function beginCache($id,$properties=array())
  3473. {
  3474. $properties['id']=$id;
  3475. $cache=$this->beginWidget('COutputCache',$properties);
  3476. if($cache->getIsContentCached())
  3477. {
  3478. $this->endCache();
  3479. return false;
  3480. }
  3481. else
  3482. return true;
  3483. }
  3484. public function endCache()
  3485. {
  3486. $this->endWidget('COutputCache');
  3487. }
  3488. public function beginContent($view=null,$data=array())
  3489. {
  3490. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3491. }
  3492. public function endContent()
  3493. {
  3494. $this->endWidget('CContentDecorator');
  3495. }
  3496. }
  3497. class CController extends CBaseController
  3498. {
  3499. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3500. public $layout;
  3501. public $defaultAction='index';
  3502. private $_id;
  3503. private $_action;
  3504. private $_pageTitle;
  3505. private $_cachingStack;
  3506. private $_clips;
  3507. private $_dynamicOutput;
  3508. private $_pageStates;
  3509. private $_module;
  3510. public function __construct($id,$module=null)
  3511. {
  3512. $this->_id=$id;
  3513. $this->_module=$module;
  3514. $this->attachBehaviors($this->behaviors());
  3515. }
  3516. public function init()
  3517. {
  3518. }
  3519. public function filters()
  3520. {
  3521. return array();
  3522. }
  3523. public function actions()
  3524. {
  3525. return array();
  3526. }
  3527. public function behaviors()
  3528. {
  3529. return array();
  3530. }
  3531. public function accessRules()
  3532. {
  3533. return array();
  3534. }
  3535. public function run($actionID)
  3536. {
  3537. if(($action=$this->createAction($actionID))!==null)
  3538. {
  3539. if(($parent=$this->getModule())===null)
  3540. $parent=Yii::app();
  3541. if($parent->beforeControllerAction($this,$action))
  3542. {
  3543. $this->runActionWithFilters($action,$this->filters());
  3544. $parent->afterControllerAction($this,$action);
  3545. }
  3546. }
  3547. else
  3548. $this->missingAction($actionID);
  3549. }
  3550. public function runActionWithFilters($action,$filters)
  3551. {
  3552. if(empty($filters))
  3553. $this->runAction($action);
  3554. else
  3555. {
  3556. $priorAction=$this->_action;
  3557. $this->_action=$action;
  3558. CFilterChain::create($this,$action,$filters)->run();
  3559. $this->_action=$priorAction;
  3560. }
  3561. }
  3562. public function runAction($action)
  3563. {
  3564. $priorAction=$this->_action;
  3565. $this->_action=$action;
  3566. if($this->beforeAction($action))
  3567. {
  3568. if($action->runWithParams($this->getActionParams())===false)
  3569. $this->invalidActionParams($action);
  3570. else
  3571. $this->afterAction($action);
  3572. }
  3573. $this->_action=$priorAction;
  3574. }
  3575. public function getActionParams()
  3576. {
  3577. return $_GET;
  3578. }
  3579. public function invalidActionParams($action)
  3580. {
  3581. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3582. }
  3583. public function processOutput($output)
  3584. {
  3585. Yii::app()->getClientScript()->render($output);
  3586. // if using page caching, we should delay dynamic output replacement
  3587. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3588. {
  3589. $output=$this->processDynamicOutput($output);
  3590. $this->_dynamicOutput=null;
  3591. }
  3592. if($this->_pageStates===null)
  3593. $this->_pageStates=$this->loadPageStates();
  3594. if(!empty($this->_pageStates))
  3595. $this->savePageStates($this->_pageStates,$output);
  3596. return $output;
  3597. }
  3598. public function processDynamicOutput($output)
  3599. {
  3600. if($this->_dynamicOutput)
  3601. {
  3602. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3603. }
  3604. return $output;
  3605. }
  3606. protected function replaceDynamicOutput($matches)
  3607. {
  3608. $content=$matches[0];
  3609. if(isset($this->_dynamicOutput[$matches[1]]))
  3610. {
  3611. $content=$this->_dynamicOutput[$matches[1]];
  3612. $this->_dynamicOutput[$matches[1]]=null;
  3613. }
  3614. return $content;
  3615. }
  3616. public function createAction($actionID)
  3617. {
  3618. if($actionID==='')
  3619. $actionID=$this->defaultAction;
  3620. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3621. return new CInlineAction($this,$actionID);
  3622. else
  3623. {
  3624. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3625. if($action!==null && !method_exists($action,'run'))
  3626. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3627. return $action;
  3628. }
  3629. }
  3630. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3631. {
  3632. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3633. {
  3634. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3635. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3636. }
  3637. elseif($pos===false)
  3638. return null;
  3639. // the action is defined in a provider
  3640. $prefix=substr($actionID,0,$pos+1);
  3641. if(!isset($actionMap[$prefix]))
  3642. return null;
  3643. $actionID=(string)substr($actionID,$pos+1);
  3644. $provider=$actionMap[$prefix];
  3645. if(is_string($provider))
  3646. $providerType=$provider;
  3647. elseif(is_array($provider) && isset($provider['class']))
  3648. {
  3649. $providerType=$provider['class'];
  3650. if(isset($provider[$actionID]))
  3651. {
  3652. if(is_string($provider[$actionID]))
  3653. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3654. else
  3655. $config=array_merge($provider[$actionID],$config);
  3656. }
  3657. }
  3658. else
  3659. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3660. $class=Yii::import($providerType,true);
  3661. $map=call_user_func(array($class,'actions'));
  3662. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3663. }
  3664. public function missingAction($actionID)
  3665. {
  3666. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3667. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3668. }
  3669. public function getAction()
  3670. {
  3671. return $this->_action;
  3672. }
  3673. public function setAction($value)
  3674. {
  3675. $this->_action=$value;
  3676. }
  3677. public function getId()
  3678. {
  3679. return $this->_id;
  3680. }
  3681. public function getUniqueId()
  3682. {
  3683. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3684. }
  3685. public function getRoute()
  3686. {
  3687. if(($action=$this->getAction())!==null)
  3688. return $this->getUniqueId().'/'.$action->getId();
  3689. else
  3690. return $this->getUniqueId();
  3691. }
  3692. public function getModule()
  3693. {
  3694. return $this->_module;
  3695. }
  3696. public function getViewPath()
  3697. {
  3698. if(($module=$this->getModule())===null)
  3699. $module=Yii::app();
  3700. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3701. }
  3702. public function getViewFile($viewName)
  3703. {
  3704. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3705. return $viewFile;
  3706. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3707. if(($module=$this->getModule())!==null)
  3708. $moduleViewPath=$module->getViewPath();
  3709. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3710. }
  3711. public function getLayoutFile($layoutName)
  3712. {
  3713. if($layoutName===false)
  3714. return false;
  3715. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3716. return $layoutFile;
  3717. if(empty($layoutName))
  3718. {
  3719. $module=$this->getModule();
  3720. while($module!==null)
  3721. {
  3722. if($module->layout===false)
  3723. return false;
  3724. if(!empty($module->layout))
  3725. break;
  3726. $module=$module->getParentModule();
  3727. }
  3728. if($module===null)
  3729. $module=Yii::app();
  3730. $layoutName=$module->layout;
  3731. }
  3732. elseif(($module=$this->getModule())===null)
  3733. $module=Yii::app();
  3734. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3735. }
  3736. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3737. {
  3738. if(empty($viewName))
  3739. return false;
  3740. if($moduleViewPath===null)
  3741. $moduleViewPath=$basePath;
  3742. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3743. $extension=$renderer->fileExtension;
  3744. else
  3745. $extension='.php';
  3746. if($viewName[0]==='/')
  3747. {
  3748. if(strncmp($viewName,'//',2)===0)
  3749. $viewFile=$basePath.$viewName;
  3750. else
  3751. $viewFile=$moduleViewPath.$viewName;
  3752. }
  3753. elseif(strpos($viewName,'.'))
  3754. $viewFile=Yii::getPathOfAlias($viewName);
  3755. else
  3756. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3757. if(is_file($viewFile.$extension))
  3758. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3759. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  3760. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3761. else
  3762. return false;
  3763. }
  3764. public function getClips()
  3765. {
  3766. if($this->_clips!==null)
  3767. return $this->_clips;
  3768. else
  3769. return $this->_clips=new CMap;
  3770. }
  3771. public function forward($route,$exit=true)
  3772. {
  3773. if(strpos($route,'/')===false)
  3774. $this->run($route);
  3775. else
  3776. {
  3777. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3778. $route=$module->getId().'/'.$route;
  3779. Yii::app()->runController($route);
  3780. }
  3781. if($exit)
  3782. Yii::app()->end();
  3783. }
  3784. public function render($view,$data=null,$return=false)
  3785. {
  3786. if($this->beforeRender($view))
  3787. {
  3788. $output=$this->renderPartial($view,$data,true);
  3789. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3790. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3791. $this->afterRender($view,$output);
  3792. $output=$this->processOutput($output);
  3793. if($return)
  3794. return $output;
  3795. else
  3796. echo $output;
  3797. }
  3798. }
  3799. protected function beforeRender($view)
  3800. {
  3801. return true;
  3802. }
  3803. protected function afterRender($view, &$output)
  3804. {
  3805. }
  3806. public function renderText($text,$return=false)
  3807. {
  3808. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3809. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3810. $text=$this->processOutput($text);
  3811. if($return)
  3812. return $text;
  3813. else
  3814. echo $text;
  3815. }
  3816. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3817. {
  3818. if(($viewFile=$this->getViewFile($view))!==false)
  3819. {
  3820. $output=$this->renderFile($viewFile,$data,true);
  3821. if($processOutput)
  3822. $output=$this->processOutput($output);
  3823. if($return)
  3824. return $output;
  3825. else
  3826. echo $output;
  3827. }
  3828. else
  3829. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3830. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3831. }
  3832. public function renderClip($name,$params=array(),$return=false)
  3833. {
  3834. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  3835. if($return)
  3836. return $text;
  3837. else
  3838. echo $text;
  3839. }
  3840. public function renderDynamic($callback)
  3841. {
  3842. $n=count($this->_dynamicOutput);
  3843. echo "<###dynamic-$n###>";
  3844. $params=func_get_args();
  3845. array_shift($params);
  3846. $this->renderDynamicInternal($callback,$params);
  3847. }
  3848. public function renderDynamicInternal($callback,$params)
  3849. {
  3850. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3851. if(is_string($callback) && method_exists($this,$callback))
  3852. $callback=array($this,$callback);
  3853. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3854. }
  3855. public function createUrl($route,$params=array(),$ampersand='&')
  3856. {
  3857. if($route==='')
  3858. $route=$this->getId().'/'.$this->getAction()->getId();
  3859. elseif(strpos($route,'/')===false)
  3860. $route=$this->getId().'/'.$route;
  3861. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3862. $route=$module->getId().'/'.$route;
  3863. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3864. }
  3865. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3866. {
  3867. $url=$this->createUrl($route,$params,$ampersand);
  3868. if(strpos($url,'http')===0)
  3869. return $url;
  3870. else
  3871. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  3872. }
  3873. public function getPageTitle()
  3874. {
  3875. if($this->_pageTitle!==null)
  3876. return $this->_pageTitle;
  3877. else
  3878. {
  3879. $name=ucfirst(basename($this->getId()));
  3880. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3881. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3882. else
  3883. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3884. }
  3885. }
  3886. public function setPageTitle($value)
  3887. {
  3888. $this->_pageTitle=$value;
  3889. }
  3890. public function redirect($url,$terminate=true,$statusCode=302)
  3891. {
  3892. if(is_array($url))
  3893. {
  3894. $route=isset($url[0]) ? $url[0] : '';
  3895. $url=$this->createUrl($route,array_splice($url,1));
  3896. }
  3897. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  3898. }
  3899. public function refresh($terminate=true,$anchor='')
  3900. {
  3901. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  3902. }
  3903. public function recordCachingAction($context,$method,$params)
  3904. {
  3905. if($this->_cachingStack) // record only when there is an active output cache
  3906. {
  3907. foreach($this->_cachingStack as $cache)
  3908. $cache->recordAction($context,$method,$params);
  3909. }
  3910. }
  3911. public function getCachingStack($createIfNull=true)
  3912. {
  3913. if(!$this->_cachingStack)
  3914. $this->_cachingStack=new CStack;
  3915. return $this->_cachingStack;
  3916. }
  3917. public function isCachingStackEmpty()
  3918. {
  3919. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  3920. }
  3921. protected function beforeAction($action)
  3922. {
  3923. return true;
  3924. }
  3925. protected function afterAction($action)
  3926. {
  3927. }
  3928. public function filterPostOnly($filterChain)
  3929. {
  3930. if(Yii::app()->getRequest()->getIsPostRequest())
  3931. $filterChain->run();
  3932. else
  3933. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3934. }
  3935. public function filterAjaxOnly($filterChain)
  3936. {
  3937. if(Yii::app()->getRequest()->getIsAjaxRequest())
  3938. $filterChain->run();
  3939. else
  3940. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3941. }
  3942. public function filterAccessControl($filterChain)
  3943. {
  3944. $filter=new CAccessControlFilter;
  3945. $filter->setRules($this->accessRules());
  3946. $filter->filter($filterChain);
  3947. }
  3948. public function getPageState($name,$defaultValue=null)
  3949. {
  3950. if($this->_pageStates===null)
  3951. $this->_pageStates=$this->loadPageStates();
  3952. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  3953. }
  3954. public function setPageState($name,$value,$defaultValue=null)
  3955. {
  3956. if($this->_pageStates===null)
  3957. $this->_pageStates=$this->loadPageStates();
  3958. if($value===$defaultValue)
  3959. unset($this->_pageStates[$name]);
  3960. else
  3961. $this->_pageStates[$name]=$value;
  3962. $params=func_get_args();
  3963. $this->recordCachingAction('','setPageState',$params);
  3964. }
  3965. public function clearPageStates()
  3966. {
  3967. $this->_pageStates=array();
  3968. }
  3969. protected function loadPageStates()
  3970. {
  3971. if(!empty($_POST[self::STATE_INPUT_NAME]))
  3972. {
  3973. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  3974. {
  3975. if(extension_loaded('zlib'))
  3976. $data=@gzuncompress($data);
  3977. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  3978. return unserialize($data);
  3979. }
  3980. }
  3981. return array();
  3982. }
  3983. protected function savePageStates($states,&$output)
  3984. {
  3985. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  3986. if(extension_loaded('zlib'))
  3987. $data=gzcompress($data);
  3988. $value=base64_encode($data);
  3989. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  3990. }
  3991. }
  3992. abstract class CAction extends CComponent implements IAction
  3993. {
  3994. private $_id;
  3995. private $_controller;
  3996. public function __construct($controller,$id)
  3997. {
  3998. $this->_controller=$controller;
  3999. $this->_id=$id;
  4000. }
  4001. public function getController()
  4002. {
  4003. return $this->_controller;
  4004. }
  4005. public function getId()
  4006. {
  4007. return $this->_id;
  4008. }
  4009. public function runWithParams($params)
  4010. {
  4011. $method=new ReflectionMethod($this, 'run');
  4012. if($method->getNumberOfParameters()>0)
  4013. return $this->runWithParamsInternal($this, $method, $params);
  4014. else
  4015. return $this->run();
  4016. }
  4017. protected function runWithParamsInternal($object, $method, $params)
  4018. {
  4019. $ps=array();
  4020. foreach($method->getParameters() as $i=>$param)
  4021. {
  4022. $name=$param->getName();
  4023. if(isset($params[$name]))
  4024. {
  4025. if($param->isArray())
  4026. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  4027. elseif(!is_array($params[$name]))
  4028. $ps[]=$params[$name];
  4029. else
  4030. return false;
  4031. }
  4032. elseif($param->isDefaultValueAvailable())
  4033. $ps[]=$param->getDefaultValue();
  4034. else
  4035. return false;
  4036. }
  4037. $method->invokeArgs($object,$ps);
  4038. return true;
  4039. }
  4040. }
  4041. class CInlineAction extends CAction
  4042. {
  4043. public function run()
  4044. {
  4045. $method='action'.$this->getId();
  4046. $this->getController()->$method();
  4047. }
  4048. public function runWithParams($params)
  4049. {
  4050. $methodName='action'.$this->getId();
  4051. $controller=$this->getController();
  4052. $method=new ReflectionMethod($controller, $methodName);
  4053. if($method->getNumberOfParameters()>0)
  4054. return $this->runWithParamsInternal($controller, $method, $params);
  4055. else
  4056. return $controller->$methodName();
  4057. }
  4058. }
  4059. class CWebUser extends CApplicationComponent implements IWebUser
  4060. {
  4061. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  4062. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  4063. const STATES_VAR='__states';
  4064. const AUTH_TIMEOUT_VAR='__timeout';
  4065. const AUTH_ABSOLUTE_TIMEOUT_VAR='__absolute_timeout';
  4066. public $allowAutoLogin=false;
  4067. public $guestName='Guest';
  4068. public $loginUrl=array('/site/login');
  4069. public $identityCookie;
  4070. public $authTimeout;
  4071. public $absoluteAuthTimeout;
  4072. public $autoRenewCookie=false;
  4073. public $autoUpdateFlash=true;
  4074. public $loginRequiredAjaxResponse;
  4075. private $_keyPrefix;
  4076. private $_access=array();
  4077. public function __get($name)
  4078. {
  4079. if($this->hasState($name))
  4080. return $this->getState($name);
  4081. else
  4082. return parent::__get($name);
  4083. }
  4084. public function __set($name,$value)
  4085. {
  4086. if($this->hasState($name))
  4087. $this->setState($name,$value);
  4088. else
  4089. parent::__set($name,$value);
  4090. }
  4091. public function __isset($name)
  4092. {
  4093. if($this->hasState($name))
  4094. return $this->getState($name)!==null;
  4095. else
  4096. return parent::__isset($name);
  4097. }
  4098. public function __unset($name)
  4099. {
  4100. if($this->hasState($name))
  4101. $this->setState($name,null);
  4102. else
  4103. parent::__unset($name);
  4104. }
  4105. public function init()
  4106. {
  4107. parent::init();
  4108. Yii::app()->getSession()->open();
  4109. if($this->getIsGuest() && $this->allowAutoLogin)
  4110. $this->restoreFromCookie();
  4111. elseif($this->autoRenewCookie && $this->allowAutoLogin)
  4112. $this->renewCookie();
  4113. if($this->autoUpdateFlash)
  4114. $this->updateFlash();
  4115. $this->updateAuthStatus();
  4116. }
  4117. public function login($identity,$duration=0)
  4118. {
  4119. $id=$identity->getId();
  4120. $states=$identity->getPersistentStates();
  4121. if($this->beforeLogin($id,$states,false))
  4122. {
  4123. $this->changeIdentity($id,$identity->getName(),$states);
  4124. if($duration>0)
  4125. {
  4126. if($this->allowAutoLogin)
  4127. $this->saveToCookie($duration);
  4128. else
  4129. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  4130. array('{class}'=>get_class($this))));
  4131. }
  4132. if ($this->absoluteAuthTimeout)
  4133. $this->setState(self::AUTH_ABSOLUTE_TIMEOUT_VAR, time()+$this->absoluteAuthTimeout);
  4134. $this->afterLogin(false);
  4135. }
  4136. return !$this->getIsGuest();
  4137. }
  4138. public function logout($destroySession=true)
  4139. {
  4140. if($this->beforeLogout())
  4141. {
  4142. if($this->allowAutoLogin)
  4143. {
  4144. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  4145. if($this->identityCookie!==null)
  4146. {
  4147. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4148. $cookie->value=null;
  4149. $cookie->expire=0;
  4150. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  4151. }
  4152. }
  4153. if($destroySession)
  4154. Yii::app()->getSession()->destroy();
  4155. else
  4156. $this->clearStates();
  4157. $this->_access=array();
  4158. $this->afterLogout();
  4159. }
  4160. }
  4161. public function getIsGuest()
  4162. {
  4163. return $this->getState('__id')===null;
  4164. }
  4165. public function getId()
  4166. {
  4167. return $this->getState('__id');
  4168. }
  4169. public function setId($value)
  4170. {
  4171. $this->setState('__id',$value);
  4172. }
  4173. public function getName()
  4174. {
  4175. if(($name=$this->getState('__name'))!==null)
  4176. return $name;
  4177. else
  4178. return $this->guestName;
  4179. }
  4180. public function setName($value)
  4181. {
  4182. $this->setState('__name',$value);
  4183. }
  4184. public function getReturnUrl($defaultUrl=null)
  4185. {
  4186. if($defaultUrl===null)
  4187. {
  4188. $defaultReturnUrl=Yii::app()->getUrlManager()->showScriptName ? Yii::app()->getRequest()->getScriptUrl() : Yii::app()->getRequest()->getBaseUrl().'/';
  4189. }
  4190. else
  4191. {
  4192. $defaultReturnUrl=CHtml::normalizeUrl($defaultUrl);
  4193. }
  4194. return $this->getState('__returnUrl',$defaultReturnUrl);
  4195. }
  4196. public function setReturnUrl($value)
  4197. {
  4198. $this->setState('__returnUrl',$value);
  4199. }
  4200. public function loginRequired()
  4201. {
  4202. $app=Yii::app();
  4203. $request=$app->getRequest();
  4204. if(!$request->getIsAjaxRequest())
  4205. {
  4206. $this->setReturnUrl($request->getUrl());
  4207. if(($url=$this->loginUrl)!==null)
  4208. {
  4209. if(is_array($url))
  4210. {
  4211. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  4212. $url=$app->createUrl($route,array_splice($url,1));
  4213. }
  4214. $request->redirect($url);
  4215. }
  4216. }
  4217. elseif(isset($this->loginRequiredAjaxResponse))
  4218. {
  4219. echo $this->loginRequiredAjaxResponse;
  4220. Yii::app()->end();
  4221. }
  4222. throw new CHttpException(403,Yii::t('yii','Login Required'));
  4223. }
  4224. protected function beforeLogin($id,$states,$fromCookie)
  4225. {
  4226. return true;
  4227. }
  4228. protected function afterLogin($fromCookie)
  4229. {
  4230. }
  4231. protected function beforeLogout()
  4232. {
  4233. return true;
  4234. }
  4235. protected function afterLogout()
  4236. {
  4237. }
  4238. protected function restoreFromCookie()
  4239. {
  4240. $app=Yii::app();
  4241. $request=$app->getRequest();
  4242. $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  4243. if($cookie && !empty($cookie->value) && is_string($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  4244. {
  4245. $data=@unserialize($data);
  4246. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4247. {
  4248. list($id,$name,$duration,$states)=$data;
  4249. if($this->beforeLogin($id,$states,true))
  4250. {
  4251. $this->changeIdentity($id,$name,$states);
  4252. if($this->autoRenewCookie)
  4253. {
  4254. $this->saveToCookie($duration);
  4255. }
  4256. $this->afterLogin(true);
  4257. }
  4258. }
  4259. }
  4260. }
  4261. protected function renewCookie()
  4262. {
  4263. $request=Yii::app()->getRequest();
  4264. $cookies=$request->getCookies();
  4265. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  4266. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  4267. {
  4268. $data=@unserialize($data);
  4269. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4270. {
  4271. $this->saveToCookie($data[2]);
  4272. }
  4273. }
  4274. }
  4275. protected function saveToCookie($duration)
  4276. {
  4277. $app=Yii::app();
  4278. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4279. $cookie->expire=time()+$duration;
  4280. $data=array(
  4281. $this->getId(),
  4282. $this->getName(),
  4283. $duration,
  4284. $this->saveIdentityStates(),
  4285. );
  4286. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  4287. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  4288. }
  4289. protected function createIdentityCookie($name)
  4290. {
  4291. $cookie=new CHttpCookie($name,'');
  4292. if(is_array($this->identityCookie))
  4293. {
  4294. foreach($this->identityCookie as $name=>$value)
  4295. $cookie->$name=$value;
  4296. }
  4297. return $cookie;
  4298. }
  4299. public function getStateKeyPrefix()
  4300. {
  4301. if($this->_keyPrefix!==null)
  4302. return $this->_keyPrefix;
  4303. else
  4304. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  4305. }
  4306. public function setStateKeyPrefix($value)
  4307. {
  4308. $this->_keyPrefix=$value;
  4309. }
  4310. public function getState($key,$defaultValue=null)
  4311. {
  4312. $key=$this->getStateKeyPrefix().$key;
  4313. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4314. }
  4315. public function setState($key,$value,$defaultValue=null)
  4316. {
  4317. $key=$this->getStateKeyPrefix().$key;
  4318. if($value===$defaultValue)
  4319. unset($_SESSION[$key]);
  4320. else
  4321. $_SESSION[$key]=$value;
  4322. }
  4323. public function hasState($key)
  4324. {
  4325. $key=$this->getStateKeyPrefix().$key;
  4326. return isset($_SESSION[$key]);
  4327. }
  4328. public function clearStates()
  4329. {
  4330. $keys=array_keys($_SESSION);
  4331. $prefix=$this->getStateKeyPrefix();
  4332. $n=strlen($prefix);
  4333. foreach($keys as $key)
  4334. {
  4335. if(!strncmp($key,$prefix,$n))
  4336. unset($_SESSION[$key]);
  4337. }
  4338. }
  4339. public function getFlashes($delete=true)
  4340. {
  4341. $flashes=array();
  4342. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  4343. $keys=array_keys($_SESSION);
  4344. $n=strlen($prefix);
  4345. foreach($keys as $key)
  4346. {
  4347. if(!strncmp($key,$prefix,$n))
  4348. {
  4349. $flashes[substr($key,$n)]=$_SESSION[$key];
  4350. if($delete)
  4351. unset($_SESSION[$key]);
  4352. }
  4353. }
  4354. if($delete)
  4355. $this->setState(self::FLASH_COUNTERS,array());
  4356. return $flashes;
  4357. }
  4358. public function getFlash($key,$defaultValue=null,$delete=true)
  4359. {
  4360. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4361. if($delete)
  4362. $this->setFlash($key,null);
  4363. return $value;
  4364. }
  4365. public function setFlash($key,$value,$defaultValue=null)
  4366. {
  4367. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4368. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4369. if($value===$defaultValue)
  4370. unset($counters[$key]);
  4371. else
  4372. $counters[$key]=0;
  4373. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4374. }
  4375. public function hasFlash($key)
  4376. {
  4377. return $this->getFlash($key, null, false)!==null;
  4378. }
  4379. protected function changeIdentity($id,$name,$states)
  4380. {
  4381. Yii::app()->getSession()->regenerateID(true);
  4382. $this->setId($id);
  4383. $this->setName($name);
  4384. $this->loadIdentityStates($states);
  4385. }
  4386. protected function saveIdentityStates()
  4387. {
  4388. $states=array();
  4389. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4390. $states[$name]=$this->getState($name);
  4391. return $states;
  4392. }
  4393. protected function loadIdentityStates($states)
  4394. {
  4395. $names=array();
  4396. if(is_array($states))
  4397. {
  4398. foreach($states as $name=>$value)
  4399. {
  4400. $this->setState($name,$value);
  4401. $names[$name]=true;
  4402. }
  4403. }
  4404. $this->setState(self::STATES_VAR,$names);
  4405. }
  4406. protected function updateFlash()
  4407. {
  4408. $counters=$this->getState(self::FLASH_COUNTERS);
  4409. if(!is_array($counters))
  4410. return;
  4411. foreach($counters as $key=>$count)
  4412. {
  4413. if($count)
  4414. {
  4415. unset($counters[$key]);
  4416. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4417. }
  4418. else
  4419. $counters[$key]++;
  4420. }
  4421. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4422. }
  4423. protected function updateAuthStatus()
  4424. {
  4425. if(($this->authTimeout!==null || $this->absoluteAuthTimeout!==null) && !$this->getIsGuest())
  4426. {
  4427. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4428. $expiresAbsolute=$this->getState(self::AUTH_ABSOLUTE_TIMEOUT_VAR);
  4429. if ($expires!==null && $expires < time() || $expiresAbsolute!==null && $expiresAbsolute < time())
  4430. $this->logout(false);
  4431. else
  4432. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4433. }
  4434. }
  4435. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4436. {
  4437. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4438. return $this->_access[$operation];
  4439. $access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4440. if($allowCaching && $params===array())
  4441. $this->_access[$operation]=$access;
  4442. return $access;
  4443. }
  4444. }
  4445. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4446. {
  4447. public $autoStart=true;
  4448. public function init()
  4449. {
  4450. parent::init();
  4451. if($this->autoStart)
  4452. $this->open();
  4453. register_shutdown_function(array($this,'close'));
  4454. }
  4455. public function getUseCustomStorage()
  4456. {
  4457. return false;
  4458. }
  4459. public function open()
  4460. {
  4461. if($this->getUseCustomStorage())
  4462. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4463. @session_start();
  4464. if(YII_DEBUG && session_id()=='')
  4465. {
  4466. $message=Yii::t('yii','Failed to start session.');
  4467. if(function_exists('error_get_last'))
  4468. {
  4469. $error=error_get_last();
  4470. if(isset($error['message']))
  4471. $message=$error['message'];
  4472. }
  4473. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4474. }
  4475. }
  4476. public function close()
  4477. {
  4478. if(session_id()!=='')
  4479. @session_write_close();
  4480. }
  4481. public function destroy()
  4482. {
  4483. if(session_id()!=='')
  4484. {
  4485. @session_unset();
  4486. @session_destroy();
  4487. }
  4488. }
  4489. public function getIsStarted()
  4490. {
  4491. return session_id()!=='';
  4492. }
  4493. public function getSessionID()
  4494. {
  4495. return session_id();
  4496. }
  4497. public function setSessionID($value)
  4498. {
  4499. session_id($value);
  4500. }
  4501. public function regenerateID($deleteOldSession=false)
  4502. {
  4503. session_regenerate_id($deleteOldSession);
  4504. }
  4505. public function getSessionName()
  4506. {
  4507. return session_name();
  4508. }
  4509. public function setSessionName($value)
  4510. {
  4511. session_name($value);
  4512. }
  4513. public function getSavePath()
  4514. {
  4515. return session_save_path();
  4516. }
  4517. public function setSavePath($value)
  4518. {
  4519. if(is_dir($value))
  4520. session_save_path($value);
  4521. else
  4522. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4523. array('{path}'=>$value)));
  4524. }
  4525. public function getCookieParams()
  4526. {
  4527. return session_get_cookie_params();
  4528. }
  4529. public function setCookieParams($value)
  4530. {
  4531. $data=session_get_cookie_params();
  4532. extract($data);
  4533. extract($value);
  4534. if(isset($httponly))
  4535. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4536. else
  4537. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4538. }
  4539. public function getCookieMode()
  4540. {
  4541. if(ini_get('session.use_cookies')==='0')
  4542. return 'none';
  4543. elseif(ini_get('session.use_only_cookies')==='0')
  4544. return 'allow';
  4545. else
  4546. return 'only';
  4547. }
  4548. public function setCookieMode($value)
  4549. {
  4550. if($value==='none')
  4551. {
  4552. ini_set('session.use_cookies','0');
  4553. ini_set('session.use_only_cookies','0');
  4554. }
  4555. elseif($value==='allow')
  4556. {
  4557. ini_set('session.use_cookies','1');
  4558. ini_set('session.use_only_cookies','0');
  4559. }
  4560. elseif($value==='only')
  4561. {
  4562. ini_set('session.use_cookies','1');
  4563. ini_set('session.use_only_cookies','1');
  4564. }
  4565. else
  4566. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4567. }
  4568. public function getGCProbability()
  4569. {
  4570. return (float)(ini_get('session.gc_probability')/ini_get('session.gc_divisor')*100);
  4571. }
  4572. public function setGCProbability($value)
  4573. {
  4574. if($value>=0 && $value<=100)
  4575. {
  4576. // percent * 21474837 / 2147483647 ≈ percent * 0.01
  4577. ini_set('session.gc_probability',floor($value*21474836.47));
  4578. ini_set('session.gc_divisor',2147483647);
  4579. }
  4580. else
  4581. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be a float between 0 and 100.',
  4582. array('{value}'=>$value)));
  4583. }
  4584. public function getUseTransparentSessionID()
  4585. {
  4586. return ini_get('session.use_trans_sid')==1;
  4587. }
  4588. public function setUseTransparentSessionID($value)
  4589. {
  4590. ini_set('session.use_trans_sid',$value?'1':'0');
  4591. }
  4592. public function getTimeout()
  4593. {
  4594. return (int)ini_get('session.gc_maxlifetime');
  4595. }
  4596. public function setTimeout($value)
  4597. {
  4598. ini_set('session.gc_maxlifetime',$value);
  4599. }
  4600. public function openSession($savePath,$sessionName)
  4601. {
  4602. return true;
  4603. }
  4604. public function closeSession()
  4605. {
  4606. return true;
  4607. }
  4608. public function readSession($id)
  4609. {
  4610. return '';
  4611. }
  4612. public function writeSession($id,$data)
  4613. {
  4614. return true;
  4615. }
  4616. public function destroySession($id)
  4617. {
  4618. return true;
  4619. }
  4620. public function gcSession($maxLifetime)
  4621. {
  4622. return true;
  4623. }
  4624. //------ The following methods enable CHttpSession to be CMap-like -----
  4625. public function getIterator()
  4626. {
  4627. return new CHttpSessionIterator;
  4628. }
  4629. public function getCount()
  4630. {
  4631. return count($_SESSION);
  4632. }
  4633. public function count()
  4634. {
  4635. return $this->getCount();
  4636. }
  4637. public function getKeys()
  4638. {
  4639. return array_keys($_SESSION);
  4640. }
  4641. public function get($key,$defaultValue=null)
  4642. {
  4643. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4644. }
  4645. public function itemAt($key)
  4646. {
  4647. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4648. }
  4649. public function add($key,$value)
  4650. {
  4651. $_SESSION[$key]=$value;
  4652. }
  4653. public function remove($key)
  4654. {
  4655. if(isset($_SESSION[$key]))
  4656. {
  4657. $value=$_SESSION[$key];
  4658. unset($_SESSION[$key]);
  4659. return $value;
  4660. }
  4661. else
  4662. return null;
  4663. }
  4664. public function clear()
  4665. {
  4666. foreach(array_keys($_SESSION) as $key)
  4667. unset($_SESSION[$key]);
  4668. }
  4669. public function contains($key)
  4670. {
  4671. return isset($_SESSION[$key]);
  4672. }
  4673. public function toArray()
  4674. {
  4675. return $_SESSION;
  4676. }
  4677. public function offsetExists($offset)
  4678. {
  4679. return isset($_SESSION[$offset]);
  4680. }
  4681. public function offsetGet($offset)
  4682. {
  4683. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4684. }
  4685. public function offsetSet($offset,$item)
  4686. {
  4687. $_SESSION[$offset]=$item;
  4688. }
  4689. public function offsetUnset($offset)
  4690. {
  4691. unset($_SESSION[$offset]);
  4692. }
  4693. }
  4694. class CHtml
  4695. {
  4696. const ID_PREFIX='yt';
  4697. public static $errorSummaryCss='errorSummary';
  4698. public static $errorMessageCss='errorMessage';
  4699. public static $errorCss='error';
  4700. public static $errorContainerTag='div';
  4701. public static $requiredCss='required';
  4702. public static $beforeRequiredLabel='';
  4703. public static $afterRequiredLabel=' <span class="required">*</span>';
  4704. public static $count=0;
  4705. public static $liveEvents=true;
  4706. public static $closeSingleTags=true;
  4707. public static $renderSpecialAttributesValue=true;
  4708. private static $_modelNameConverter;
  4709. public static function encode($text)
  4710. {
  4711. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4712. }
  4713. public static function decode($text)
  4714. {
  4715. return htmlspecialchars_decode($text,ENT_QUOTES);
  4716. }
  4717. public static function encodeArray($data)
  4718. {
  4719. $d=array();
  4720. foreach($data as $key=>$value)
  4721. {
  4722. if(is_string($key))
  4723. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4724. if(is_string($value))
  4725. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4726. elseif(is_array($value))
  4727. $value=self::encodeArray($value);
  4728. $d[$key]=$value;
  4729. }
  4730. return $d;
  4731. }
  4732. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4733. {
  4734. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4735. if($content===false)
  4736. return $closeTag && self::$closeSingleTags ? $html.' />' : $html.'>';
  4737. else
  4738. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4739. }
  4740. public static function openTag($tag,$htmlOptions=array())
  4741. {
  4742. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4743. }
  4744. public static function closeTag($tag)
  4745. {
  4746. return '</'.$tag.'>';
  4747. }
  4748. public static function cdata($text)
  4749. {
  4750. return '<![CDATA[' . $text . ']]>';
  4751. }
  4752. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4753. {
  4754. if($name!==null)
  4755. $options['name']=$name;
  4756. if($httpEquiv!==null)
  4757. $options['http-equiv']=$httpEquiv;
  4758. $options['content']=$content;
  4759. return self::tag('meta',$options);
  4760. }
  4761. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4762. {
  4763. if($relation!==null)
  4764. $options['rel']=$relation;
  4765. if($type!==null)
  4766. $options['type']=$type;
  4767. if($href!==null)
  4768. $options['href']=$href;
  4769. if($media!==null)
  4770. $options['media']=$media;
  4771. return self::tag('link',$options);
  4772. }
  4773. public static function css($text,$media='')
  4774. {
  4775. if($media!=='')
  4776. $media=' media="'.$media.'"';
  4777. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4778. }
  4779. public static function refresh($seconds,$url='')
  4780. {
  4781. $content="$seconds";
  4782. if($url!=='')
  4783. $content.=';url='.self::normalizeUrl($url);
  4784. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4785. }
  4786. public static function cssFile($url,$media='')
  4787. {
  4788. return CHtml::linkTag('stylesheet','text/css',$url,$media!=='' ? $media : null);
  4789. }
  4790. public static function script($text,array $htmlOptions=array())
  4791. {
  4792. $defaultHtmlOptions=array(
  4793. 'type'=>'text/javascript',
  4794. );
  4795. $htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
  4796. return self::tag('script',$htmlOptions,"\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n");
  4797. }
  4798. public static function scriptFile($url,array $htmlOptions=array())
  4799. {
  4800. $defaultHtmlOptions=array(
  4801. 'type'=>'text/javascript',
  4802. 'src'=>$url
  4803. );
  4804. $htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
  4805. return self::tag('script',$htmlOptions,'');
  4806. }
  4807. public static function form($action='',$method='post',$htmlOptions=array())
  4808. {
  4809. return self::beginForm($action,$method,$htmlOptions);
  4810. }
  4811. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4812. {
  4813. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4814. $htmlOptions['method']=$method;
  4815. $form=self::tag('form',$htmlOptions,false,false);
  4816. $hiddens=array();
  4817. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4818. {
  4819. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4820. {
  4821. if(($pos=strpos($pair,'='))!==false)
  4822. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4823. else
  4824. $hiddens[]=self::hiddenField(urldecode($pair),'',array('id'=>false));
  4825. }
  4826. }
  4827. $request=Yii::app()->request;
  4828. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4829. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4830. if($hiddens!==array())
  4831. $form.="\n".self::tag('div',array('style'=>'display:none'),implode("\n",$hiddens));
  4832. return $form;
  4833. }
  4834. public static function endForm()
  4835. {
  4836. return '</form>';
  4837. }
  4838. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4839. {
  4840. return self::form($action,$method,$htmlOptions)."\n".
  4841. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4842. }
  4843. public static function pageStateField($value)
  4844. {
  4845. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4846. }
  4847. public static function link($text,$url='#',$htmlOptions=array())
  4848. {
  4849. if($url!=='')
  4850. $htmlOptions['href']=self::normalizeUrl($url);
  4851. self::clientChange('click',$htmlOptions);
  4852. return self::tag('a',$htmlOptions,$text);
  4853. }
  4854. public static function mailto($text,$email='',$htmlOptions=array())
  4855. {
  4856. if($email==='')
  4857. $email=$text;
  4858. return self::link($text,'mailto:'.$email,$htmlOptions);
  4859. }
  4860. public static function image($src,$alt='',$htmlOptions=array())
  4861. {
  4862. $htmlOptions['src']=$src;
  4863. $htmlOptions['alt']=$alt;
  4864. return self::tag('img',$htmlOptions);
  4865. }
  4866. public static function button($label='button',$htmlOptions=array())
  4867. {
  4868. if(!isset($htmlOptions['name']))
  4869. {
  4870. if(!array_key_exists('name',$htmlOptions))
  4871. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4872. }
  4873. if(!isset($htmlOptions['type']))
  4874. $htmlOptions['type']='button';
  4875. if(!isset($htmlOptions['value']) && $htmlOptions['type']!='image')
  4876. $htmlOptions['value']=$label;
  4877. self::clientChange('click',$htmlOptions);
  4878. return self::tag('input',$htmlOptions);
  4879. }
  4880. public static function htmlButton($label='button',$htmlOptions=array())
  4881. {
  4882. if(!isset($htmlOptions['name']))
  4883. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4884. if(!isset($htmlOptions['type']))
  4885. $htmlOptions['type']='button';
  4886. self::clientChange('click',$htmlOptions);
  4887. return self::tag('button',$htmlOptions,$label);
  4888. }
  4889. public static function submitButton($label='submit',$htmlOptions=array())
  4890. {
  4891. $htmlOptions['type']='submit';
  4892. return self::button($label,$htmlOptions);
  4893. }
  4894. public static function resetButton($label='reset',$htmlOptions=array())
  4895. {
  4896. $htmlOptions['type']='reset';
  4897. return self::button($label,$htmlOptions);
  4898. }
  4899. public static function imageButton($src,$htmlOptions=array())
  4900. {
  4901. $htmlOptions['src']=$src;
  4902. $htmlOptions['type']='image';
  4903. return self::button('submit',$htmlOptions);
  4904. }
  4905. public static function linkButton($label='submit',$htmlOptions=array())
  4906. {
  4907. if(!isset($htmlOptions['submit']))
  4908. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  4909. return self::link($label,'#',$htmlOptions);
  4910. }
  4911. public static function label($label,$for,$htmlOptions=array())
  4912. {
  4913. if($for===false)
  4914. unset($htmlOptions['for']);
  4915. else
  4916. $htmlOptions['for']=$for;
  4917. if(isset($htmlOptions['required']))
  4918. {
  4919. if($htmlOptions['required'])
  4920. {
  4921. if(isset($htmlOptions['class']))
  4922. $htmlOptions['class'].=' '.self::$requiredCss;
  4923. else
  4924. $htmlOptions['class']=self::$requiredCss;
  4925. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  4926. }
  4927. unset($htmlOptions['required']);
  4928. }
  4929. return self::tag('label',$htmlOptions,$label);
  4930. }
  4931. public static function textField($name,$value='',$htmlOptions=array())
  4932. {
  4933. self::clientChange('change',$htmlOptions);
  4934. return self::inputField('text',$name,$value,$htmlOptions);
  4935. }
  4936. public static function numberField($name,$value='',$htmlOptions=array())
  4937. {
  4938. self::clientChange('change',$htmlOptions);
  4939. return self::inputField('number',$name,$value,$htmlOptions);
  4940. }
  4941. public static function rangeField($name,$value='',$htmlOptions=array())
  4942. {
  4943. self::clientChange('change',$htmlOptions);
  4944. return self::inputField('range',$name,$value,$htmlOptions);
  4945. }
  4946. public static function dateField($name,$value='',$htmlOptions=array())
  4947. {
  4948. self::clientChange('change',$htmlOptions);
  4949. return self::inputField('date',$name,$value,$htmlOptions);
  4950. }
  4951. public static function timeField($name,$value='',$htmlOptions=array())
  4952. {
  4953. self::clientChange('change',$htmlOptions);
  4954. return self::inputField('time',$name,$value,$htmlOptions);
  4955. }
  4956. public static function emailField($name,$value='',$htmlOptions=array())
  4957. {
  4958. self::clientChange('change',$htmlOptions);
  4959. return self::inputField('email',$name,$value,$htmlOptions);
  4960. }
  4961. public static function telField($name,$value='',$htmlOptions=array())
  4962. {
  4963. self::clientChange('change',$htmlOptions);
  4964. return self::inputField('tel',$name,$value,$htmlOptions);
  4965. }
  4966. public static function urlField($name,$value='',$htmlOptions=array())
  4967. {
  4968. self::clientChange('change',$htmlOptions);
  4969. return self::inputField('url',$name,$value,$htmlOptions);
  4970. }
  4971. public static function hiddenField($name,$value='',$htmlOptions=array())
  4972. {
  4973. return self::inputField('hidden',$name,$value,$htmlOptions);
  4974. }
  4975. public static function passwordField($name,$value='',$htmlOptions=array())
  4976. {
  4977. self::clientChange('change',$htmlOptions);
  4978. return self::inputField('password',$name,$value,$htmlOptions);
  4979. }
  4980. public static function fileField($name,$value='',$htmlOptions=array())
  4981. {
  4982. return self::inputField('file',$name,$value,$htmlOptions);
  4983. }
  4984. public static function textArea($name,$value='',$htmlOptions=array())
  4985. {
  4986. $htmlOptions['name']=$name;
  4987. if(!isset($htmlOptions['id']))
  4988. $htmlOptions['id']=self::getIdByName($name);
  4989. elseif($htmlOptions['id']===false)
  4990. unset($htmlOptions['id']);
  4991. self::clientChange('change',$htmlOptions);
  4992. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  4993. }
  4994. public static function radioButton($name,$checked=false,$htmlOptions=array())
  4995. {
  4996. if($checked)
  4997. $htmlOptions['checked']='checked';
  4998. else
  4999. unset($htmlOptions['checked']);
  5000. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  5001. self::clientChange('click',$htmlOptions);
  5002. if(array_key_exists('uncheckValue',$htmlOptions))
  5003. {
  5004. $uncheck=$htmlOptions['uncheckValue'];
  5005. unset($htmlOptions['uncheckValue']);
  5006. }
  5007. else
  5008. $uncheck=null;
  5009. if($uncheck!==null)
  5010. {
  5011. // add a hidden field so that if the radio button is not selected, it still submits a value
  5012. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  5013. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  5014. else
  5015. $uncheckOptions=array('id'=>false);
  5016. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  5017. }
  5018. else
  5019. $hidden='';
  5020. // add a hidden field so that if the radio button is not selected, it still submits a value
  5021. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  5022. }
  5023. public static function checkBox($name,$checked=false,$htmlOptions=array())
  5024. {
  5025. if($checked)
  5026. $htmlOptions['checked']='checked';
  5027. else
  5028. unset($htmlOptions['checked']);
  5029. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  5030. self::clientChange('click',$htmlOptions);
  5031. if(array_key_exists('uncheckValue',$htmlOptions))
  5032. {
  5033. $uncheck=$htmlOptions['uncheckValue'];
  5034. unset($htmlOptions['uncheckValue']);
  5035. }
  5036. else
  5037. $uncheck=null;
  5038. if($uncheck!==null)
  5039. {
  5040. // add a hidden field so that if the check box is not checked, it still submits a value
  5041. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  5042. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  5043. else
  5044. $uncheckOptions=array('id'=>false);
  5045. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  5046. }
  5047. else
  5048. $hidden='';
  5049. // add a hidden field so that if the check box is not checked, it still submits a value
  5050. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  5051. }
  5052. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  5053. {
  5054. $htmlOptions['name']=$name;
  5055. if(!isset($htmlOptions['id']))
  5056. $htmlOptions['id']=self::getIdByName($name);
  5057. elseif($htmlOptions['id']===false)
  5058. unset($htmlOptions['id']);
  5059. self::clientChange('change',$htmlOptions);
  5060. $options="\n".self::listOptions($select,$data,$htmlOptions);
  5061. $hidden='';
  5062. if(!empty($htmlOptions['multiple']))
  5063. {
  5064. if(substr($htmlOptions['name'],-2)!=='[]')
  5065. $htmlOptions['name'].='[]';
  5066. if(isset($htmlOptions['unselectValue']))
  5067. {
  5068. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5069. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  5070. unset($htmlOptions['unselectValue']);
  5071. }
  5072. }
  5073. // add a hidden field so that if the option is not selected, it still submits a value
  5074. return $hidden . self::tag('select',$htmlOptions,$options);
  5075. }
  5076. public static function listBox($name,$select,$data,$htmlOptions=array())
  5077. {
  5078. if(!isset($htmlOptions['size']))
  5079. $htmlOptions['size']=4;
  5080. if(!empty($htmlOptions['multiple']))
  5081. {
  5082. if(substr($name,-2)!=='[]')
  5083. $name.='[]';
  5084. }
  5085. return self::dropDownList($name,$select,$data,$htmlOptions);
  5086. }
  5087. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  5088. {
  5089. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  5090. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  5091. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  5092. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  5093. if(substr($name,-2)!=='[]')
  5094. $name.='[]';
  5095. if(isset($htmlOptions['checkAll']))
  5096. {
  5097. $checkAllLabel=$htmlOptions['checkAll'];
  5098. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  5099. }
  5100. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  5101. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  5102. unset($htmlOptions['labelOptions']);
  5103. $items=array();
  5104. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  5105. unset($htmlOptions['baseID']);
  5106. $id=0;
  5107. $checkAll=true;
  5108. foreach($data as $value=>$labelTitle)
  5109. {
  5110. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  5111. $checkAll=$checkAll && $checked;
  5112. $htmlOptions['value']=$value;
  5113. $htmlOptions['id']=$baseID.'_'.$id++;
  5114. $option=self::checkBox($name,$checked,$htmlOptions);
  5115. $beginLabel=self::openTag('label',$labelOptions);
  5116. $label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
  5117. $endLabel=self::closeTag('label');
  5118. $items[]=strtr($template,array(
  5119. '{input}'=>$option,
  5120. '{beginLabel}'=>$beginLabel,
  5121. '{label}'=>$label,
  5122. '{labelTitle}'=>$labelTitle,
  5123. '{endLabel}'=>$endLabel,
  5124. ));
  5125. }
  5126. if(isset($checkAllLabel))
  5127. {
  5128. $htmlOptions['value']=1;
  5129. $htmlOptions['id']=$id=$baseID.'_all';
  5130. $option=self::checkBox($id,$checkAll,$htmlOptions);
  5131. $beginLabel=self::openTag('label',$labelOptions);
  5132. $label=self::label($checkAllLabel,$id,$labelOptions);
  5133. $endLabel=self::closeTag('label');
  5134. $item=strtr($template,array(
  5135. '{input}'=>$option,
  5136. '{beginLabel}'=>$beginLabel,
  5137. '{label}'=>$label,
  5138. '{labelTitle}'=>$checkAllLabel,
  5139. '{endLabel}'=>$endLabel,
  5140. ));
  5141. if($checkAllLast)
  5142. $items[]=$item;
  5143. else
  5144. array_unshift($items,$item);
  5145. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  5146. $js=<<<EOD
  5147. jQuery('#$id').click(function() {
  5148. jQuery("input[name='$name']").prop('checked', this.checked);
  5149. });
  5150. jQuery("input[name='$name']").click(function() {
  5151. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  5152. });
  5153. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  5154. EOD;
  5155. $cs=Yii::app()->getClientScript();
  5156. $cs->registerCoreScript('jquery');
  5157. $cs->registerScript($id,$js);
  5158. }
  5159. if(empty($container))
  5160. return implode($separator,$items);
  5161. else
  5162. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  5163. }
  5164. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  5165. {
  5166. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  5167. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  5168. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  5169. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  5170. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  5171. unset($htmlOptions['labelOptions']);
  5172. if(isset($htmlOptions['empty']))
  5173. {
  5174. if(!is_array($htmlOptions['empty']))
  5175. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5176. $data=array_merge($htmlOptions['empty'],$data);
  5177. unset($htmlOptions['empty']);
  5178. }
  5179. $items=array();
  5180. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  5181. unset($htmlOptions['baseID']);
  5182. $id=0;
  5183. foreach($data as $value=>$labelTitle)
  5184. {
  5185. $checked=!strcmp($value,$select);
  5186. $htmlOptions['value']=$value;
  5187. $htmlOptions['id']=$baseID.'_'.$id++;
  5188. $option=self::radioButton($name,$checked,$htmlOptions);
  5189. $beginLabel=self::openTag('label',$labelOptions);
  5190. $label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
  5191. $endLabel=self::closeTag('label');
  5192. $items[]=strtr($template,array(
  5193. '{input}'=>$option,
  5194. '{beginLabel}'=>$beginLabel,
  5195. '{label}'=>$label,
  5196. '{labelTitle}'=>$labelTitle,
  5197. '{endLabel}'=>$endLabel,
  5198. ));
  5199. }
  5200. if(empty($container))
  5201. return implode($separator,$items);
  5202. else
  5203. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  5204. }
  5205. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  5206. {
  5207. if(!isset($htmlOptions['href']))
  5208. $htmlOptions['href']='#';
  5209. $ajaxOptions['url']=$url;
  5210. $htmlOptions['ajax']=$ajaxOptions;
  5211. self::clientChange('click',$htmlOptions);
  5212. return self::tag('a',$htmlOptions,$text);
  5213. }
  5214. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  5215. {
  5216. $ajaxOptions['url']=$url;
  5217. $htmlOptions['ajax']=$ajaxOptions;
  5218. return self::button($label,$htmlOptions);
  5219. }
  5220. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  5221. {
  5222. $ajaxOptions['type']='POST';
  5223. $htmlOptions['type']='submit';
  5224. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  5225. }
  5226. public static function ajax($options)
  5227. {
  5228. Yii::app()->getClientScript()->registerCoreScript('jquery');
  5229. if(!isset($options['url']))
  5230. $options['url']=new CJavaScriptExpression('location.href');
  5231. else
  5232. $options['url']=self::normalizeUrl($options['url']);
  5233. if(!isset($options['cache']))
  5234. $options['cache']=false;
  5235. if(!isset($options['data']) && isset($options['type']))
  5236. $options['data']=new CJavaScriptExpression('jQuery(this).parents("form").serialize()');
  5237. foreach(array('beforeSend','complete','error','success') as $name)
  5238. {
  5239. if(isset($options[$name]) && !($options[$name] instanceof CJavaScriptExpression))
  5240. $options[$name]=new CJavaScriptExpression($options[$name]);
  5241. }
  5242. if(isset($options['update']))
  5243. {
  5244. if(!isset($options['success']))
  5245. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['update'].'").html(html)}');
  5246. unset($options['update']);
  5247. }
  5248. if(isset($options['replace']))
  5249. {
  5250. if(!isset($options['success']))
  5251. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['replace'].'").replaceWith(html)}');
  5252. unset($options['replace']);
  5253. }
  5254. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  5255. }
  5256. public static function asset($path,$hashByName=false)
  5257. {
  5258. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  5259. }
  5260. public static function normalizeUrl($url)
  5261. {
  5262. if(is_array($url))
  5263. {
  5264. if(isset($url[0]))
  5265. {
  5266. if(($c=Yii::app()->getController())!==null)
  5267. $url=$c->createUrl($url[0],array_splice($url,1));
  5268. else
  5269. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  5270. }
  5271. else
  5272. $url='';
  5273. }
  5274. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  5275. }
  5276. protected static function inputField($type,$name,$value,$htmlOptions)
  5277. {
  5278. $htmlOptions['type']=$type;
  5279. $htmlOptions['value']=$value;
  5280. $htmlOptions['name']=$name;
  5281. if(!isset($htmlOptions['id']))
  5282. $htmlOptions['id']=self::getIdByName($name);
  5283. elseif($htmlOptions['id']===false)
  5284. unset($htmlOptions['id']);
  5285. return self::tag('input',$htmlOptions);
  5286. }
  5287. public static function activeLabel($model,$attribute,$htmlOptions=array())
  5288. {
  5289. $inputName=self::resolveName($model,$attribute);
  5290. if(isset($htmlOptions['for']))
  5291. {
  5292. $for=$htmlOptions['for'];
  5293. unset($htmlOptions['for']);
  5294. }
  5295. else
  5296. $for=self::getIdByName($inputName);
  5297. if(isset($htmlOptions['label']))
  5298. {
  5299. if(($label=$htmlOptions['label'])===false)
  5300. return '';
  5301. unset($htmlOptions['label']);
  5302. }
  5303. else
  5304. $label=$model->getAttributeLabel($attribute);
  5305. if($model->hasErrors($attribute))
  5306. self::addErrorCss($htmlOptions);
  5307. return self::label($label,$for,$htmlOptions);
  5308. }
  5309. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  5310. {
  5311. $realAttribute=$attribute;
  5312. self::resolveName($model,$attribute); // strip off square brackets if any
  5313. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  5314. return self::activeLabel($model,$realAttribute,$htmlOptions);
  5315. }
  5316. public static function activeTextField($model,$attribute,$htmlOptions=array())
  5317. {
  5318. self::resolveNameID($model,$attribute,$htmlOptions);
  5319. self::clientChange('change',$htmlOptions);
  5320. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  5321. }
  5322. public static function activeSearchField($model,$attribute,$htmlOptions=array())
  5323. {
  5324. self::resolveNameID($model,$attribute,$htmlOptions);
  5325. self::clientChange('change',$htmlOptions);
  5326. return self::activeInputField('search',$model,$attribute,$htmlOptions);
  5327. }
  5328. public static function activeUrlField($model,$attribute,$htmlOptions=array())
  5329. {
  5330. self::resolveNameID($model,$attribute,$htmlOptions);
  5331. self::clientChange('change',$htmlOptions);
  5332. return self::activeInputField('url',$model,$attribute,$htmlOptions);
  5333. }
  5334. public static function activeEmailField($model,$attribute,$htmlOptions=array())
  5335. {
  5336. self::resolveNameID($model,$attribute,$htmlOptions);
  5337. self::clientChange('change',$htmlOptions);
  5338. return self::activeInputField('email',$model,$attribute,$htmlOptions);
  5339. }
  5340. public static function activeNumberField($model,$attribute,$htmlOptions=array())
  5341. {
  5342. self::resolveNameID($model,$attribute,$htmlOptions);
  5343. self::clientChange('change',$htmlOptions);
  5344. return self::activeInputField('number',$model,$attribute,$htmlOptions);
  5345. }
  5346. public static function activeRangeField($model,$attribute,$htmlOptions=array())
  5347. {
  5348. self::resolveNameID($model,$attribute,$htmlOptions);
  5349. self::clientChange('change',$htmlOptions);
  5350. return self::activeInputField('range',$model,$attribute,$htmlOptions);
  5351. }
  5352. public static function activeDateField($model,$attribute,$htmlOptions=array())
  5353. {
  5354. self::resolveNameID($model,$attribute,$htmlOptions);
  5355. self::clientChange('change',$htmlOptions);
  5356. return self::activeInputField('date',$model,$attribute,$htmlOptions);
  5357. }
  5358. public static function activeTimeField($model,$attribute,$htmlOptions=array())
  5359. {
  5360. self::resolveNameID($model,$attribute,$htmlOptions);
  5361. self::clientChange('change',$htmlOptions);
  5362. return self::activeInputField('time',$model,$attribute,$htmlOptions);
  5363. }
  5364. public static function activeTelField($model,$attribute,$htmlOptions=array())
  5365. {
  5366. self::resolveNameID($model,$attribute,$htmlOptions);
  5367. self::clientChange('change',$htmlOptions);
  5368. return self::activeInputField('tel',$model,$attribute,$htmlOptions);
  5369. }
  5370. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  5371. {
  5372. self::resolveNameID($model,$attribute,$htmlOptions);
  5373. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  5374. }
  5375. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  5376. {
  5377. self::resolveNameID($model,$attribute,$htmlOptions);
  5378. self::clientChange('change',$htmlOptions);
  5379. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  5380. }
  5381. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  5382. {
  5383. self::resolveNameID($model,$attribute,$htmlOptions);
  5384. self::clientChange('change',$htmlOptions);
  5385. if($model->hasErrors($attribute))
  5386. self::addErrorCss($htmlOptions);
  5387. if(isset($htmlOptions['value']))
  5388. {
  5389. $text=$htmlOptions['value'];
  5390. unset($htmlOptions['value']);
  5391. }
  5392. else
  5393. $text=self::resolveValue($model,$attribute);
  5394. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  5395. }
  5396. public static function activeFileField($model,$attribute,$htmlOptions=array())
  5397. {
  5398. self::resolveNameID($model,$attribute,$htmlOptions);
  5399. // add a hidden field so that if a model only has a file field, we can
  5400. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  5401. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5402. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  5403. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  5404. }
  5405. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  5406. {
  5407. self::resolveNameID($model,$attribute,$htmlOptions);
  5408. if(!isset($htmlOptions['value']))
  5409. $htmlOptions['value']=1;
  5410. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5411. $htmlOptions['checked']='checked';
  5412. self::clientChange('click',$htmlOptions);
  5413. if(array_key_exists('uncheckValue',$htmlOptions))
  5414. {
  5415. $uncheck=$htmlOptions['uncheckValue'];
  5416. unset($htmlOptions['uncheckValue']);
  5417. }
  5418. else
  5419. $uncheck='0';
  5420. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5421. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5422. // add a hidden field so that if the radio button is not selected, it still submits a value
  5423. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  5424. }
  5425. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  5426. {
  5427. self::resolveNameID($model,$attribute,$htmlOptions);
  5428. if(!isset($htmlOptions['value']))
  5429. $htmlOptions['value']=1;
  5430. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5431. $htmlOptions['checked']='checked';
  5432. self::clientChange('click',$htmlOptions);
  5433. if(array_key_exists('uncheckValue',$htmlOptions))
  5434. {
  5435. $uncheck=$htmlOptions['uncheckValue'];
  5436. unset($htmlOptions['uncheckValue']);
  5437. }
  5438. else
  5439. $uncheck='0';
  5440. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5441. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5442. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  5443. }
  5444. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  5445. {
  5446. self::resolveNameID($model,$attribute,$htmlOptions);
  5447. $selection=self::resolveValue($model,$attribute);
  5448. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  5449. self::clientChange('change',$htmlOptions);
  5450. if($model->hasErrors($attribute))
  5451. self::addErrorCss($htmlOptions);
  5452. $hidden='';
  5453. if(!empty($htmlOptions['multiple']))
  5454. {
  5455. if(substr($htmlOptions['name'],-2)!=='[]')
  5456. $htmlOptions['name'].='[]';
  5457. if(isset($htmlOptions['unselectValue']))
  5458. {
  5459. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5460. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  5461. unset($htmlOptions['unselectValue']);
  5462. }
  5463. }
  5464. return $hidden . self::tag('select',$htmlOptions,$options);
  5465. }
  5466. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  5467. {
  5468. if(!isset($htmlOptions['size']))
  5469. $htmlOptions['size']=4;
  5470. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  5471. }
  5472. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  5473. {
  5474. self::resolveNameID($model,$attribute,$htmlOptions);
  5475. $selection=self::resolveValue($model,$attribute);
  5476. if($model->hasErrors($attribute))
  5477. self::addErrorCss($htmlOptions);
  5478. $name=$htmlOptions['name'];
  5479. unset($htmlOptions['name']);
  5480. if(array_key_exists('uncheckValue',$htmlOptions))
  5481. {
  5482. $uncheck=$htmlOptions['uncheckValue'];
  5483. unset($htmlOptions['uncheckValue']);
  5484. }
  5485. else
  5486. $uncheck='';
  5487. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5488. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5489. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  5490. }
  5491. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  5492. {
  5493. self::resolveNameID($model,$attribute,$htmlOptions);
  5494. $selection=self::resolveValue($model,$attribute);
  5495. if($model->hasErrors($attribute))
  5496. self::addErrorCss($htmlOptions);
  5497. $name=$htmlOptions['name'];
  5498. unset($htmlOptions['name']);
  5499. if(array_key_exists('uncheckValue',$htmlOptions))
  5500. {
  5501. $uncheck=$htmlOptions['uncheckValue'];
  5502. unset($htmlOptions['uncheckValue']);
  5503. }
  5504. else
  5505. $uncheck='';
  5506. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5507. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5508. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  5509. }
  5510. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  5511. {
  5512. $content='';
  5513. if(!is_array($model))
  5514. $model=array($model);
  5515. if(isset($htmlOptions['firstError']))
  5516. {
  5517. $firstError=$htmlOptions['firstError'];
  5518. unset($htmlOptions['firstError']);
  5519. }
  5520. else
  5521. $firstError=false;
  5522. foreach($model as $m)
  5523. {
  5524. foreach($m->getErrors() as $errors)
  5525. {
  5526. foreach($errors as $error)
  5527. {
  5528. if($error!='')
  5529. $content.="<li>$error</li>\n";
  5530. if($firstError)
  5531. break;
  5532. }
  5533. }
  5534. }
  5535. if($content!=='')
  5536. {
  5537. if($header===null)
  5538. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5539. if(!isset($htmlOptions['class']))
  5540. $htmlOptions['class']=self::$errorSummaryCss;
  5541. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5542. }
  5543. else
  5544. return '';
  5545. }
  5546. public static function error($model,$attribute,$htmlOptions=array())
  5547. {
  5548. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5549. $error=$model->getError($attribute);
  5550. if($error!='')
  5551. {
  5552. if(!isset($htmlOptions['class']))
  5553. $htmlOptions['class']=self::$errorMessageCss;
  5554. return self::tag(self::$errorContainerTag,$htmlOptions,$error);
  5555. }
  5556. else
  5557. return '';
  5558. }
  5559. public static function listData($models,$valueField,$textField,$groupField='')
  5560. {
  5561. $listData=array();
  5562. if($groupField==='')
  5563. {
  5564. foreach($models as $model)
  5565. {
  5566. $value=self::value($model,$valueField);
  5567. $text=self::value($model,$textField);
  5568. $listData[$value]=$text;
  5569. }
  5570. }
  5571. else
  5572. {
  5573. foreach($models as $model)
  5574. {
  5575. $group=self::value($model,$groupField);
  5576. $value=self::value($model,$valueField);
  5577. $text=self::value($model,$textField);
  5578. if($group===null)
  5579. $listData[$value]=$text;
  5580. else
  5581. $listData[$group][$value]=$text;
  5582. }
  5583. }
  5584. return $listData;
  5585. }
  5586. public static function value($model,$attribute,$defaultValue=null)
  5587. {
  5588. if(is_scalar($attribute) || $attribute===null)
  5589. foreach(explode('.',$attribute) as $name)
  5590. {
  5591. if(is_object($model) && isset($model->$name))
  5592. $model=$model->$name;
  5593. elseif(is_array($model) && isset($model[$name]))
  5594. $model=$model[$name];
  5595. else
  5596. return $defaultValue;
  5597. }
  5598. else
  5599. return call_user_func($attribute,$model);
  5600. return $model;
  5601. }
  5602. public static function getIdByName($name)
  5603. {
  5604. return str_replace(array('[]','][','[',']',' '),array('','_','_','','_'),$name);
  5605. }
  5606. public static function activeId($model,$attribute)
  5607. {
  5608. return self::getIdByName(self::activeName($model,$attribute));
  5609. }
  5610. public static function modelName($model)
  5611. {
  5612. if(is_callable(self::$_modelNameConverter))
  5613. return call_user_func(self::$_modelNameConverter,$model);
  5614. $className=is_object($model) ? get_class($model) : (string)$model;
  5615. return trim(str_replace('\\','_',$className),'_');
  5616. }
  5617. public static function setModelNameConverter($converter)
  5618. {
  5619. if(is_callable($converter))
  5620. self::$_modelNameConverter=$converter;
  5621. elseif($converter===null)
  5622. self::$_modelNameConverter=null;
  5623. else
  5624. throw new CException(Yii::t('yii','The $converter argument must be a valid callback or null.'));
  5625. }
  5626. public static function activeName($model,$attribute)
  5627. {
  5628. $a=$attribute; // because the attribute name may be changed by resolveName
  5629. return self::resolveName($model,$a);
  5630. }
  5631. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5632. {
  5633. $htmlOptions['type']=$type;
  5634. if($type==='text' || $type==='password')
  5635. {
  5636. if(!isset($htmlOptions['maxlength']))
  5637. {
  5638. foreach($model->getValidators($attribute) as $validator)
  5639. {
  5640. if($validator instanceof CStringValidator && $validator->max!==null)
  5641. {
  5642. $htmlOptions['maxlength']=$validator->max;
  5643. break;
  5644. }
  5645. }
  5646. }
  5647. elseif($htmlOptions['maxlength']===false)
  5648. unset($htmlOptions['maxlength']);
  5649. }
  5650. if($type==='file')
  5651. unset($htmlOptions['value']);
  5652. elseif(!isset($htmlOptions['value']))
  5653. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5654. if($model->hasErrors($attribute))
  5655. self::addErrorCss($htmlOptions);
  5656. return self::tag('input',$htmlOptions);
  5657. }
  5658. public static function listOptions($selection,$listData,&$htmlOptions)
  5659. {
  5660. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5661. $content='';
  5662. if(isset($htmlOptions['prompt']))
  5663. {
  5664. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;','>'=>'&gt;'))."</option>\n";
  5665. unset($htmlOptions['prompt']);
  5666. }
  5667. if(isset($htmlOptions['empty']))
  5668. {
  5669. if(!is_array($htmlOptions['empty']))
  5670. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5671. foreach($htmlOptions['empty'] as $value=>$label)
  5672. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;','>'=>'&gt;'))."</option>\n";
  5673. unset($htmlOptions['empty']);
  5674. }
  5675. if(isset($htmlOptions['options']))
  5676. {
  5677. $options=$htmlOptions['options'];
  5678. unset($htmlOptions['options']);
  5679. }
  5680. else
  5681. $options=array();
  5682. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  5683. if(is_array($selection))
  5684. {
  5685. foreach($selection as $i=>$item)
  5686. {
  5687. if(is_object($item))
  5688. $selection[$i]=$item->$key;
  5689. }
  5690. }
  5691. elseif(is_object($selection))
  5692. $selection=$selection->$key;
  5693. foreach($listData as $key=>$value)
  5694. {
  5695. if(is_array($value))
  5696. {
  5697. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  5698. $dummy=array('options'=>$options);
  5699. if(isset($htmlOptions['encode']))
  5700. $dummy['encode']=$htmlOptions['encode'];
  5701. $content.=self::listOptions($selection,$value,$dummy);
  5702. $content.='</optgroup>'."\n";
  5703. }
  5704. else
  5705. {
  5706. $attributes=array('value'=>(string)$key,'encode'=>!$raw);
  5707. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  5708. $attributes['selected']='selected';
  5709. if(isset($options[$key]))
  5710. $attributes=array_merge($attributes,$options[$key]);
  5711. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  5712. }
  5713. }
  5714. unset($htmlOptions['key']);
  5715. return $content;
  5716. }
  5717. protected static function clientChange($event,&$htmlOptions)
  5718. {
  5719. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  5720. return;
  5721. if(isset($htmlOptions['live']))
  5722. {
  5723. $live=$htmlOptions['live'];
  5724. unset($htmlOptions['live']);
  5725. }
  5726. else
  5727. $live = self::$liveEvents;
  5728. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  5729. $return='return true';
  5730. else
  5731. $return='return false';
  5732. if(isset($htmlOptions['on'.$event]))
  5733. {
  5734. $handler=trim($htmlOptions['on'.$event],';').';';
  5735. unset($htmlOptions['on'.$event]);
  5736. }
  5737. else
  5738. $handler='';
  5739. if(isset($htmlOptions['id']))
  5740. $id=$htmlOptions['id'];
  5741. else
  5742. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  5743. $cs=Yii::app()->getClientScript();
  5744. $cs->registerCoreScript('jquery');
  5745. if(isset($htmlOptions['submit']))
  5746. {
  5747. $cs->registerCoreScript('yii');
  5748. $request=Yii::app()->getRequest();
  5749. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  5750. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  5751. if(isset($htmlOptions['params']))
  5752. $params=CJavaScript::encode($htmlOptions['params']);
  5753. else
  5754. $params='{}';
  5755. if($htmlOptions['submit']!=='')
  5756. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  5757. else
  5758. $url='';
  5759. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  5760. }
  5761. if(isset($htmlOptions['ajax']))
  5762. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  5763. if(isset($htmlOptions['confirm']))
  5764. {
  5765. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  5766. if($handler!=='')
  5767. $handler="if($confirm) {".$handler."} else return false;";
  5768. else
  5769. $handler="return $confirm;";
  5770. }
  5771. if($live)
  5772. $cs->registerScript('Yii.CHtml.#' . $id,"jQuery('body').on('$event','#$id',function(){{$handler}});");
  5773. else
  5774. $cs->registerScript('Yii.CHtml.#' . $id,"jQuery('#$id').on('$event', function(){{$handler}});");
  5775. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  5776. }
  5777. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  5778. {
  5779. if(!isset($htmlOptions['name']))
  5780. $htmlOptions['name']=self::resolveName($model,$attribute);
  5781. if(!isset($htmlOptions['id']))
  5782. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  5783. elseif($htmlOptions['id']===false)
  5784. unset($htmlOptions['id']);
  5785. }
  5786. public static function resolveName($model,&$attribute)
  5787. {
  5788. $modelName=self::modelName($model);
  5789. if(($pos=strpos($attribute,'['))!==false)
  5790. {
  5791. if($pos!==0) // e.g. name[a][b]
  5792. return $modelName.'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5793. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5794. {
  5795. $sub=substr($attribute,0,$pos+1);
  5796. $attribute=substr($attribute,$pos+1);
  5797. return $modelName.$sub.'['.$attribute.']';
  5798. }
  5799. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5800. {
  5801. $name=$modelName.'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5802. $attribute=$matches[1];
  5803. return $name;
  5804. }
  5805. }
  5806. return $modelName.'['.$attribute.']';
  5807. }
  5808. public static function resolveValue($model,$attribute)
  5809. {
  5810. if(($pos=strpos($attribute,'['))!==false)
  5811. {
  5812. if($pos===0) // [a]name[b][c], should ignore [a]
  5813. {
  5814. if(preg_match('/\](\w+(\[.+)?)/',$attribute,$matches))
  5815. $attribute=$matches[1]; // we get: name[b][c]
  5816. if(($pos=strpos($attribute,'['))===false)
  5817. return $model->$attribute;
  5818. }
  5819. $name=substr($attribute,0,$pos);
  5820. $value=$model->$name;
  5821. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5822. {
  5823. if((is_array($value) || $value instanceof ArrayAccess) && isset($value[$id]))
  5824. $value=$value[$id];
  5825. else
  5826. return null;
  5827. }
  5828. return $value;
  5829. }
  5830. else
  5831. return $model->$attribute;
  5832. }
  5833. protected static function addErrorCss(&$htmlOptions)
  5834. {
  5835. if(empty(self::$errorCss))
  5836. return;
  5837. if(isset($htmlOptions['class']))
  5838. $htmlOptions['class'].=' '.self::$errorCss;
  5839. else
  5840. $htmlOptions['class']=self::$errorCss;
  5841. }
  5842. public static function renderAttributes($htmlOptions)
  5843. {
  5844. static $specialAttributes=array(
  5845. 'async'=>1,
  5846. 'autofocus'=>1,
  5847. 'autoplay'=>1,
  5848. 'checked'=>1,
  5849. 'controls'=>1,
  5850. 'declare'=>1,
  5851. 'default'=>1,
  5852. 'defer'=>1,
  5853. 'disabled'=>1,
  5854. 'formnovalidate'=>1,
  5855. 'hidden'=>1,
  5856. 'ismap'=>1,
  5857. 'loop'=>1,
  5858. 'multiple'=>1,
  5859. 'muted'=>1,
  5860. 'nohref'=>1,
  5861. 'noresize'=>1,
  5862. 'novalidate'=>1,
  5863. 'open'=>1,
  5864. 'readonly'=>1,
  5865. 'required'=>1,
  5866. 'reversed'=>1,
  5867. 'scoped'=>1,
  5868. 'seamless'=>1,
  5869. 'selected'=>1,
  5870. 'typemustmatch'=>1,
  5871. );
  5872. if($htmlOptions===array())
  5873. return '';
  5874. $html='';
  5875. if(isset($htmlOptions['encode']))
  5876. {
  5877. $raw=!$htmlOptions['encode'];
  5878. unset($htmlOptions['encode']);
  5879. }
  5880. else
  5881. $raw=false;
  5882. foreach($htmlOptions as $name=>$value)
  5883. {
  5884. if(isset($specialAttributes[$name]))
  5885. {
  5886. if($value)
  5887. {
  5888. $html .= ' ' . $name;
  5889. if(self::$renderSpecialAttributesValue)
  5890. $html .= '="' . $name . '"';
  5891. }
  5892. }
  5893. elseif($value!==null)
  5894. $html .= ' ' . $name . '="' . ($raw ? $value : self::encode($value)) . '"';
  5895. }
  5896. return $html;
  5897. }
  5898. }
  5899. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  5900. {
  5901. public $enableSkin=false;
  5902. public $widgets=array();
  5903. public $skinnableWidgets;
  5904. public $skinPath;
  5905. private $_skins=array(); // class name, skin name, property name => value
  5906. public function init()
  5907. {
  5908. parent::init();
  5909. if($this->enableSkin && $this->skinPath===null)
  5910. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  5911. }
  5912. public function createWidget($owner,$className,$properties=array())
  5913. {
  5914. $className=Yii::import($className,true);
  5915. $widget=new $className($owner);
  5916. if(isset($this->widgets[$className]))
  5917. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  5918. if($this->enableSkin)
  5919. {
  5920. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  5921. {
  5922. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  5923. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  5924. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  5925. }
  5926. }
  5927. foreach($properties as $name=>$value)
  5928. $widget->$name=$value;
  5929. return $widget;
  5930. }
  5931. protected function getSkin($className,$skinName)
  5932. {
  5933. if(!isset($this->_skins[$className][$skinName]))
  5934. {
  5935. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  5936. if(is_file($skinFile))
  5937. $this->_skins[$className]=require($skinFile);
  5938. else
  5939. $this->_skins[$className]=array();
  5940. if(($theme=Yii::app()->getTheme())!==null)
  5941. {
  5942. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  5943. if(is_file($skinFile))
  5944. {
  5945. $skins=require($skinFile);
  5946. foreach($skins as $name=>$skin)
  5947. $this->_skins[$className][$name]=$skin;
  5948. }
  5949. }
  5950. if(!isset($this->_skins[$className][$skinName]))
  5951. $this->_skins[$className][$skinName]=array();
  5952. }
  5953. return $this->_skins[$className][$skinName];
  5954. }
  5955. }
  5956. class CWidget extends CBaseController
  5957. {
  5958. public $actionPrefix;
  5959. public $skin='default';
  5960. private static $_viewPaths;
  5961. private static $_counter=0;
  5962. private $_id;
  5963. private $_owner;
  5964. public static function actions()
  5965. {
  5966. return array();
  5967. }
  5968. public function __construct($owner=null)
  5969. {
  5970. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  5971. }
  5972. public function getOwner()
  5973. {
  5974. return $this->_owner;
  5975. }
  5976. public function getId($autoGenerate=true)
  5977. {
  5978. if($this->_id!==null)
  5979. return $this->_id;
  5980. elseif($autoGenerate)
  5981. return $this->_id='yw'.self::$_counter++;
  5982. }
  5983. public function setId($value)
  5984. {
  5985. $this->_id=$value;
  5986. }
  5987. public function getController()
  5988. {
  5989. if($this->_owner instanceof CController)
  5990. return $this->_owner;
  5991. else
  5992. return Yii::app()->getController();
  5993. }
  5994. public function init()
  5995. {
  5996. }
  5997. public function run()
  5998. {
  5999. }
  6000. public function getViewPath($checkTheme=false)
  6001. {
  6002. $className=get_class($this);
  6003. $scope=$checkTheme?'theme':'local';
  6004. if(isset(self::$_viewPaths[$className][$scope]))
  6005. return self::$_viewPaths[$className][$scope];
  6006. else
  6007. {
  6008. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  6009. {
  6010. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  6011. if(strpos($className,'\\')!==false) // namespaced class
  6012. $path.=str_replace('\\','_',ltrim($className,'\\'));
  6013. else
  6014. $path.=$className;
  6015. if(is_dir($path))
  6016. return self::$_viewPaths[$className]['theme']=$path;
  6017. }
  6018. $class=new ReflectionClass($className);
  6019. return self::$_viewPaths[$className]['local']=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  6020. }
  6021. }
  6022. public function getViewFile($viewName)
  6023. {
  6024. if(($renderer=Yii::app()->getViewRenderer())!==null)
  6025. $extension=$renderer->fileExtension;
  6026. else
  6027. $extension='.php';
  6028. if(strpos($viewName,'.')) // a path alias
  6029. $viewFile=Yii::getPathOfAlias($viewName);
  6030. else
  6031. {
  6032. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  6033. if(is_file($viewFile.$extension))
  6034. return Yii::app()->findLocalizedFile($viewFile.$extension);
  6035. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  6036. return Yii::app()->findLocalizedFile($viewFile.'.php');
  6037. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  6038. }
  6039. if(is_file($viewFile.$extension))
  6040. return Yii::app()->findLocalizedFile($viewFile.$extension);
  6041. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  6042. return Yii::app()->findLocalizedFile($viewFile.'.php');
  6043. else
  6044. return false;
  6045. }
  6046. public function render($view,$data=null,$return=false)
  6047. {
  6048. if(($viewFile=$this->getViewFile($view))!==false)
  6049. return $this->renderFile($viewFile,$data,$return);
  6050. else
  6051. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  6052. array('{widget}'=>get_class($this), '{view}'=>$view)));
  6053. }
  6054. }
  6055. class CClientScript extends CApplicationComponent
  6056. {
  6057. const POS_HEAD=0;
  6058. const POS_BEGIN=1;
  6059. const POS_END=2;
  6060. const POS_LOAD=3;
  6061. const POS_READY=4;
  6062. public $enableJavaScript=true;
  6063. public $scriptMap=array();
  6064. public $packages=array();
  6065. public $corePackages;
  6066. public $scripts=array();
  6067. protected $cssFiles=array();
  6068. protected $scriptFiles=array();
  6069. protected $metaTags=array();
  6070. protected $linkTags=array();
  6071. protected $css=array();
  6072. protected $hasScripts=false;
  6073. protected $coreScripts=array();
  6074. public $coreScriptPosition=self::POS_HEAD;
  6075. public $defaultScriptFilePosition=self::POS_HEAD;
  6076. public $defaultScriptPosition=self::POS_READY;
  6077. private $_baseUrl;
  6078. public function reset()
  6079. {
  6080. $this->hasScripts=false;
  6081. $this->coreScripts=array();
  6082. $this->cssFiles=array();
  6083. $this->css=array();
  6084. $this->scriptFiles=array();
  6085. $this->scripts=array();
  6086. $this->metaTags=array();
  6087. $this->linkTags=array();
  6088. $this->recordCachingAction('clientScript','reset',array());
  6089. }
  6090. public function render(&$output)
  6091. {
  6092. if(!$this->hasScripts)
  6093. return;
  6094. $this->renderCoreScripts();
  6095. if(!empty($this->scriptMap))
  6096. $this->remapScripts();
  6097. $this->unifyScripts();
  6098. $this->renderHead($output);
  6099. if($this->enableJavaScript)
  6100. {
  6101. $this->renderBodyBegin($output);
  6102. $this->renderBodyEnd($output);
  6103. }
  6104. }
  6105. protected function unifyScripts()
  6106. {
  6107. if(!$this->enableJavaScript)
  6108. return;
  6109. $map=array();
  6110. if(isset($this->scriptFiles[self::POS_HEAD]))
  6111. $map=$this->scriptFiles[self::POS_HEAD];
  6112. if(isset($this->scriptFiles[self::POS_BEGIN]))
  6113. {
  6114. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile=>$scriptFileValue)
  6115. {
  6116. if(isset($map[$scriptFile]))
  6117. unset($this->scriptFiles[self::POS_BEGIN][$scriptFile]);
  6118. else
  6119. $map[$scriptFile]=true;
  6120. }
  6121. }
  6122. if(isset($this->scriptFiles[self::POS_END]))
  6123. {
  6124. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  6125. {
  6126. if(isset($map[$key]))
  6127. unset($this->scriptFiles[self::POS_END][$key]);
  6128. }
  6129. }
  6130. }
  6131. protected function remapScripts()
  6132. {
  6133. $cssFiles=array();
  6134. foreach($this->cssFiles as $url=>$media)
  6135. {
  6136. $name=basename($url);
  6137. if(isset($this->scriptMap[$name]))
  6138. {
  6139. if($this->scriptMap[$name]!==false)
  6140. $cssFiles[$this->scriptMap[$name]]=$media;
  6141. }
  6142. elseif(isset($this->scriptMap['*.css']))
  6143. {
  6144. if($this->scriptMap['*.css']!==false)
  6145. $cssFiles[$this->scriptMap['*.css']]=$media;
  6146. }
  6147. else
  6148. $cssFiles[$url]=$media;
  6149. }
  6150. $this->cssFiles=$cssFiles;
  6151. $jsFiles=array();
  6152. foreach($this->scriptFiles as $position=>$scriptFiles)
  6153. {
  6154. $jsFiles[$position]=array();
  6155. foreach($scriptFiles as $scriptFile=>$scriptFileValue)
  6156. {
  6157. $name=basename($scriptFile);
  6158. if(isset($this->scriptMap[$name]))
  6159. {
  6160. if($this->scriptMap[$name]!==false)
  6161. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  6162. }
  6163. elseif(isset($this->scriptMap['*.js']))
  6164. {
  6165. if($this->scriptMap['*.js']!==false)
  6166. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  6167. }
  6168. else
  6169. $jsFiles[$position][$scriptFile]=$scriptFileValue;
  6170. }
  6171. }
  6172. $this->scriptFiles=$jsFiles;
  6173. }
  6174. protected function renderScriptBatch(array $scripts)
  6175. {
  6176. $html = '';
  6177. $scriptBatches = array();
  6178. foreach($scripts as $scriptValue)
  6179. {
  6180. if(is_array($scriptValue))
  6181. {
  6182. $scriptContent = $scriptValue['content'];
  6183. unset($scriptValue['content']);
  6184. $scriptHtmlOptions = $scriptValue;
  6185. }
  6186. else
  6187. {
  6188. $scriptContent = $scriptValue;
  6189. $scriptHtmlOptions = array();
  6190. }
  6191. $key=serialize(ksort($scriptHtmlOptions));
  6192. $scriptBatches[$key]['htmlOptions']=$scriptHtmlOptions;
  6193. $scriptBatches[$key]['scripts'][]=$scriptContent;
  6194. }
  6195. foreach($scriptBatches as $scriptBatch)
  6196. if(!empty($scriptBatch['scripts']))
  6197. $html.=CHtml::script(implode("\n",$scriptBatch['scripts']),$scriptBatch['htmlOptions'])."\n";
  6198. return $html;
  6199. }
  6200. public function renderCoreScripts()
  6201. {
  6202. if($this->coreScripts===null)
  6203. return;
  6204. $cssFiles=array();
  6205. $jsFiles=array();
  6206. foreach($this->coreScripts as $name=>$package)
  6207. {
  6208. $baseUrl=$this->getPackageBaseUrl($name);
  6209. if(!empty($package['js']))
  6210. {
  6211. foreach($package['js'] as $js)
  6212. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  6213. }
  6214. if(!empty($package['css']))
  6215. {
  6216. foreach($package['css'] as $css)
  6217. $cssFiles[$baseUrl.'/'.$css]='';
  6218. }
  6219. }
  6220. // merge in place
  6221. if($cssFiles!==array())
  6222. {
  6223. foreach($this->cssFiles as $cssFile=>$media)
  6224. $cssFiles[$cssFile]=$media;
  6225. $this->cssFiles=$cssFiles;
  6226. }
  6227. if($jsFiles!==array())
  6228. {
  6229. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  6230. {
  6231. foreach($this->scriptFiles[$this->coreScriptPosition] as $url => $value)
  6232. $jsFiles[$url]=$value;
  6233. }
  6234. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  6235. }
  6236. }
  6237. public function renderHead(&$output)
  6238. {
  6239. $html='';
  6240. foreach($this->metaTags as $meta)
  6241. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  6242. foreach($this->linkTags as $link)
  6243. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  6244. foreach($this->cssFiles as $url=>$media)
  6245. $html.=CHtml::cssFile($url,$media)."\n";
  6246. foreach($this->css as $css)
  6247. $html.=CHtml::css($css[0],$css[1])."\n";
  6248. if($this->enableJavaScript)
  6249. {
  6250. if(isset($this->scriptFiles[self::POS_HEAD]))
  6251. {
  6252. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFileValueUrl=>$scriptFileValue)
  6253. {
  6254. if(is_array($scriptFileValue))
  6255. $html.=CHtml::scriptFile($scriptFileValueUrl,$scriptFileValue)."\n";
  6256. else
  6257. $html.=CHtml::scriptFile($scriptFileValueUrl)."\n";
  6258. }
  6259. }
  6260. if(isset($this->scripts[self::POS_HEAD]))
  6261. $html.=$this->renderScriptBatch($this->scripts[self::POS_HEAD]);
  6262. }
  6263. if($html!=='')
  6264. {
  6265. $count=0;
  6266. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  6267. if($count)
  6268. $output=str_replace('<###head###>',$html,$output);
  6269. else
  6270. $output=$html.$output;
  6271. }
  6272. }
  6273. public function renderBodyBegin(&$output)
  6274. {
  6275. $html='';
  6276. if(isset($this->scriptFiles[self::POS_BEGIN]))
  6277. {
  6278. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFileUrl=>$scriptFileValue)
  6279. {
  6280. if(is_array($scriptFileValue))
  6281. $html.=CHtml::scriptFile($scriptFileUrl,$scriptFileValue)."\n";
  6282. else
  6283. $html.=CHtml::scriptFile($scriptFileUrl)."\n";
  6284. }
  6285. }
  6286. if(isset($this->scripts[self::POS_BEGIN]))
  6287. $html.=$this->renderScriptBatch($this->scripts[self::POS_BEGIN]);
  6288. if($html!=='')
  6289. {
  6290. $count=0;
  6291. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  6292. if($count)
  6293. $output=str_replace('<###begin###>',$html,$output);
  6294. else
  6295. $output=$html.$output;
  6296. }
  6297. }
  6298. public function renderBodyEnd(&$output)
  6299. {
  6300. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  6301. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  6302. return;
  6303. $fullPage=0;
  6304. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  6305. $html='';
  6306. if(isset($this->scriptFiles[self::POS_END]))
  6307. {
  6308. foreach($this->scriptFiles[self::POS_END] as $scriptFileUrl=>$scriptFileValue)
  6309. {
  6310. if(is_array($scriptFileValue))
  6311. $html.=CHtml::scriptFile($scriptFileUrl,$scriptFileValue)."\n";
  6312. else
  6313. $html.=CHtml::scriptFile($scriptFileUrl)."\n";
  6314. }
  6315. }
  6316. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  6317. if(isset($this->scripts[self::POS_READY]))
  6318. {
  6319. if($fullPage)
  6320. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  6321. else
  6322. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  6323. }
  6324. if(isset($this->scripts[self::POS_LOAD]))
  6325. {
  6326. if($fullPage)
  6327. $scripts[]="jQuery(window).on('load',function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  6328. else
  6329. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  6330. }
  6331. if(!empty($scripts))
  6332. $html.=$this->renderScriptBatch($scripts);
  6333. if($fullPage)
  6334. $output=str_replace('<###end###>',$html,$output);
  6335. else
  6336. $output=$output.$html;
  6337. }
  6338. public function getCoreScriptUrl()
  6339. {
  6340. if($this->_baseUrl!==null)
  6341. return $this->_baseUrl;
  6342. else
  6343. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  6344. }
  6345. public function setCoreScriptUrl($value)
  6346. {
  6347. $this->_baseUrl=$value;
  6348. }
  6349. public function getPackageBaseUrl($name)
  6350. {
  6351. if(!isset($this->coreScripts[$name]))
  6352. return false;
  6353. $package=$this->coreScripts[$name];
  6354. if(isset($package['baseUrl']))
  6355. {
  6356. $baseUrl=$package['baseUrl'];
  6357. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  6358. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  6359. $baseUrl=rtrim($baseUrl,'/');
  6360. }
  6361. elseif(isset($package['basePath']))
  6362. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  6363. else
  6364. $baseUrl=$this->getCoreScriptUrl();
  6365. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  6366. }
  6367. public function registerPackage($name)
  6368. {
  6369. return $this->registerCoreScript($name);
  6370. }
  6371. public function registerCoreScript($name)
  6372. {
  6373. if(isset($this->coreScripts[$name]))
  6374. return $this;
  6375. if(isset($this->packages[$name]))
  6376. $package=$this->packages[$name];
  6377. else
  6378. {
  6379. if($this->corePackages===null)
  6380. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  6381. if(isset($this->corePackages[$name]))
  6382. $package=$this->corePackages[$name];
  6383. }
  6384. if(isset($package))
  6385. {
  6386. if(!empty($package['depends']))
  6387. {
  6388. foreach($package['depends'] as $p)
  6389. $this->registerCoreScript($p);
  6390. }
  6391. $this->coreScripts[$name]=$package;
  6392. $this->hasScripts=true;
  6393. $params=func_get_args();
  6394. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  6395. }
  6396. return $this;
  6397. }
  6398. public function registerCssFile($url,$media='')
  6399. {
  6400. $this->hasScripts=true;
  6401. $this->cssFiles[$url]=$media;
  6402. $params=func_get_args();
  6403. $this->recordCachingAction('clientScript','registerCssFile',$params);
  6404. return $this;
  6405. }
  6406. public function registerCss($id,$css,$media='')
  6407. {
  6408. $this->hasScripts=true;
  6409. $this->css[$id]=array($css,$media);
  6410. $params=func_get_args();
  6411. $this->recordCachingAction('clientScript','registerCss',$params);
  6412. return $this;
  6413. }
  6414. public function registerScriptFile($url,$position=null,array $htmlOptions=array())
  6415. {
  6416. if($position===null)
  6417. $position=$this->defaultScriptFilePosition;
  6418. $this->hasScripts=true;
  6419. if(empty($htmlOptions))
  6420. $value=$url;
  6421. else
  6422. {
  6423. $value=$htmlOptions;
  6424. $value['src']=$url;
  6425. }
  6426. $this->scriptFiles[$position][$url]=$value;
  6427. $params=func_get_args();
  6428. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  6429. return $this;
  6430. }
  6431. public function registerScript($id,$script,$position=null,array $htmlOptions=array())
  6432. {
  6433. if($position===null)
  6434. $position=$this->defaultScriptPosition;
  6435. $this->hasScripts=true;
  6436. if(empty($htmlOptions))
  6437. $scriptValue=$script;
  6438. else
  6439. {
  6440. if($position==self::POS_LOAD || $position==self::POS_READY)
  6441. throw new CException(Yii::t('yii','Script HTML options are not allowed for "CClientScript::POS_LOAD" and "CClientScript::POS_READY".'));
  6442. $scriptValue=$htmlOptions;
  6443. $scriptValue['content']=$script;
  6444. }
  6445. $this->scripts[$position][$id]=$scriptValue;
  6446. if($position===self::POS_READY || $position===self::POS_LOAD)
  6447. $this->registerCoreScript('jquery');
  6448. $params=func_get_args();
  6449. $this->recordCachingAction('clientScript','registerScript',$params);
  6450. return $this;
  6451. }
  6452. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array(),$id=null)
  6453. {
  6454. $this->hasScripts=true;
  6455. if($name!==null)
  6456. $options['name']=$name;
  6457. if($httpEquiv!==null)
  6458. $options['http-equiv']=$httpEquiv;
  6459. $options['content']=$content;
  6460. $this->metaTags[null===$id?count($this->metaTags):$id]=$options;
  6461. $params=func_get_args();
  6462. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  6463. return $this;
  6464. }
  6465. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  6466. {
  6467. $this->hasScripts=true;
  6468. if($relation!==null)
  6469. $options['rel']=$relation;
  6470. if($type!==null)
  6471. $options['type']=$type;
  6472. if($href!==null)
  6473. $options['href']=$href;
  6474. if($media!==null)
  6475. $options['media']=$media;
  6476. $this->linkTags[serialize($options)]=$options;
  6477. $params=func_get_args();
  6478. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  6479. return $this;
  6480. }
  6481. public function isCssFileRegistered($url)
  6482. {
  6483. return isset($this->cssFiles[$url]);
  6484. }
  6485. public function isCssRegistered($id)
  6486. {
  6487. return isset($this->css[$id]);
  6488. }
  6489. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  6490. {
  6491. return isset($this->scriptFiles[$position][$url]);
  6492. }
  6493. public function isScriptRegistered($id,$position=self::POS_READY)
  6494. {
  6495. return isset($this->scripts[$position][$id]);
  6496. }
  6497. protected function recordCachingAction($context,$method,$params)
  6498. {
  6499. if(($controller=Yii::app()->getController())!==null)
  6500. $controller->recordCachingAction($context,$method,$params);
  6501. }
  6502. public function addPackage($name,$definition)
  6503. {
  6504. $this->packages[$name]=$definition;
  6505. return $this;
  6506. }
  6507. }
  6508. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  6509. {
  6510. private $_d=array();
  6511. private $_c=0;
  6512. private $_r=false;
  6513. public function __construct($data=null,$readOnly=false)
  6514. {
  6515. if($data!==null)
  6516. $this->copyFrom($data);
  6517. $this->setReadOnly($readOnly);
  6518. }
  6519. public function getReadOnly()
  6520. {
  6521. return $this->_r;
  6522. }
  6523. protected function setReadOnly($value)
  6524. {
  6525. $this->_r=$value;
  6526. }
  6527. public function getIterator()
  6528. {
  6529. return new CListIterator($this->_d);
  6530. }
  6531. public function count()
  6532. {
  6533. return $this->getCount();
  6534. }
  6535. public function getCount()
  6536. {
  6537. return $this->_c;
  6538. }
  6539. public function itemAt($index)
  6540. {
  6541. if(isset($this->_d[$index]))
  6542. return $this->_d[$index];
  6543. elseif($index>=0 && $index<$this->_c) // in case the value is null
  6544. return $this->_d[$index];
  6545. else
  6546. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6547. array('{index}'=>$index)));
  6548. }
  6549. public function add($item)
  6550. {
  6551. $this->insertAt($this->_c,$item);
  6552. return $this->_c-1;
  6553. }
  6554. public function insertAt($index,$item)
  6555. {
  6556. if(!$this->_r)
  6557. {
  6558. if($index===$this->_c)
  6559. $this->_d[$this->_c++]=$item;
  6560. elseif($index>=0 && $index<$this->_c)
  6561. {
  6562. array_splice($this->_d,$index,0,array($item));
  6563. $this->_c++;
  6564. }
  6565. else
  6566. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6567. array('{index}'=>$index)));
  6568. }
  6569. else
  6570. throw new CException(Yii::t('yii','The list is read only.'));
  6571. }
  6572. public function remove($item)
  6573. {
  6574. if(($index=$this->indexOf($item))>=0)
  6575. {
  6576. $this->removeAt($index);
  6577. return $index;
  6578. }
  6579. else
  6580. return false;
  6581. }
  6582. public function removeAt($index)
  6583. {
  6584. if(!$this->_r)
  6585. {
  6586. if($index>=0 && $index<$this->_c)
  6587. {
  6588. $this->_c--;
  6589. if($index===$this->_c)
  6590. return array_pop($this->_d);
  6591. else
  6592. {
  6593. $item=$this->_d[$index];
  6594. array_splice($this->_d,$index,1);
  6595. return $item;
  6596. }
  6597. }
  6598. else
  6599. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6600. array('{index}'=>$index)));
  6601. }
  6602. else
  6603. throw new CException(Yii::t('yii','The list is read only.'));
  6604. }
  6605. public function clear()
  6606. {
  6607. for($i=$this->_c-1;$i>=0;--$i)
  6608. $this->removeAt($i);
  6609. }
  6610. public function contains($item)
  6611. {
  6612. return $this->indexOf($item)>=0;
  6613. }
  6614. public function indexOf($item)
  6615. {
  6616. if(($index=array_search($item,$this->_d,true))!==false)
  6617. return $index;
  6618. else
  6619. return -1;
  6620. }
  6621. public function toArray()
  6622. {
  6623. return $this->_d;
  6624. }
  6625. public function copyFrom($data)
  6626. {
  6627. if(is_array($data) || ($data instanceof Traversable))
  6628. {
  6629. if($this->_c>0)
  6630. $this->clear();
  6631. if($data instanceof CList)
  6632. $data=$data->_d;
  6633. foreach($data as $item)
  6634. $this->add($item);
  6635. }
  6636. elseif($data!==null)
  6637. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6638. }
  6639. public function mergeWith($data)
  6640. {
  6641. if(is_array($data) || ($data instanceof Traversable))
  6642. {
  6643. if($data instanceof CList)
  6644. $data=$data->_d;
  6645. foreach($data as $item)
  6646. $this->add($item);
  6647. }
  6648. elseif($data!==null)
  6649. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6650. }
  6651. public function offsetExists($offset)
  6652. {
  6653. return ($offset>=0 && $offset<$this->_c);
  6654. }
  6655. public function offsetGet($offset)
  6656. {
  6657. return $this->itemAt($offset);
  6658. }
  6659. public function offsetSet($offset,$item)
  6660. {
  6661. if($offset===null || $offset===$this->_c)
  6662. $this->insertAt($this->_c,$item);
  6663. else
  6664. {
  6665. $this->removeAt($offset);
  6666. $this->insertAt($offset,$item);
  6667. }
  6668. }
  6669. public function offsetUnset($offset)
  6670. {
  6671. $this->removeAt($offset);
  6672. }
  6673. }
  6674. class CFilterChain extends CList
  6675. {
  6676. public $controller;
  6677. public $action;
  6678. public $filterIndex=0;
  6679. public function __construct($controller,$action)
  6680. {
  6681. $this->controller=$controller;
  6682. $this->action=$action;
  6683. }
  6684. public static function create($controller,$action,$filters)
  6685. {
  6686. $chain=new CFilterChain($controller,$action);
  6687. $actionID=$action->getId();
  6688. foreach($filters as $filter)
  6689. {
  6690. if(is_string($filter)) // filterName [+|- action1 action2]
  6691. {
  6692. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  6693. {
  6694. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  6695. if(($filter[$pos]==='+')===$matched)
  6696. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  6697. }
  6698. else
  6699. $filter=CInlineFilter::create($controller,$filter);
  6700. }
  6701. elseif(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  6702. {
  6703. if(!isset($filter[0]))
  6704. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  6705. $filterClass=$filter[0];
  6706. unset($filter[0]);
  6707. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  6708. {
  6709. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  6710. if(($filterClass[$pos]==='+')===$matched)
  6711. $filterClass=trim(substr($filterClass,0,$pos));
  6712. else
  6713. continue;
  6714. }
  6715. $filter['class']=$filterClass;
  6716. $filter=Yii::createComponent($filter);
  6717. }
  6718. if(is_object($filter))
  6719. {
  6720. $filter->init();
  6721. $chain->add($filter);
  6722. }
  6723. }
  6724. return $chain;
  6725. }
  6726. public function insertAt($index,$item)
  6727. {
  6728. if($item instanceof IFilter)
  6729. parent::insertAt($index,$item);
  6730. else
  6731. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  6732. }
  6733. public function run()
  6734. {
  6735. if($this->offsetExists($this->filterIndex))
  6736. {
  6737. $filter=$this->itemAt($this->filterIndex++);
  6738. $filter->filter($this);
  6739. }
  6740. else
  6741. $this->controller->runAction($this->action);
  6742. }
  6743. }
  6744. class CFilter extends CComponent implements IFilter
  6745. {
  6746. public function filter($filterChain)
  6747. {
  6748. if($this->preFilter($filterChain))
  6749. {
  6750. $filterChain->run();
  6751. $this->postFilter($filterChain);
  6752. }
  6753. }
  6754. public function init()
  6755. {
  6756. }
  6757. protected function preFilter($filterChain)
  6758. {
  6759. return true;
  6760. }
  6761. protected function postFilter($filterChain)
  6762. {
  6763. }
  6764. }
  6765. class CInlineFilter extends CFilter
  6766. {
  6767. public $name;
  6768. public static function create($controller,$filterName)
  6769. {
  6770. if(method_exists($controller,'filter'.$filterName))
  6771. {
  6772. $filter=new CInlineFilter;
  6773. $filter->name=$filterName;
  6774. return $filter;
  6775. }
  6776. else
  6777. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  6778. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  6779. }
  6780. public function filter($filterChain)
  6781. {
  6782. $method='filter'.$this->name;
  6783. $filterChain->controller->$method($filterChain);
  6784. }
  6785. }
  6786. class CAccessControlFilter extends CFilter
  6787. {
  6788. public $message;
  6789. private $_rules=array();
  6790. public function getRules()
  6791. {
  6792. return $this->_rules;
  6793. }
  6794. public function setRules($rules)
  6795. {
  6796. foreach($rules as $rule)
  6797. {
  6798. if(is_array($rule) && isset($rule[0]))
  6799. {
  6800. $r=new CAccessRule;
  6801. $r->allow=$rule[0]==='allow';
  6802. foreach(array_slice($rule,1) as $name=>$value)
  6803. {
  6804. if($name==='expression' || $name==='roles' || $name==='message' || $name==='deniedCallback')
  6805. $r->$name=$value;
  6806. else
  6807. $r->$name=array_map('strtolower',$value);
  6808. }
  6809. $this->_rules[]=$r;
  6810. }
  6811. }
  6812. }
  6813. protected function preFilter($filterChain)
  6814. {
  6815. $app=Yii::app();
  6816. $request=$app->getRequest();
  6817. $user=$app->getUser();
  6818. $verb=$request->getRequestType();
  6819. $ip=$request->getUserHostAddress();
  6820. foreach($this->getRules() as $rule)
  6821. {
  6822. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  6823. break;
  6824. elseif($allow<0) // denied
  6825. {
  6826. if(isset($rule->deniedCallback))
  6827. call_user_func($rule->deniedCallback, $rule);
  6828. else
  6829. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  6830. return false;
  6831. }
  6832. }
  6833. return true;
  6834. }
  6835. protected function resolveErrorMessage($rule)
  6836. {
  6837. if($rule->message!==null)
  6838. return $rule->message;
  6839. elseif($this->message!==null)
  6840. return $this->message;
  6841. else
  6842. return Yii::t('yii','You are not authorized to perform this action.');
  6843. }
  6844. protected function accessDenied($user,$message)
  6845. {
  6846. if($user->getIsGuest())
  6847. $user->loginRequired();
  6848. else
  6849. throw new CHttpException(403,$message);
  6850. }
  6851. }
  6852. class CAccessRule extends CComponent
  6853. {
  6854. public $allow;
  6855. public $actions;
  6856. public $controllers;
  6857. public $users;
  6858. public $roles;
  6859. public $ips;
  6860. public $verbs;
  6861. public $expression;
  6862. public $message;
  6863. public $deniedCallback;
  6864. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  6865. {
  6866. if($this->isActionMatched($action)
  6867. && $this->isUserMatched($user)
  6868. && $this->isRoleMatched($user)
  6869. && $this->isIpMatched($ip)
  6870. && $this->isVerbMatched($verb)
  6871. && $this->isControllerMatched($controller)
  6872. && $this->isExpressionMatched($user))
  6873. return $this->allow ? 1 : -1;
  6874. else
  6875. return 0;
  6876. }
  6877. protected function isActionMatched($action)
  6878. {
  6879. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  6880. }
  6881. protected function isControllerMatched($controller)
  6882. {
  6883. return empty($this->controllers) || in_array(strtolower($controller->getUniqueId()),$this->controllers);
  6884. }
  6885. protected function isUserMatched($user)
  6886. {
  6887. if(empty($this->users))
  6888. return true;
  6889. foreach($this->users as $u)
  6890. {
  6891. if($u==='*')
  6892. return true;
  6893. elseif($u==='?' && $user->getIsGuest())
  6894. return true;
  6895. elseif($u==='@' && !$user->getIsGuest())
  6896. return true;
  6897. elseif(!strcasecmp($u,$user->getName()))
  6898. return true;
  6899. }
  6900. return false;
  6901. }
  6902. protected function isRoleMatched($user)
  6903. {
  6904. if(empty($this->roles))
  6905. return true;
  6906. foreach($this->roles as $key=>$role)
  6907. {
  6908. if(is_numeric($key))
  6909. {
  6910. if($user->checkAccess($role))
  6911. return true;
  6912. }
  6913. else
  6914. {
  6915. if($user->checkAccess($key,$role))
  6916. return true;
  6917. }
  6918. }
  6919. return false;
  6920. }
  6921. protected function isIpMatched($ip)
  6922. {
  6923. if(empty($this->ips))
  6924. return true;
  6925. foreach($this->ips as $rule)
  6926. {
  6927. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  6928. return true;
  6929. }
  6930. return false;
  6931. }
  6932. protected function isVerbMatched($verb)
  6933. {
  6934. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  6935. }
  6936. protected function isExpressionMatched($user)
  6937. {
  6938. if($this->expression===null)
  6939. return true;
  6940. else
  6941. return $this->evaluateExpression($this->expression, array('user'=>$user));
  6942. }
  6943. }
  6944. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  6945. {
  6946. private $_errors=array(); // attribute name => array of errors
  6947. private $_validators; // validators
  6948. private $_scenario=''; // scenario
  6949. abstract public function attributeNames();
  6950. public function rules()
  6951. {
  6952. return array();
  6953. }
  6954. public function behaviors()
  6955. {
  6956. return array();
  6957. }
  6958. public function attributeLabels()
  6959. {
  6960. return array();
  6961. }
  6962. public function validate($attributes=null, $clearErrors=true)
  6963. {
  6964. if($clearErrors)
  6965. $this->clearErrors();
  6966. if($this->beforeValidate())
  6967. {
  6968. foreach($this->getValidators() as $validator)
  6969. $validator->validate($this,$attributes);
  6970. $this->afterValidate();
  6971. return !$this->hasErrors();
  6972. }
  6973. else
  6974. return false;
  6975. }
  6976. protected function afterConstruct()
  6977. {
  6978. if($this->hasEventHandler('onAfterConstruct'))
  6979. $this->onAfterConstruct(new CEvent($this));
  6980. }
  6981. protected function beforeValidate()
  6982. {
  6983. $event=new CModelEvent($this);
  6984. $this->onBeforeValidate($event);
  6985. return $event->isValid;
  6986. }
  6987. protected function afterValidate()
  6988. {
  6989. $this->onAfterValidate(new CEvent($this));
  6990. }
  6991. public function onAfterConstruct($event)
  6992. {
  6993. $this->raiseEvent('onAfterConstruct',$event);
  6994. }
  6995. public function onBeforeValidate($event)
  6996. {
  6997. $this->raiseEvent('onBeforeValidate',$event);
  6998. }
  6999. public function onAfterValidate($event)
  7000. {
  7001. $this->raiseEvent('onAfterValidate',$event);
  7002. }
  7003. public function getValidatorList()
  7004. {
  7005. if($this->_validators===null)
  7006. $this->_validators=$this->createValidators();
  7007. return $this->_validators;
  7008. }
  7009. public function getValidators($attribute=null)
  7010. {
  7011. if($this->_validators===null)
  7012. $this->_validators=$this->createValidators();
  7013. $validators=array();
  7014. $scenario=$this->getScenario();
  7015. foreach($this->_validators as $validator)
  7016. {
  7017. if($validator->applyTo($scenario))
  7018. {
  7019. if($attribute===null || in_array($attribute,$validator->attributes,true))
  7020. $validators[]=$validator;
  7021. }
  7022. }
  7023. return $validators;
  7024. }
  7025. public function createValidators()
  7026. {
  7027. $validators=new CList;
  7028. foreach($this->rules() as $rule)
  7029. {
  7030. if(isset($rule[0],$rule[1])) // attributes, validator name
  7031. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  7032. else
  7033. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  7034. array('{class}'=>get_class($this))));
  7035. }
  7036. return $validators;
  7037. }
  7038. public function isAttributeRequired($attribute)
  7039. {
  7040. foreach($this->getValidators($attribute) as $validator)
  7041. {
  7042. if($validator instanceof CRequiredValidator)
  7043. return true;
  7044. }
  7045. return false;
  7046. }
  7047. public function isAttributeSafe($attribute)
  7048. {
  7049. $attributes=$this->getSafeAttributeNames();
  7050. return in_array($attribute,$attributes);
  7051. }
  7052. public function getAttributeLabel($attribute)
  7053. {
  7054. $labels=$this->attributeLabels();
  7055. if(isset($labels[$attribute]))
  7056. return $labels[$attribute];
  7057. else
  7058. return $this->generateAttributeLabel($attribute);
  7059. }
  7060. public function hasErrors($attribute=null)
  7061. {
  7062. if($attribute===null)
  7063. return $this->_errors!==array();
  7064. else
  7065. return isset($this->_errors[$attribute]);
  7066. }
  7067. public function getErrors($attribute=null)
  7068. {
  7069. if($attribute===null)
  7070. return $this->_errors;
  7071. else
  7072. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  7073. }
  7074. public function getError($attribute)
  7075. {
  7076. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  7077. }
  7078. public function addError($attribute,$error)
  7079. {
  7080. $this->_errors[$attribute][]=$error;
  7081. }
  7082. public function addErrors($errors)
  7083. {
  7084. foreach($errors as $attribute=>$error)
  7085. {
  7086. if(is_array($error))
  7087. {
  7088. foreach($error as $e)
  7089. $this->addError($attribute, $e);
  7090. }
  7091. else
  7092. $this->addError($attribute, $error);
  7093. }
  7094. }
  7095. public function clearErrors($attribute=null)
  7096. {
  7097. if($attribute===null)
  7098. $this->_errors=array();
  7099. else
  7100. unset($this->_errors[$attribute]);
  7101. }
  7102. public function generateAttributeLabel($name)
  7103. {
  7104. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  7105. }
  7106. public function getAttributes($names=null)
  7107. {
  7108. $values=array();
  7109. foreach($this->attributeNames() as $name)
  7110. $values[$name]=$this->$name;
  7111. if(is_array($names))
  7112. {
  7113. $values2=array();
  7114. foreach($names as $name)
  7115. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  7116. return $values2;
  7117. }
  7118. else
  7119. return $values;
  7120. }
  7121. public function setAttributes($values,$safeOnly=true)
  7122. {
  7123. if(!is_array($values))
  7124. return;
  7125. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  7126. foreach($values as $name=>$value)
  7127. {
  7128. if(isset($attributes[$name]))
  7129. $this->$name=$value;
  7130. elseif($safeOnly)
  7131. $this->onUnsafeAttribute($name,$value);
  7132. }
  7133. }
  7134. public function unsetAttributes($names=null)
  7135. {
  7136. if($names===null)
  7137. $names=$this->attributeNames();
  7138. foreach($names as $name)
  7139. $this->$name=null;
  7140. }
  7141. public function onUnsafeAttribute($name,$value)
  7142. {
  7143. if(YII_DEBUG)
  7144. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  7145. }
  7146. public function getScenario()
  7147. {
  7148. return $this->_scenario;
  7149. }
  7150. public function setScenario($value)
  7151. {
  7152. $this->_scenario=$value;
  7153. }
  7154. public function getSafeAttributeNames()
  7155. {
  7156. $attributes=array();
  7157. $unsafe=array();
  7158. foreach($this->getValidators() as $validator)
  7159. {
  7160. if(!$validator->safe)
  7161. {
  7162. foreach($validator->attributes as $name)
  7163. $unsafe[]=$name;
  7164. }
  7165. else
  7166. {
  7167. foreach($validator->attributes as $name)
  7168. $attributes[$name]=true;
  7169. }
  7170. }
  7171. foreach($unsafe as $name)
  7172. unset($attributes[$name]);
  7173. return array_keys($attributes);
  7174. }
  7175. public function getIterator()
  7176. {
  7177. $attributes=$this->getAttributes();
  7178. return new CMapIterator($attributes);
  7179. }
  7180. public function offsetExists($offset)
  7181. {
  7182. return property_exists($this,$offset);
  7183. }
  7184. public function offsetGet($offset)
  7185. {
  7186. return $this->$offset;
  7187. }
  7188. public function offsetSet($offset,$item)
  7189. {
  7190. $this->$offset=$item;
  7191. }
  7192. public function offsetUnset($offset)
  7193. {
  7194. unset($this->$offset);
  7195. }
  7196. }
  7197. abstract class CActiveRecord extends CModel
  7198. {
  7199. const BELONGS_TO='CBelongsToRelation';
  7200. const HAS_ONE='CHasOneRelation';
  7201. const HAS_MANY='CHasManyRelation';
  7202. const MANY_MANY='CManyManyRelation';
  7203. const STAT='CStatRelation';
  7204. public static $db;
  7205. private static $_models=array(); // class name => model
  7206. private static $_md=array(); // class name => meta data
  7207. private $_new=false; // whether this instance is new or not
  7208. private $_attributes=array(); // attribute name => attribute value
  7209. private $_related=array(); // attribute name => related objects
  7210. private $_c; // query criteria (used by finder only)
  7211. private $_pk; // old primary key value
  7212. private $_alias='t'; // the table alias being used for query
  7213. public function __construct($scenario='insert')
  7214. {
  7215. if($scenario===null) // internally used by populateRecord() and model()
  7216. return;
  7217. $this->setScenario($scenario);
  7218. $this->setIsNewRecord(true);
  7219. $this->_attributes=$this->getMetaData()->attributeDefaults;
  7220. $this->init();
  7221. $this->attachBehaviors($this->behaviors());
  7222. $this->afterConstruct();
  7223. }
  7224. public function init()
  7225. {
  7226. }
  7227. public function cache($duration, $dependency=null, $queryCount=1)
  7228. {
  7229. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  7230. return $this;
  7231. }
  7232. public function __sleep()
  7233. {
  7234. return array_keys((array)$this);
  7235. }
  7236. public function __get($name)
  7237. {
  7238. if(isset($this->_attributes[$name]))
  7239. return $this->_attributes[$name];
  7240. elseif(isset($this->getMetaData()->columns[$name]))
  7241. return null;
  7242. elseif(isset($this->_related[$name]))
  7243. return $this->_related[$name];
  7244. elseif(isset($this->getMetaData()->relations[$name]))
  7245. return $this->getRelated($name);
  7246. else
  7247. return parent::__get($name);
  7248. }
  7249. public function __set($name,$value)
  7250. {
  7251. if($this->setAttribute($name,$value)===false)
  7252. {
  7253. if(isset($this->getMetaData()->relations[$name]))
  7254. $this->_related[$name]=$value;
  7255. else
  7256. parent::__set($name,$value);
  7257. }
  7258. }
  7259. public function __isset($name)
  7260. {
  7261. if(isset($this->_attributes[$name]))
  7262. return true;
  7263. elseif(isset($this->getMetaData()->columns[$name]))
  7264. return false;
  7265. elseif(isset($this->_related[$name]))
  7266. return true;
  7267. elseif(isset($this->getMetaData()->relations[$name]))
  7268. return $this->getRelated($name)!==null;
  7269. else
  7270. return parent::__isset($name);
  7271. }
  7272. public function __unset($name)
  7273. {
  7274. if(isset($this->getMetaData()->columns[$name]))
  7275. unset($this->_attributes[$name]);
  7276. elseif(isset($this->getMetaData()->relations[$name]))
  7277. unset($this->_related[$name]);
  7278. else
  7279. parent::__unset($name);
  7280. }
  7281. public function __call($name,$parameters)
  7282. {
  7283. if(isset($this->getMetaData()->relations[$name]))
  7284. {
  7285. if(empty($parameters))
  7286. return $this->getRelated($name,false);
  7287. else
  7288. return $this->getRelated($name,false,$parameters[0]);
  7289. }
  7290. $scopes=$this->scopes();
  7291. if(isset($scopes[$name]))
  7292. {
  7293. $this->getDbCriteria()->mergeWith($scopes[$name]);
  7294. return $this;
  7295. }
  7296. return parent::__call($name,$parameters);
  7297. }
  7298. public function getRelated($name,$refresh=false,$params=array())
  7299. {
  7300. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  7301. return $this->_related[$name];
  7302. $md=$this->getMetaData();
  7303. if(!isset($md->relations[$name]))
  7304. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  7305. array('{class}'=>get_class($this), '{name}'=>$name)));
  7306. $relation=$md->relations[$name];
  7307. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  7308. return $relation instanceof CHasOneRelation ? null : array();
  7309. if($params!==array()) // dynamic query
  7310. {
  7311. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7312. if($exists)
  7313. $save=$this->_related[$name];
  7314. if($params instanceof CDbCriteria)
  7315. $params = $params->toArray();
  7316. $r=array($name=>$params);
  7317. }
  7318. else
  7319. $r=$name;
  7320. unset($this->_related[$name]);
  7321. $finder=$this->getActiveFinder($r);
  7322. $finder->lazyFind($this);
  7323. if(!isset($this->_related[$name]))
  7324. {
  7325. if($relation instanceof CHasManyRelation)
  7326. $this->_related[$name]=array();
  7327. elseif($relation instanceof CStatRelation)
  7328. $this->_related[$name]=$relation->defaultValue;
  7329. else
  7330. $this->_related[$name]=null;
  7331. }
  7332. if($params!==array())
  7333. {
  7334. $results=$this->_related[$name];
  7335. if($exists)
  7336. $this->_related[$name]=$save;
  7337. else
  7338. unset($this->_related[$name]);
  7339. return $results;
  7340. }
  7341. else
  7342. return $this->_related[$name];
  7343. }
  7344. public function hasRelated($name)
  7345. {
  7346. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7347. }
  7348. public function getDbCriteria($createIfNull=true)
  7349. {
  7350. if($this->_c===null)
  7351. {
  7352. if(($c=$this->defaultScope())!==array() || $createIfNull)
  7353. $this->_c=new CDbCriteria($c);
  7354. }
  7355. return $this->_c;
  7356. }
  7357. public function setDbCriteria($criteria)
  7358. {
  7359. $this->_c=$criteria;
  7360. }
  7361. public function defaultScope()
  7362. {
  7363. return array();
  7364. }
  7365. public function resetScope($resetDefault=true)
  7366. {
  7367. if($resetDefault)
  7368. $this->_c=new CDbCriteria();
  7369. else
  7370. $this->_c=null;
  7371. return $this;
  7372. }
  7373. public static function model($className=__CLASS__)
  7374. {
  7375. if(isset(self::$_models[$className]))
  7376. return self::$_models[$className];
  7377. else
  7378. {
  7379. $model=self::$_models[$className]=new $className(null);
  7380. $model->attachBehaviors($model->behaviors());
  7381. return $model;
  7382. }
  7383. }
  7384. public function getMetaData()
  7385. {
  7386. $className=get_class($this);
  7387. if(!array_key_exists($className,self::$_md))
  7388. {
  7389. self::$_md[$className]=null; // preventing recursive invokes of {@link getMetaData()} via {@link __get()}
  7390. self::$_md[$className]=new CActiveRecordMetaData($this);
  7391. }
  7392. return self::$_md[$className];
  7393. }
  7394. public function refreshMetaData()
  7395. {
  7396. $className=get_class($this);
  7397. if(array_key_exists($className,self::$_md))
  7398. unset(self::$_md[$className]);
  7399. }
  7400. public function tableName()
  7401. {
  7402. return get_class($this);
  7403. }
  7404. public function primaryKey()
  7405. {
  7406. }
  7407. public function relations()
  7408. {
  7409. return array();
  7410. }
  7411. public function scopes()
  7412. {
  7413. return array();
  7414. }
  7415. public function attributeNames()
  7416. {
  7417. return array_keys($this->getMetaData()->columns);
  7418. }
  7419. public function getAttributeLabel($attribute)
  7420. {
  7421. $labels=$this->attributeLabels();
  7422. if(isset($labels[$attribute]))
  7423. return $labels[$attribute];
  7424. elseif(strpos($attribute,'.')!==false)
  7425. {
  7426. $segs=explode('.',$attribute);
  7427. $name=array_pop($segs);
  7428. $model=$this;
  7429. foreach($segs as $seg)
  7430. {
  7431. $relations=$model->getMetaData()->relations;
  7432. if(isset($relations[$seg]))
  7433. $model=CActiveRecord::model($relations[$seg]->className);
  7434. else
  7435. break;
  7436. }
  7437. return $model->getAttributeLabel($name);
  7438. }
  7439. else
  7440. return $this->generateAttributeLabel($attribute);
  7441. }
  7442. public function getDbConnection()
  7443. {
  7444. if(self::$db!==null)
  7445. return self::$db;
  7446. else
  7447. {
  7448. self::$db=Yii::app()->getDb();
  7449. if(self::$db instanceof CDbConnection)
  7450. return self::$db;
  7451. else
  7452. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  7453. }
  7454. }
  7455. public function getActiveRelation($name)
  7456. {
  7457. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  7458. }
  7459. public function getTableSchema()
  7460. {
  7461. return $this->getMetaData()->tableSchema;
  7462. }
  7463. public function getCommandBuilder()
  7464. {
  7465. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  7466. }
  7467. public function hasAttribute($name)
  7468. {
  7469. return isset($this->getMetaData()->columns[$name]);
  7470. }
  7471. public function getAttribute($name)
  7472. {
  7473. if(property_exists($this,$name))
  7474. return $this->$name;
  7475. elseif(isset($this->_attributes[$name]))
  7476. return $this->_attributes[$name];
  7477. }
  7478. public function setAttribute($name,$value)
  7479. {
  7480. if(property_exists($this,$name))
  7481. $this->$name=$value;
  7482. elseif(isset($this->getMetaData()->columns[$name]))
  7483. $this->_attributes[$name]=$value;
  7484. else
  7485. return false;
  7486. return true;
  7487. }
  7488. public function addRelatedRecord($name,$record,$index)
  7489. {
  7490. if($index!==false)
  7491. {
  7492. if(!isset($this->_related[$name]))
  7493. $this->_related[$name]=array();
  7494. if($record instanceof CActiveRecord)
  7495. {
  7496. if($index===true)
  7497. $this->_related[$name][]=$record;
  7498. else
  7499. $this->_related[$name][$index]=$record;
  7500. }
  7501. }
  7502. elseif(!isset($this->_related[$name]))
  7503. $this->_related[$name]=$record;
  7504. }
  7505. public function getAttributes($names=true)
  7506. {
  7507. $attributes=$this->_attributes;
  7508. foreach($this->getMetaData()->columns as $name=>$column)
  7509. {
  7510. if(property_exists($this,$name))
  7511. $attributes[$name]=$this->$name;
  7512. elseif($names===true && !isset($attributes[$name]))
  7513. $attributes[$name]=null;
  7514. }
  7515. if(is_array($names))
  7516. {
  7517. $attrs=array();
  7518. foreach($names as $name)
  7519. {
  7520. if(property_exists($this,$name))
  7521. $attrs[$name]=$this->$name;
  7522. else
  7523. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  7524. }
  7525. return $attrs;
  7526. }
  7527. else
  7528. return $attributes;
  7529. }
  7530. public function save($runValidation=true,$attributes=null)
  7531. {
  7532. if(!$runValidation || $this->validate($attributes))
  7533. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  7534. else
  7535. return false;
  7536. }
  7537. public function getIsNewRecord()
  7538. {
  7539. return $this->_new;
  7540. }
  7541. public function setIsNewRecord($value)
  7542. {
  7543. $this->_new=$value;
  7544. }
  7545. public function onBeforeSave($event)
  7546. {
  7547. $this->raiseEvent('onBeforeSave',$event);
  7548. }
  7549. public function onAfterSave($event)
  7550. {
  7551. $this->raiseEvent('onAfterSave',$event);
  7552. }
  7553. public function onBeforeDelete($event)
  7554. {
  7555. $this->raiseEvent('onBeforeDelete',$event);
  7556. }
  7557. public function onAfterDelete($event)
  7558. {
  7559. $this->raiseEvent('onAfterDelete',$event);
  7560. }
  7561. public function onBeforeFind($event)
  7562. {
  7563. $this->raiseEvent('onBeforeFind',$event);
  7564. }
  7565. public function onAfterFind($event)
  7566. {
  7567. $this->raiseEvent('onAfterFind',$event);
  7568. }
  7569. public function getActiveFinder($with)
  7570. {
  7571. return new CActiveFinder($this,$with);
  7572. }
  7573. public function onBeforeCount($event)
  7574. {
  7575. $this->raiseEvent('onBeforeCount',$event);
  7576. }
  7577. protected function beforeSave()
  7578. {
  7579. if($this->hasEventHandler('onBeforeSave'))
  7580. {
  7581. $event=new CModelEvent($this);
  7582. $this->onBeforeSave($event);
  7583. return $event->isValid;
  7584. }
  7585. else
  7586. return true;
  7587. }
  7588. protected function afterSave()
  7589. {
  7590. if($this->hasEventHandler('onAfterSave'))
  7591. $this->onAfterSave(new CEvent($this));
  7592. }
  7593. protected function beforeDelete()
  7594. {
  7595. if($this->hasEventHandler('onBeforeDelete'))
  7596. {
  7597. $event=new CModelEvent($this);
  7598. $this->onBeforeDelete($event);
  7599. return $event->isValid;
  7600. }
  7601. else
  7602. return true;
  7603. }
  7604. protected function afterDelete()
  7605. {
  7606. if($this->hasEventHandler('onAfterDelete'))
  7607. $this->onAfterDelete(new CEvent($this));
  7608. }
  7609. protected function beforeFind()
  7610. {
  7611. if($this->hasEventHandler('onBeforeFind'))
  7612. {
  7613. $event=new CModelEvent($this);
  7614. $this->onBeforeFind($event);
  7615. }
  7616. }
  7617. protected function beforeCount()
  7618. {
  7619. if($this->hasEventHandler('onBeforeCount'))
  7620. $this->onBeforeCount(new CEvent($this));
  7621. }
  7622. protected function afterFind()
  7623. {
  7624. if($this->hasEventHandler('onAfterFind'))
  7625. $this->onAfterFind(new CEvent($this));
  7626. }
  7627. public function beforeFindInternal()
  7628. {
  7629. $this->beforeFind();
  7630. }
  7631. public function afterFindInternal()
  7632. {
  7633. $this->afterFind();
  7634. }
  7635. public function insert($attributes=null)
  7636. {
  7637. if(!$this->getIsNewRecord())
  7638. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  7639. if($this->beforeSave())
  7640. {
  7641. $builder=$this->getCommandBuilder();
  7642. $table=$this->getMetaData()->tableSchema;
  7643. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  7644. if($command->execute())
  7645. {
  7646. $primaryKey=$table->primaryKey;
  7647. if($table->sequenceName!==null)
  7648. {
  7649. if(is_string($primaryKey) && $this->$primaryKey===null)
  7650. $this->$primaryKey=$builder->getLastInsertID($table);
  7651. elseif(is_array($primaryKey))
  7652. {
  7653. foreach($primaryKey as $pk)
  7654. {
  7655. if($this->$pk===null)
  7656. {
  7657. $this->$pk=$builder->getLastInsertID($table);
  7658. break;
  7659. }
  7660. }
  7661. }
  7662. }
  7663. $this->_pk=$this->getPrimaryKey();
  7664. $this->afterSave();
  7665. $this->setIsNewRecord(false);
  7666. $this->setScenario('update');
  7667. return true;
  7668. }
  7669. }
  7670. return false;
  7671. }
  7672. public function update($attributes=null)
  7673. {
  7674. if($this->getIsNewRecord())
  7675. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7676. if($this->beforeSave())
  7677. {
  7678. if($this->_pk===null)
  7679. $this->_pk=$this->getPrimaryKey();
  7680. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  7681. $this->_pk=$this->getPrimaryKey();
  7682. $this->afterSave();
  7683. return true;
  7684. }
  7685. else
  7686. return false;
  7687. }
  7688. public function saveAttributes($attributes)
  7689. {
  7690. if(!$this->getIsNewRecord())
  7691. {
  7692. $values=array();
  7693. foreach($attributes as $name=>$value)
  7694. {
  7695. if(is_integer($name))
  7696. $values[$value]=$this->$value;
  7697. else
  7698. $values[$name]=$this->$name=$value;
  7699. }
  7700. if($this->_pk===null)
  7701. $this->_pk=$this->getPrimaryKey();
  7702. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  7703. {
  7704. $this->_pk=$this->getPrimaryKey();
  7705. return true;
  7706. }
  7707. else
  7708. return false;
  7709. }
  7710. else
  7711. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7712. }
  7713. public function saveCounters($counters)
  7714. {
  7715. $builder=$this->getCommandBuilder();
  7716. $table=$this->getTableSchema();
  7717. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  7718. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7719. if($command->execute())
  7720. {
  7721. foreach($counters as $name=>$value)
  7722. $this->$name=$this->$name+$value;
  7723. return true;
  7724. }
  7725. else
  7726. return false;
  7727. }
  7728. public function delete()
  7729. {
  7730. if(!$this->getIsNewRecord())
  7731. {
  7732. if($this->beforeDelete())
  7733. {
  7734. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  7735. $this->afterDelete();
  7736. return $result;
  7737. }
  7738. else
  7739. return false;
  7740. }
  7741. else
  7742. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  7743. }
  7744. public function refresh()
  7745. {
  7746. if(($record=$this->findByPk($this->getPrimaryKey()))!==null)
  7747. {
  7748. $this->_attributes=array();
  7749. $this->_related=array();
  7750. foreach($this->getMetaData()->columns as $name=>$column)
  7751. {
  7752. if(property_exists($this,$name))
  7753. $this->$name=$record->$name;
  7754. else
  7755. $this->_attributes[$name]=$record->$name;
  7756. }
  7757. return true;
  7758. }
  7759. else
  7760. return false;
  7761. }
  7762. public function equals($record)
  7763. {
  7764. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  7765. }
  7766. public function getPrimaryKey()
  7767. {
  7768. $table=$this->getMetaData()->tableSchema;
  7769. if(is_string($table->primaryKey))
  7770. return $this->{$table->primaryKey};
  7771. elseif(is_array($table->primaryKey))
  7772. {
  7773. $values=array();
  7774. foreach($table->primaryKey as $name)
  7775. $values[$name]=$this->$name;
  7776. return $values;
  7777. }
  7778. else
  7779. return null;
  7780. }
  7781. public function setPrimaryKey($value)
  7782. {
  7783. $this->_pk=$this->getPrimaryKey();
  7784. $table=$this->getMetaData()->tableSchema;
  7785. if(is_string($table->primaryKey))
  7786. $this->{$table->primaryKey}=$value;
  7787. elseif(is_array($table->primaryKey))
  7788. {
  7789. foreach($table->primaryKey as $name)
  7790. $this->$name=$value[$name];
  7791. }
  7792. }
  7793. public function getOldPrimaryKey()
  7794. {
  7795. return $this->_pk;
  7796. }
  7797. public function setOldPrimaryKey($value)
  7798. {
  7799. $this->_pk=$value;
  7800. }
  7801. protected function query($criteria,$all=false)
  7802. {
  7803. $this->beforeFind();
  7804. $this->applyScopes($criteria);
  7805. if(empty($criteria->with))
  7806. {
  7807. if(!$all)
  7808. $criteria->limit=1;
  7809. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria,$this->getTableAlias());
  7810. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  7811. }
  7812. else
  7813. {
  7814. $finder=$this->getActiveFinder($criteria->with);
  7815. return $finder->query($criteria,$all);
  7816. }
  7817. }
  7818. public function applyScopes(&$criteria)
  7819. {
  7820. if(!empty($criteria->scopes))
  7821. {
  7822. $scs=$this->scopes();
  7823. $c=$this->getDbCriteria();
  7824. foreach((array)$criteria->scopes as $k=>$v)
  7825. {
  7826. if(is_integer($k))
  7827. {
  7828. if(is_string($v))
  7829. {
  7830. if(isset($scs[$v]))
  7831. {
  7832. $c->mergeWith($scs[$v],true);
  7833. continue;
  7834. }
  7835. $scope=$v;
  7836. $params=array();
  7837. }
  7838. elseif(is_array($v))
  7839. {
  7840. $scope=key($v);
  7841. $params=current($v);
  7842. }
  7843. }
  7844. elseif(is_string($k))
  7845. {
  7846. $scope=$k;
  7847. $params=$v;
  7848. }
  7849. call_user_func_array(array($this,$scope),(array)$params);
  7850. }
  7851. }
  7852. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  7853. {
  7854. $c->mergeWith($criteria);
  7855. $criteria=$c;
  7856. $this->resetScope(false);
  7857. }
  7858. }
  7859. public function getTableAlias($quote=false, $checkScopes=true)
  7860. {
  7861. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  7862. $alias=$criteria->alias;
  7863. else
  7864. $alias=$this->_alias;
  7865. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  7866. }
  7867. public function setTableAlias($alias)
  7868. {
  7869. $this->_alias=$alias;
  7870. }
  7871. public function find($condition='',$params=array())
  7872. {
  7873. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7874. return $this->query($criteria);
  7875. }
  7876. public function findAll($condition='',$params=array())
  7877. {
  7878. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7879. return $this->query($criteria,true);
  7880. }
  7881. public function findByPk($pk,$condition='',$params=array())
  7882. {
  7883. $prefix=$this->getTableAlias(true).'.';
  7884. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7885. return $this->query($criteria);
  7886. }
  7887. public function findAllByPk($pk,$condition='',$params=array())
  7888. {
  7889. $prefix=$this->getTableAlias(true).'.';
  7890. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7891. return $this->query($criteria,true);
  7892. }
  7893. public function findByAttributes($attributes,$condition='',$params=array())
  7894. {
  7895. $prefix=$this->getTableAlias(true).'.';
  7896. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7897. return $this->query($criteria);
  7898. }
  7899. public function findAllByAttributes($attributes,$condition='',$params=array())
  7900. {
  7901. $prefix=$this->getTableAlias(true).'.';
  7902. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7903. return $this->query($criteria,true);
  7904. }
  7905. public function findBySql($sql,$params=array())
  7906. {
  7907. $this->beforeFind();
  7908. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7909. {
  7910. $this->resetScope(false);
  7911. $finder=$this->getActiveFinder($criteria->with);
  7912. return $finder->findBySql($sql,$params);
  7913. }
  7914. else
  7915. {
  7916. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7917. return $this->populateRecord($command->queryRow());
  7918. }
  7919. }
  7920. public function findAllBySql($sql,$params=array())
  7921. {
  7922. $this->beforeFind();
  7923. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7924. {
  7925. $this->resetScope(false);
  7926. $finder=$this->getActiveFinder($criteria->with);
  7927. return $finder->findAllBySql($sql,$params);
  7928. }
  7929. else
  7930. {
  7931. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7932. return $this->populateRecords($command->queryAll());
  7933. }
  7934. }
  7935. public function count($condition='',$params=array())
  7936. {
  7937. $builder=$this->getCommandBuilder();
  7938. $this->beforeCount();
  7939. $criteria=$builder->createCriteria($condition,$params);
  7940. $this->applyScopes($criteria);
  7941. if(empty($criteria->with))
  7942. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7943. else
  7944. {
  7945. $finder=$this->getActiveFinder($criteria->with);
  7946. return $finder->count($criteria);
  7947. }
  7948. }
  7949. public function countByAttributes($attributes,$condition='',$params=array())
  7950. {
  7951. $prefix=$this->getTableAlias(true).'.';
  7952. $builder=$this->getCommandBuilder();
  7953. $this->beforeCount();
  7954. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7955. $this->applyScopes($criteria);
  7956. if(empty($criteria->with))
  7957. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7958. else
  7959. {
  7960. $finder=$this->getActiveFinder($criteria->with);
  7961. return $finder->count($criteria);
  7962. }
  7963. }
  7964. public function countBySql($sql,$params=array())
  7965. {
  7966. $this->beforeCount();
  7967. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  7968. }
  7969. public function exists($condition='',$params=array())
  7970. {
  7971. $builder=$this->getCommandBuilder();
  7972. $criteria=$builder->createCriteria($condition,$params);
  7973. $table=$this->getTableSchema();
  7974. $criteria->select='1';
  7975. $criteria->limit=1;
  7976. $this->applyScopes($criteria);
  7977. if(empty($criteria->with))
  7978. return $builder->createFindCommand($table,$criteria,$this->getTableAlias(false, false))->queryRow()!==false;
  7979. else
  7980. {
  7981. $criteria->select='*';
  7982. $finder=$this->getActiveFinder($criteria->with);
  7983. return $finder->count($criteria)>0;
  7984. }
  7985. }
  7986. public function with()
  7987. {
  7988. if(func_num_args()>0)
  7989. {
  7990. $with=func_get_args();
  7991. if(is_array($with[0])) // the parameter is given as an array
  7992. $with=$with[0];
  7993. if(!empty($with))
  7994. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  7995. }
  7996. return $this;
  7997. }
  7998. public function together()
  7999. {
  8000. $this->getDbCriteria()->together=true;
  8001. return $this;
  8002. }
  8003. public function updateByPk($pk,$attributes,$condition='',$params=array())
  8004. {
  8005. $builder=$this->getCommandBuilder();
  8006. $table=$this->getTableSchema();
  8007. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  8008. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  8009. return $command->execute();
  8010. }
  8011. public function updateAll($attributes,$condition='',$params=array())
  8012. {
  8013. $builder=$this->getCommandBuilder();
  8014. $criteria=$builder->createCriteria($condition,$params);
  8015. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  8016. return $command->execute();
  8017. }
  8018. public function updateCounters($counters,$condition='',$params=array())
  8019. {
  8020. $builder=$this->getCommandBuilder();
  8021. $criteria=$builder->createCriteria($condition,$params);
  8022. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  8023. return $command->execute();
  8024. }
  8025. public function deleteByPk($pk,$condition='',$params=array())
  8026. {
  8027. $builder=$this->getCommandBuilder();
  8028. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  8029. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  8030. return $command->execute();
  8031. }
  8032. public function deleteAll($condition='',$params=array())
  8033. {
  8034. $builder=$this->getCommandBuilder();
  8035. $criteria=$builder->createCriteria($condition,$params);
  8036. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  8037. return $command->execute();
  8038. }
  8039. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  8040. {
  8041. $builder=$this->getCommandBuilder();
  8042. $table=$this->getTableSchema();
  8043. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  8044. $command=$builder->createDeleteCommand($table,$criteria);
  8045. return $command->execute();
  8046. }
  8047. public function populateRecord($attributes,$callAfterFind=true)
  8048. {
  8049. if($attributes!==false)
  8050. {
  8051. $record=$this->instantiate($attributes);
  8052. $record->setScenario('update');
  8053. $record->init();
  8054. $md=$record->getMetaData();
  8055. foreach($attributes as $name=>$value)
  8056. {
  8057. if(property_exists($record,$name))
  8058. $record->$name=$value;
  8059. elseif(isset($md->columns[$name]))
  8060. $record->_attributes[$name]=$value;
  8061. }
  8062. $record->_pk=$record->getPrimaryKey();
  8063. $record->attachBehaviors($record->behaviors());
  8064. if($callAfterFind)
  8065. $record->afterFind();
  8066. return $record;
  8067. }
  8068. else
  8069. return null;
  8070. }
  8071. public function populateRecords($data,$callAfterFind=true,$index=null)
  8072. {
  8073. $records=array();
  8074. foreach($data as $attributes)
  8075. {
  8076. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  8077. {
  8078. if($index===null)
  8079. $records[]=$record;
  8080. else
  8081. $records[$record->$index]=$record;
  8082. }
  8083. }
  8084. return $records;
  8085. }
  8086. protected function instantiate($attributes)
  8087. {
  8088. $class=get_class($this);
  8089. $model=new $class(null);
  8090. return $model;
  8091. }
  8092. public function offsetExists($offset)
  8093. {
  8094. return $this->__isset($offset);
  8095. }
  8096. }
  8097. class CBaseActiveRelation extends CComponent
  8098. {
  8099. public $name;
  8100. public $className;
  8101. public $foreignKey;
  8102. public $select='*';
  8103. public $condition='';
  8104. public $params=array();
  8105. public $group='';
  8106. public $join='';
  8107. public $having='';
  8108. public $order='';
  8109. public function __construct($name,$className,$foreignKey,$options=array())
  8110. {
  8111. $this->name=$name;
  8112. $this->className=$className;
  8113. $this->foreignKey=$foreignKey;
  8114. foreach($options as $name=>$value)
  8115. $this->$name=$value;
  8116. }
  8117. public function mergeWith($criteria,$fromScope=false)
  8118. {
  8119. if($criteria instanceof CDbCriteria)
  8120. $criteria=$criteria->toArray();
  8121. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  8122. {
  8123. if($this->select==='*')
  8124. $this->select=$criteria['select'];
  8125. elseif($criteria['select']!=='*')
  8126. {
  8127. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  8128. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  8129. $this->select=array_merge($select1,array_diff($select2,$select1));
  8130. }
  8131. }
  8132. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  8133. {
  8134. if($this->condition==='')
  8135. $this->condition=$criteria['condition'];
  8136. elseif($criteria['condition']!=='')
  8137. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  8138. }
  8139. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  8140. $this->params=array_merge($this->params,$criteria['params']);
  8141. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  8142. {
  8143. if($this->order==='')
  8144. $this->order=$criteria['order'];
  8145. elseif($criteria['order']!=='')
  8146. $this->order=$criteria['order'].', '.$this->order;
  8147. }
  8148. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  8149. {
  8150. if($this->group==='')
  8151. $this->group=$criteria['group'];
  8152. elseif($criteria['group']!=='')
  8153. $this->group.=', '.$criteria['group'];
  8154. }
  8155. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  8156. {
  8157. if($this->join==='')
  8158. $this->join=$criteria['join'];
  8159. elseif($criteria['join']!=='')
  8160. $this->join.=' '.$criteria['join'];
  8161. }
  8162. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  8163. {
  8164. if($this->having==='')
  8165. $this->having=$criteria['having'];
  8166. elseif($criteria['having']!=='')
  8167. $this->having="({$this->having}) AND ({$criteria['having']})";
  8168. }
  8169. }
  8170. }
  8171. class CStatRelation extends CBaseActiveRelation
  8172. {
  8173. public $select='COUNT(*)';
  8174. public $defaultValue=0;
  8175. public function mergeWith($criteria,$fromScope=false)
  8176. {
  8177. if($criteria instanceof CDbCriteria)
  8178. $criteria=$criteria->toArray();
  8179. parent::mergeWith($criteria,$fromScope);
  8180. if(isset($criteria['defaultValue']))
  8181. $this->defaultValue=$criteria['defaultValue'];
  8182. }
  8183. }
  8184. class CActiveRelation extends CBaseActiveRelation
  8185. {
  8186. public $joinType='LEFT OUTER JOIN';
  8187. public $on='';
  8188. public $alias;
  8189. public $with=array();
  8190. public $together;
  8191. public $scopes;
  8192. public $through;
  8193. public function mergeWith($criteria,$fromScope=false)
  8194. {
  8195. if($criteria instanceof CDbCriteria)
  8196. $criteria=$criteria->toArray();
  8197. if($fromScope)
  8198. {
  8199. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  8200. {
  8201. if($this->on==='')
  8202. $this->on=$criteria['condition'];
  8203. elseif($criteria['condition']!=='')
  8204. $this->on="({$this->on}) AND ({$criteria['condition']})";
  8205. }
  8206. unset($criteria['condition']);
  8207. }
  8208. parent::mergeWith($criteria);
  8209. if(isset($criteria['joinType']))
  8210. $this->joinType=$criteria['joinType'];
  8211. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  8212. {
  8213. if($this->on==='')
  8214. $this->on=$criteria['on'];
  8215. elseif($criteria['on']!=='')
  8216. $this->on="({$this->on}) AND ({$criteria['on']})";
  8217. }
  8218. if(isset($criteria['with']))
  8219. $this->with=$criteria['with'];
  8220. if(isset($criteria['alias']))
  8221. $this->alias=$criteria['alias'];
  8222. if(isset($criteria['together']))
  8223. $this->together=$criteria['together'];
  8224. }
  8225. }
  8226. class CBelongsToRelation extends CActiveRelation
  8227. {
  8228. }
  8229. class CHasOneRelation extends CActiveRelation
  8230. {
  8231. }
  8232. class CHasManyRelation extends CActiveRelation
  8233. {
  8234. public $limit=-1;
  8235. public $offset=-1;
  8236. public $index;
  8237. public function mergeWith($criteria,$fromScope=false)
  8238. {
  8239. if($criteria instanceof CDbCriteria)
  8240. $criteria=$criteria->toArray();
  8241. parent::mergeWith($criteria,$fromScope);
  8242. if(isset($criteria['limit']) && $criteria['limit']>0)
  8243. $this->limit=$criteria['limit'];
  8244. if(isset($criteria['offset']) && $criteria['offset']>=0)
  8245. $this->offset=$criteria['offset'];
  8246. if(isset($criteria['index']))
  8247. $this->index=$criteria['index'];
  8248. }
  8249. }
  8250. class CManyManyRelation extends CHasManyRelation
  8251. {
  8252. private $_junctionTableName=null;
  8253. private $_junctionForeignKeys=null;
  8254. public function getJunctionTableName()
  8255. {
  8256. if ($this->_junctionTableName===null)
  8257. $this->initJunctionData();
  8258. return $this->_junctionTableName;
  8259. }
  8260. public function getJunctionForeignKeys()
  8261. {
  8262. if ($this->_junctionForeignKeys===null)
  8263. $this->initJunctionData();
  8264. return $this->_junctionForeignKeys;
  8265. }
  8266. private function initJunctionData()
  8267. {
  8268. if(!preg_match('/^\s*(.*?)\((.*)\)\s*$/',$this->foreignKey,$matches))
  8269. 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,...)".',
  8270. array('{class}'=>$this->className,'{relation}'=>$this->name)));
  8271. $this->_junctionTableName=$matches[1];
  8272. $this->_junctionForeignKeys=preg_split('/\s*,\s*/',$matches[2],-1,PREG_SPLIT_NO_EMPTY);
  8273. }
  8274. }
  8275. class CActiveRecordMetaData
  8276. {
  8277. public $tableSchema;
  8278. public $columns;
  8279. public $relations=array();
  8280. public $attributeDefaults=array();
  8281. private $_modelClassName;
  8282. public function __construct($model)
  8283. {
  8284. $this->_modelClassName=get_class($model);
  8285. $tableName=$model->tableName();
  8286. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  8287. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  8288. array('{class}'=>$this->_modelClassName,'{table}'=>$tableName)));
  8289. if($table->primaryKey===null)
  8290. {
  8291. $table->primaryKey=$model->primaryKey();
  8292. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  8293. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  8294. elseif(is_array($table->primaryKey))
  8295. {
  8296. foreach($table->primaryKey as $name)
  8297. {
  8298. if(isset($table->columns[$name]))
  8299. $table->columns[$name]->isPrimaryKey=true;
  8300. }
  8301. }
  8302. }
  8303. $this->tableSchema=$table;
  8304. $this->columns=$table->columns;
  8305. foreach($table->columns as $name=>$column)
  8306. {
  8307. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  8308. $this->attributeDefaults[$name]=$column->defaultValue;
  8309. }
  8310. foreach($model->relations() as $name=>$config)
  8311. {
  8312. $this->addRelation($name,$config);
  8313. }
  8314. }
  8315. public function addRelation($name,$config)
  8316. {
  8317. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  8318. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  8319. else
  8320. 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)));
  8321. }
  8322. public function hasRelation($name)
  8323. {
  8324. return isset($this->relations[$name]);
  8325. }
  8326. public function removeRelation($name)
  8327. {
  8328. unset($this->relations[$name]);
  8329. }
  8330. }
  8331. class CDbConnection extends CApplicationComponent
  8332. {
  8333. public $connectionString;
  8334. public $username='';
  8335. public $password='';
  8336. public $schemaCachingDuration=0;
  8337. public $schemaCachingExclude=array();
  8338. public $schemaCacheID='cache';
  8339. public $queryCachingDuration=0;
  8340. public $queryCachingDependency;
  8341. public $queryCachingCount=0;
  8342. public $queryCacheID='cache';
  8343. public $autoConnect=true;
  8344. public $charset;
  8345. public $emulatePrepare;
  8346. public $enableParamLogging=false;
  8347. public $enableProfiling=false;
  8348. public $tablePrefix;
  8349. public $initSQLs;
  8350. public $driverMap=array(
  8351. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  8352. 'mysqli'=>'CMysqlSchema', // MySQL
  8353. 'mysql'=>'CMysqlSchema', // MySQL
  8354. 'sqlite'=>'CSqliteSchema', // sqlite 3
  8355. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  8356. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  8357. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  8358. 'sqlsrv'=>'CMssqlSchema', // Mssql
  8359. 'oci'=>'COciSchema', // Oracle driver
  8360. );
  8361. public $pdoClass = 'PDO';
  8362. private $_attributes=array();
  8363. private $_active=false;
  8364. private $_pdo;
  8365. private $_transaction;
  8366. private $_schema;
  8367. public function __construct($dsn='',$username='',$password='')
  8368. {
  8369. $this->connectionString=$dsn;
  8370. $this->username=$username;
  8371. $this->password=$password;
  8372. }
  8373. public function __sleep()
  8374. {
  8375. $this->close();
  8376. return array_keys(get_object_vars($this));
  8377. }
  8378. public static function getAvailableDrivers()
  8379. {
  8380. return PDO::getAvailableDrivers();
  8381. }
  8382. public function init()
  8383. {
  8384. parent::init();
  8385. if($this->autoConnect)
  8386. $this->setActive(true);
  8387. }
  8388. public function getActive()
  8389. {
  8390. return $this->_active;
  8391. }
  8392. public function setActive($value)
  8393. {
  8394. if($value!=$this->_active)
  8395. {
  8396. if($value)
  8397. $this->open();
  8398. else
  8399. $this->close();
  8400. }
  8401. }
  8402. public function cache($duration, $dependency=null, $queryCount=1)
  8403. {
  8404. $this->queryCachingDuration=$duration;
  8405. $this->queryCachingDependency=$dependency;
  8406. $this->queryCachingCount=$queryCount;
  8407. return $this;
  8408. }
  8409. protected function open()
  8410. {
  8411. if($this->_pdo===null)
  8412. {
  8413. if(empty($this->connectionString))
  8414. throw new CDbException('CDbConnection.connectionString cannot be empty.');
  8415. try
  8416. {
  8417. $this->_pdo=$this->createPdoInstance();
  8418. $this->initConnection($this->_pdo);
  8419. $this->_active=true;
  8420. }
  8421. catch(PDOException $e)
  8422. {
  8423. if(YII_DEBUG)
  8424. {
  8425. throw new CDbException('CDbConnection failed to open the DB connection: '.
  8426. $e->getMessage(),(int)$e->getCode(),$e->errorInfo);
  8427. }
  8428. else
  8429. {
  8430. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  8431. throw new CDbException('CDbConnection failed to open the DB connection.',(int)$e->getCode(),$e->errorInfo);
  8432. }
  8433. }
  8434. }
  8435. }
  8436. protected function close()
  8437. {
  8438. $this->_pdo=null;
  8439. $this->_active=false;
  8440. $this->_schema=null;
  8441. }
  8442. protected function createPdoInstance()
  8443. {
  8444. $pdoClass=$this->pdoClass;
  8445. if(($pos=strpos($this->connectionString,':'))!==false)
  8446. {
  8447. $driver=strtolower(substr($this->connectionString,0,$pos));
  8448. if($driver==='mssql' || $driver==='dblib')
  8449. $pdoClass='CMssqlPdoAdapter';
  8450. elseif($driver==='sqlsrv')
  8451. $pdoClass='CMssqlSqlsrvPdoAdapter';
  8452. }
  8453. if(!class_exists($pdoClass))
  8454. throw new CDbException(Yii::t('yii','CDbConnection is unable to find PDO class "{className}". Make sure PDO is installed correctly.',
  8455. array('{className}'=>$pdoClass)));
  8456. @$instance=new $pdoClass($this->connectionString,$this->username,$this->password,$this->_attributes);
  8457. if(!$instance)
  8458. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'));
  8459. return $instance;
  8460. }
  8461. protected function initConnection($pdo)
  8462. {
  8463. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  8464. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  8465. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  8466. if($this->charset!==null)
  8467. {
  8468. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  8469. if(in_array($driver,array('pgsql','mysql','mysqli')))
  8470. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  8471. }
  8472. if($this->initSQLs!==null)
  8473. {
  8474. foreach($this->initSQLs as $sql)
  8475. $pdo->exec($sql);
  8476. }
  8477. }
  8478. public function getPdoInstance()
  8479. {
  8480. return $this->_pdo;
  8481. }
  8482. public function createCommand($query=null)
  8483. {
  8484. $this->setActive(true);
  8485. return new CDbCommand($this,$query);
  8486. }
  8487. public function getCurrentTransaction()
  8488. {
  8489. if($this->_transaction!==null)
  8490. {
  8491. if($this->_transaction->getActive())
  8492. return $this->_transaction;
  8493. }
  8494. return null;
  8495. }
  8496. public function beginTransaction()
  8497. {
  8498. $this->setActive(true);
  8499. $this->_pdo->beginTransaction();
  8500. return $this->_transaction=new CDbTransaction($this);
  8501. }
  8502. public function getSchema()
  8503. {
  8504. if($this->_schema!==null)
  8505. return $this->_schema;
  8506. else
  8507. {
  8508. $driver=$this->getDriverName();
  8509. if(isset($this->driverMap[$driver]))
  8510. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  8511. else
  8512. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  8513. array('{driver}'=>$driver)));
  8514. }
  8515. }
  8516. public function getCommandBuilder()
  8517. {
  8518. return $this->getSchema()->getCommandBuilder();
  8519. }
  8520. public function getLastInsertID($sequenceName='')
  8521. {
  8522. $this->setActive(true);
  8523. return $this->_pdo->lastInsertId($sequenceName);
  8524. }
  8525. public function quoteValue($str)
  8526. {
  8527. if(is_int($str) || is_float($str))
  8528. return $str;
  8529. $this->setActive(true);
  8530. if(($value=$this->_pdo->quote($str))!==false)
  8531. return $value;
  8532. else // the driver doesn't support quote (e.g. oci)
  8533. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  8534. }
  8535. public function quoteTableName($name)
  8536. {
  8537. return $this->getSchema()->quoteTableName($name);
  8538. }
  8539. public function quoteColumnName($name)
  8540. {
  8541. return $this->getSchema()->quoteColumnName($name);
  8542. }
  8543. public function getPdoType($type)
  8544. {
  8545. static $map=array
  8546. (
  8547. 'boolean'=>PDO::PARAM_BOOL,
  8548. 'integer'=>PDO::PARAM_INT,
  8549. 'string'=>PDO::PARAM_STR,
  8550. 'resource'=>PDO::PARAM_LOB,
  8551. 'NULL'=>PDO::PARAM_NULL,
  8552. );
  8553. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  8554. }
  8555. public function getColumnCase()
  8556. {
  8557. return $this->getAttribute(PDO::ATTR_CASE);
  8558. }
  8559. public function setColumnCase($value)
  8560. {
  8561. $this->setAttribute(PDO::ATTR_CASE,$value);
  8562. }
  8563. public function getNullConversion()
  8564. {
  8565. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  8566. }
  8567. public function setNullConversion($value)
  8568. {
  8569. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  8570. }
  8571. public function getAutoCommit()
  8572. {
  8573. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  8574. }
  8575. public function setAutoCommit($value)
  8576. {
  8577. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  8578. }
  8579. public function getPersistent()
  8580. {
  8581. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  8582. }
  8583. public function setPersistent($value)
  8584. {
  8585. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  8586. }
  8587. public function getDriverName()
  8588. {
  8589. if(($pos=strpos($this->connectionString, ':'))!==false)
  8590. return strtolower(substr($this->connectionString, 0, $pos));
  8591. // return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  8592. }
  8593. public function getClientVersion()
  8594. {
  8595. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  8596. }
  8597. public function getConnectionStatus()
  8598. {
  8599. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  8600. }
  8601. public function getPrefetch()
  8602. {
  8603. return $this->getAttribute(PDO::ATTR_PREFETCH);
  8604. }
  8605. public function getServerInfo()
  8606. {
  8607. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  8608. }
  8609. public function getServerVersion()
  8610. {
  8611. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  8612. }
  8613. public function getTimeout()
  8614. {
  8615. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  8616. }
  8617. public function getAttribute($name)
  8618. {
  8619. $this->setActive(true);
  8620. return $this->_pdo->getAttribute($name);
  8621. }
  8622. public function setAttribute($name,$value)
  8623. {
  8624. if($this->_pdo instanceof PDO)
  8625. $this->_pdo->setAttribute($name,$value);
  8626. else
  8627. $this->_attributes[$name]=$value;
  8628. }
  8629. public function getAttributes()
  8630. {
  8631. return $this->_attributes;
  8632. }
  8633. public function setAttributes($values)
  8634. {
  8635. foreach($values as $name=>$value)
  8636. $this->_attributes[$name]=$value;
  8637. }
  8638. public function getStats()
  8639. {
  8640. $logger=Yii::getLogger();
  8641. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  8642. $count=count($timings);
  8643. $time=array_sum($timings);
  8644. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  8645. $count+=count($timings);
  8646. $time+=array_sum($timings);
  8647. return array($count,$time);
  8648. }
  8649. }
  8650. abstract class CDbSchema extends CComponent
  8651. {
  8652. public $columnTypes=array();
  8653. private $_tableNames=array();
  8654. private $_tables=array();
  8655. private $_connection;
  8656. private $_builder;
  8657. private $_cacheExclude=array();
  8658. abstract protected function loadTable($name);
  8659. public function __construct($conn)
  8660. {
  8661. $this->_connection=$conn;
  8662. foreach($conn->schemaCachingExclude as $name)
  8663. $this->_cacheExclude[$name]=true;
  8664. }
  8665. public function getDbConnection()
  8666. {
  8667. return $this->_connection;
  8668. }
  8669. public function getTable($name,$refresh=false)
  8670. {
  8671. if($refresh===false && isset($this->_tables[$name]))
  8672. return $this->_tables[$name];
  8673. else
  8674. {
  8675. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  8676. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  8677. else
  8678. $realName=$name;
  8679. // temporarily disable query caching
  8680. if($this->_connection->queryCachingDuration>0)
  8681. {
  8682. $qcDuration=$this->_connection->queryCachingDuration;
  8683. $this->_connection->queryCachingDuration=0;
  8684. }
  8685. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8686. {
  8687. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8688. $table=$cache->get($key);
  8689. if($refresh===true || $table===false)
  8690. {
  8691. $table=$this->loadTable($realName);
  8692. if($table!==null)
  8693. $cache->set($key,$table,$duration);
  8694. }
  8695. $this->_tables[$name]=$table;
  8696. }
  8697. else
  8698. $this->_tables[$name]=$table=$this->loadTable($realName);
  8699. if(isset($qcDuration)) // re-enable query caching
  8700. $this->_connection->queryCachingDuration=$qcDuration;
  8701. return $table;
  8702. }
  8703. }
  8704. public function getTables($schema='')
  8705. {
  8706. $tables=array();
  8707. foreach($this->getTableNames($schema) as $name)
  8708. {
  8709. if(($table=$this->getTable($name))!==null)
  8710. $tables[$name]=$table;
  8711. }
  8712. return $tables;
  8713. }
  8714. public function getTableNames($schema='')
  8715. {
  8716. if(!isset($this->_tableNames[$schema]))
  8717. $this->_tableNames[$schema]=$this->findTableNames($schema);
  8718. return $this->_tableNames[$schema];
  8719. }
  8720. public function getCommandBuilder()
  8721. {
  8722. if($this->_builder!==null)
  8723. return $this->_builder;
  8724. else
  8725. return $this->_builder=$this->createCommandBuilder();
  8726. }
  8727. public function refresh()
  8728. {
  8729. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8730. {
  8731. foreach(array_keys($this->_tables) as $name)
  8732. {
  8733. if(!isset($this->_cacheExclude[$name]))
  8734. {
  8735. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8736. $cache->delete($key);
  8737. }
  8738. }
  8739. }
  8740. $this->_tables=array();
  8741. $this->_tableNames=array();
  8742. $this->_builder=null;
  8743. }
  8744. public function quoteTableName($name)
  8745. {
  8746. if(strpos($name,'.')===false)
  8747. return $this->quoteSimpleTableName($name);
  8748. $parts=explode('.',$name);
  8749. foreach($parts as $i=>$part)
  8750. $parts[$i]=$this->quoteSimpleTableName($part);
  8751. return implode('.',$parts);
  8752. }
  8753. public function quoteSimpleTableName($name)
  8754. {
  8755. return "'".$name."'";
  8756. }
  8757. public function quoteColumnName($name)
  8758. {
  8759. if(($pos=strrpos($name,'.'))!==false)
  8760. {
  8761. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  8762. $name=substr($name,$pos+1);
  8763. }
  8764. else
  8765. $prefix='';
  8766. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  8767. }
  8768. public function quoteSimpleColumnName($name)
  8769. {
  8770. return '"'.$name.'"';
  8771. }
  8772. public function compareTableNames($name1,$name2)
  8773. {
  8774. $name1=str_replace(array('"','`',"'"),'',$name1);
  8775. $name2=str_replace(array('"','`',"'"),'',$name2);
  8776. if(($pos=strrpos($name1,'.'))!==false)
  8777. $name1=substr($name1,$pos+1);
  8778. if(($pos=strrpos($name2,'.'))!==false)
  8779. $name2=substr($name2,$pos+1);
  8780. if($this->_connection->tablePrefix!==null)
  8781. {
  8782. if(strpos($name1,'{')!==false)
  8783. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  8784. if(strpos($name2,'{')!==false)
  8785. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  8786. }
  8787. return $name1===$name2;
  8788. }
  8789. public function resetSequence($table,$value=null)
  8790. {
  8791. }
  8792. public function checkIntegrity($check=true,$schema='')
  8793. {
  8794. }
  8795. protected function createCommandBuilder()
  8796. {
  8797. return new CDbCommandBuilder($this);
  8798. }
  8799. protected function findTableNames($schema='')
  8800. {
  8801. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  8802. array('{class}'=>get_class($this))));
  8803. }
  8804. public function getColumnType($type)
  8805. {
  8806. if(isset($this->columnTypes[$type]))
  8807. return $this->columnTypes[$type];
  8808. elseif(($pos=strpos($type,' '))!==false)
  8809. {
  8810. $t=substr($type,0,$pos);
  8811. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  8812. }
  8813. else
  8814. return $type;
  8815. }
  8816. public function createTable($table, $columns, $options=null)
  8817. {
  8818. $cols=array();
  8819. foreach($columns as $name=>$type)
  8820. {
  8821. if(is_string($name))
  8822. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  8823. else
  8824. $cols[]="\t".$type;
  8825. }
  8826. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  8827. return $options===null ? $sql : $sql.' '.$options;
  8828. }
  8829. public function renameTable($table, $newName)
  8830. {
  8831. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  8832. }
  8833. public function dropTable($table)
  8834. {
  8835. return "DROP TABLE ".$this->quoteTableName($table);
  8836. }
  8837. public function truncateTable($table)
  8838. {
  8839. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  8840. }
  8841. public function addColumn($table, $column, $type)
  8842. {
  8843. return 'ALTER TABLE ' . $this->quoteTableName($table)
  8844. . ' ADD ' . $this->quoteColumnName($column) . ' '
  8845. . $this->getColumnType($type);
  8846. }
  8847. public function dropColumn($table, $column)
  8848. {
  8849. return "ALTER TABLE ".$this->quoteTableName($table)
  8850. ." DROP COLUMN ".$this->quoteColumnName($column);
  8851. }
  8852. public function renameColumn($table, $name, $newName)
  8853. {
  8854. return "ALTER TABLE ".$this->quoteTableName($table)
  8855. . " RENAME COLUMN ".$this->quoteColumnName($name)
  8856. . " TO ".$this->quoteColumnName($newName);
  8857. }
  8858. public function alterColumn($table, $column, $type)
  8859. {
  8860. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  8861. . $this->quoteColumnName($column) . ' '
  8862. . $this->quoteColumnName($column) . ' '
  8863. . $this->getColumnType($type);
  8864. }
  8865. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8866. {
  8867. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  8868. foreach($columns as $i=>$col)
  8869. $columns[$i]=$this->quoteColumnName($col);
  8870. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  8871. foreach($refColumns as $i=>$col)
  8872. $refColumns[$i]=$this->quoteColumnName($col);
  8873. $sql='ALTER TABLE '.$this->quoteTableName($table)
  8874. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  8875. .' FOREIGN KEY ('.implode(', ', $columns).')'
  8876. .' REFERENCES '.$this->quoteTableName($refTable)
  8877. .' ('.implode(', ', $refColumns).')';
  8878. if($delete!==null)
  8879. $sql.=' ON DELETE '.$delete;
  8880. if($update!==null)
  8881. $sql.=' ON UPDATE '.$update;
  8882. return $sql;
  8883. }
  8884. public function dropForeignKey($name, $table)
  8885. {
  8886. return 'ALTER TABLE '.$this->quoteTableName($table)
  8887. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  8888. }
  8889. public function createIndex($name, $table, $column, $unique=false)
  8890. {
  8891. $cols=array();
  8892. $columns=preg_split('/\s*,\s*/',$column,-1,PREG_SPLIT_NO_EMPTY);
  8893. foreach($columns as $col)
  8894. {
  8895. if(strpos($col,'(')!==false)
  8896. $cols[]=$col;
  8897. else
  8898. $cols[]=$this->quoteColumnName($col);
  8899. }
  8900. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  8901. . $this->quoteTableName($name).' ON '
  8902. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  8903. }
  8904. public function dropIndex($name, $table)
  8905. {
  8906. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  8907. }
  8908. public function addPrimaryKey($name,$table,$columns)
  8909. {
  8910. if(is_string($columns))
  8911. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  8912. foreach($columns as $i=>$col)
  8913. $columns[$i]=$this->quoteColumnName($col);
  8914. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' ADD CONSTRAINT '
  8915. . $this->quoteColumnName($name) . ' PRIMARY KEY ('
  8916. . implode(', ', $columns). ' )';
  8917. }
  8918. public function dropPrimaryKey($name,$table)
  8919. {
  8920. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' DROP CONSTRAINT '
  8921. . $this->quoteColumnName($name);
  8922. }
  8923. }
  8924. class CSqliteSchema extends CDbSchema
  8925. {
  8926. public $columnTypes=array(
  8927. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  8928. 'string' => 'varchar(255)',
  8929. 'text' => 'text',
  8930. 'integer' => 'integer',
  8931. 'float' => 'float',
  8932. 'decimal' => 'decimal',
  8933. 'datetime' => 'datetime',
  8934. 'timestamp' => 'timestamp',
  8935. 'time' => 'time',
  8936. 'date' => 'date',
  8937. 'binary' => 'blob',
  8938. 'boolean' => 'tinyint(1)',
  8939. 'money' => 'decimal(19,4)',
  8940. );
  8941. public function resetSequence($table,$value=null)
  8942. {
  8943. if($table->sequenceName===null)
  8944. return;
  8945. if($value!==null)
  8946. $value=(int)($value)-1;
  8947. else
  8948. $value=(int)$this->getDbConnection()
  8949. ->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")
  8950. ->queryScalar();
  8951. try
  8952. {
  8953. // it's possible that 'sqlite_sequence' does not exist
  8954. $this->getDbConnection()
  8955. ->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")
  8956. ->execute();
  8957. }
  8958. catch(Exception $e)
  8959. {
  8960. }
  8961. }
  8962. public function checkIntegrity($check=true,$schema='')
  8963. {
  8964. $this->getDbConnection()->createCommand('PRAGMA foreign_keys='.(int)$check)->execute();
  8965. }
  8966. protected function findTableNames($schema='')
  8967. {
  8968. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  8969. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  8970. }
  8971. protected function createCommandBuilder()
  8972. {
  8973. return new CSqliteCommandBuilder($this);
  8974. }
  8975. protected function loadTable($name)
  8976. {
  8977. $table=new CDbTableSchema;
  8978. $table->name=$name;
  8979. $table->rawName=$this->quoteTableName($name);
  8980. if($this->findColumns($table))
  8981. {
  8982. $this->findConstraints($table);
  8983. return $table;
  8984. }
  8985. else
  8986. return null;
  8987. }
  8988. protected function findColumns($table)
  8989. {
  8990. $sql="PRAGMA table_info({$table->rawName})";
  8991. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  8992. if(empty($columns))
  8993. return false;
  8994. foreach($columns as $column)
  8995. {
  8996. $c=$this->createColumn($column);
  8997. $table->columns[$c->name]=$c;
  8998. if($c->isPrimaryKey)
  8999. {
  9000. if($table->primaryKey===null)
  9001. $table->primaryKey=$c->name;
  9002. elseif(is_string($table->primaryKey))
  9003. $table->primaryKey=array($table->primaryKey,$c->name);
  9004. else
  9005. $table->primaryKey[]=$c->name;
  9006. }
  9007. }
  9008. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  9009. {
  9010. $table->sequenceName='';
  9011. $table->columns[$table->primaryKey]->autoIncrement=true;
  9012. }
  9013. return true;
  9014. }
  9015. protected function findConstraints($table)
  9016. {
  9017. $foreignKeys=array();
  9018. $sql="PRAGMA foreign_key_list({$table->rawName})";
  9019. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  9020. foreach($keys as $key)
  9021. {
  9022. $column=$table->columns[$key['from']];
  9023. $column->isForeignKey=true;
  9024. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  9025. }
  9026. $table->foreignKeys=$foreignKeys;
  9027. }
  9028. protected function createColumn($column)
  9029. {
  9030. $c=new CSqliteColumnSchema;
  9031. $c->name=$column['name'];
  9032. $c->rawName=$this->quoteColumnName($c->name);
  9033. $c->allowNull=!$column['notnull'];
  9034. $c->isPrimaryKey=$column['pk']!=0;
  9035. $c->isForeignKey=false;
  9036. $c->comment=null; // SQLite does not support column comments at all
  9037. $c->init(strtolower($column['type']),$column['dflt_value']);
  9038. return $c;
  9039. }
  9040. public function renameTable($table, $newName)
  9041. {
  9042. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' RENAME TO ' . $this->quoteTableName($newName);
  9043. }
  9044. public function truncateTable($table)
  9045. {
  9046. return "DELETE FROM ".$this->quoteTableName($table);
  9047. }
  9048. public function dropColumn($table, $column)
  9049. {
  9050. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  9051. }
  9052. public function renameColumn($table, $name, $newName)
  9053. {
  9054. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  9055. }
  9056. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9057. {
  9058. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  9059. }
  9060. public function dropForeignKey($name, $table)
  9061. {
  9062. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  9063. }
  9064. public function alterColumn($table, $column, $type)
  9065. {
  9066. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  9067. }
  9068. public function dropIndex($name, $table)
  9069. {
  9070. return 'DROP INDEX '.$this->quoteTableName($name);
  9071. }
  9072. public function addPrimaryKey($name,$table,$columns)
  9073. {
  9074. throw new CDbException(Yii::t('yii', 'Adding a primary key after table has been created is not supported by SQLite.'));
  9075. }
  9076. public function dropPrimaryKey($name,$table)
  9077. {
  9078. throw new CDbException(Yii::t('yii', 'Removing a primary key after table has been created is not supported by SQLite.'));
  9079. }
  9080. }
  9081. class CDbTableSchema extends CComponent
  9082. {
  9083. public $name;
  9084. public $rawName;
  9085. public $primaryKey;
  9086. public $sequenceName;
  9087. public $foreignKeys=array();
  9088. public $columns=array();
  9089. public function getColumn($name)
  9090. {
  9091. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  9092. }
  9093. public function getColumnNames()
  9094. {
  9095. return array_keys($this->columns);
  9096. }
  9097. }
  9098. class CDbCommand extends CComponent
  9099. {
  9100. public $params=array();
  9101. private $_connection;
  9102. private $_text;
  9103. private $_statement;
  9104. private $_paramLog=array();
  9105. private $_query;
  9106. private $_fetchMode = array(PDO::FETCH_ASSOC);
  9107. public function __construct(CDbConnection $connection,$query=null)
  9108. {
  9109. $this->_connection=$connection;
  9110. if(is_array($query))
  9111. {
  9112. foreach($query as $name=>$value)
  9113. $this->$name=$value;
  9114. }
  9115. else
  9116. $this->setText($query);
  9117. }
  9118. public function __sleep()
  9119. {
  9120. $this->_statement=null;
  9121. return array_keys(get_object_vars($this));
  9122. }
  9123. public function setFetchMode($mode)
  9124. {
  9125. $params=func_get_args();
  9126. $this->_fetchMode = $params;
  9127. return $this;
  9128. }
  9129. public function reset()
  9130. {
  9131. $this->_text=null;
  9132. $this->_query=null;
  9133. $this->_statement=null;
  9134. $this->_paramLog=array();
  9135. $this->params=array();
  9136. return $this;
  9137. }
  9138. public function getText()
  9139. {
  9140. if($this->_text=='' && !empty($this->_query))
  9141. $this->setText($this->buildQuery($this->_query));
  9142. return $this->_text;
  9143. }
  9144. public function setText($value)
  9145. {
  9146. if($this->_connection->tablePrefix!==null && $value!='')
  9147. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  9148. else
  9149. $this->_text=$value;
  9150. $this->cancel();
  9151. return $this;
  9152. }
  9153. public function getConnection()
  9154. {
  9155. return $this->_connection;
  9156. }
  9157. public function getPdoStatement()
  9158. {
  9159. return $this->_statement;
  9160. }
  9161. public function prepare()
  9162. {
  9163. if($this->_statement==null)
  9164. {
  9165. try
  9166. {
  9167. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  9168. $this->_paramLog=array();
  9169. }
  9170. catch(Exception $e)
  9171. {
  9172. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9173. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9174. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  9175. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  9176. }
  9177. }
  9178. }
  9179. public function cancel()
  9180. {
  9181. $this->_statement=null;
  9182. }
  9183. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  9184. {
  9185. $this->prepare();
  9186. if($dataType===null)
  9187. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  9188. elseif($length===null)
  9189. $this->_statement->bindParam($name,$value,$dataType);
  9190. elseif($driverOptions===null)
  9191. $this->_statement->bindParam($name,$value,$dataType,$length);
  9192. else
  9193. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  9194. $this->_paramLog[$name]=&$value;
  9195. return $this;
  9196. }
  9197. public function bindValue($name, $value, $dataType=null)
  9198. {
  9199. $this->prepare();
  9200. if($dataType===null)
  9201. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  9202. else
  9203. $this->_statement->bindValue($name,$value,$dataType);
  9204. $this->_paramLog[$name]=$value;
  9205. return $this;
  9206. }
  9207. public function bindValues($values)
  9208. {
  9209. $this->prepare();
  9210. foreach($values as $name=>$value)
  9211. {
  9212. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  9213. $this->_paramLog[$name]=$value;
  9214. }
  9215. return $this;
  9216. }
  9217. public function execute($params=array())
  9218. {
  9219. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  9220. {
  9221. $p=array();
  9222. foreach($pars as $name=>$value)
  9223. $p[$name]=$name.'='.var_export($value,true);
  9224. $par='. Bound with ' .implode(', ',$p);
  9225. }
  9226. else
  9227. $par='';
  9228. try
  9229. {
  9230. if($this->_connection->enableProfiling)
  9231. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9232. $this->prepare();
  9233. if($params===array())
  9234. $this->_statement->execute();
  9235. else
  9236. $this->_statement->execute($params);
  9237. $n=$this->_statement->rowCount();
  9238. if($this->_connection->enableProfiling)
  9239. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9240. return $n;
  9241. }
  9242. catch(Exception $e)
  9243. {
  9244. if($this->_connection->enableProfiling)
  9245. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9246. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9247. $message=$e->getMessage();
  9248. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  9249. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9250. if(YII_DEBUG)
  9251. $message.='. The SQL statement executed was: '.$this->getText().$par;
  9252. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  9253. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  9254. }
  9255. }
  9256. public function query($params=array())
  9257. {
  9258. return $this->queryInternal('',0,$params);
  9259. }
  9260. public function queryAll($fetchAssociative=true,$params=array())
  9261. {
  9262. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  9263. }
  9264. public function queryRow($fetchAssociative=true,$params=array())
  9265. {
  9266. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  9267. }
  9268. public function queryScalar($params=array())
  9269. {
  9270. $result=$this->queryInternal('fetchColumn',0,$params);
  9271. if(is_resource($result) && get_resource_type($result)==='stream')
  9272. return stream_get_contents($result);
  9273. else
  9274. return $result;
  9275. }
  9276. public function queryColumn($params=array())
  9277. {
  9278. return $this->queryInternal('fetchAll',array(PDO::FETCH_COLUMN, 0),$params);
  9279. }
  9280. private function queryInternal($method,$mode,$params=array())
  9281. {
  9282. $params=array_merge($this->params,$params);
  9283. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  9284. {
  9285. $p=array();
  9286. foreach($pars as $name=>$value)
  9287. $p[$name]=$name.'='.var_export($value,true);
  9288. $par='. Bound with '.implode(', ',$p);
  9289. }
  9290. else
  9291. $par='';
  9292. if($this->_connection->queryCachingCount>0 && $method!==''
  9293. && $this->_connection->queryCachingDuration>0
  9294. && $this->_connection->queryCacheID!==false
  9295. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  9296. {
  9297. $this->_connection->queryCachingCount--;
  9298. $cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
  9299. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  9300. if(($result=$cache->get($cacheKey))!==false)
  9301. {
  9302. return $result[0];
  9303. }
  9304. }
  9305. try
  9306. {
  9307. if($this->_connection->enableProfiling)
  9308. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9309. $this->prepare();
  9310. if($params===array())
  9311. $this->_statement->execute();
  9312. else
  9313. $this->_statement->execute($params);
  9314. if($method==='')
  9315. $result=new CDbDataReader($this);
  9316. else
  9317. {
  9318. $mode=(array)$mode;
  9319. call_user_func_array(array($this->_statement, 'setFetchMode'), $mode);
  9320. $result=$this->_statement->$method();
  9321. $this->_statement->closeCursor();
  9322. }
  9323. if($this->_connection->enableProfiling)
  9324. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9325. if(isset($cache,$cacheKey))
  9326. $cache->set($cacheKey, array($result), $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  9327. return $result;
  9328. }
  9329. catch(Exception $e)
  9330. {
  9331. if($this->_connection->enableProfiling)
  9332. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9333. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9334. $message=$e->getMessage();
  9335. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  9336. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9337. if(YII_DEBUG)
  9338. $message.='. The SQL statement executed was: '.$this->getText().$par;
  9339. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  9340. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  9341. }
  9342. }
  9343. public function buildQuery($query)
  9344. {
  9345. $sql=!empty($query['distinct']) ? 'SELECT DISTINCT' : 'SELECT';
  9346. $sql.=' '.(!empty($query['select']) ? $query['select'] : '*');
  9347. if(!empty($query['from']))
  9348. $sql.="\nFROM ".$query['from'];
  9349. else
  9350. throw new CDbException(Yii::t('yii','The DB query must contain the "from" portion.'));
  9351. if(!empty($query['join']))
  9352. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  9353. if(!empty($query['where']))
  9354. $sql.="\nWHERE ".$query['where'];
  9355. if(!empty($query['group']))
  9356. $sql.="\nGROUP BY ".$query['group'];
  9357. if(!empty($query['having']))
  9358. $sql.="\nHAVING ".$query['having'];
  9359. if(!empty($query['union']))
  9360. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  9361. if(!empty($query['order']))
  9362. $sql.="\nORDER BY ".$query['order'];
  9363. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  9364. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  9365. if($limit>=0 || $offset>0)
  9366. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  9367. return $sql;
  9368. }
  9369. public function select($columns='*', $option='')
  9370. {
  9371. if(is_string($columns) && strpos($columns,'(')!==false)
  9372. $this->_query['select']=$columns;
  9373. else
  9374. {
  9375. if(!is_array($columns))
  9376. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9377. foreach($columns as $i=>$column)
  9378. {
  9379. if(is_object($column))
  9380. $columns[$i]=(string)$column;
  9381. elseif(strpos($column,'(')===false)
  9382. {
  9383. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  9384. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  9385. else
  9386. $columns[$i]=$this->_connection->quoteColumnName($column);
  9387. }
  9388. }
  9389. $this->_query['select']=implode(', ',$columns);
  9390. }
  9391. if($option!='')
  9392. $this->_query['select']=$option.' '.$this->_query['select'];
  9393. return $this;
  9394. }
  9395. public function getSelect()
  9396. {
  9397. return isset($this->_query['select']) ? $this->_query['select'] : '';
  9398. }
  9399. public function setSelect($value)
  9400. {
  9401. $this->select($value);
  9402. }
  9403. public function selectDistinct($columns='*')
  9404. {
  9405. $this->_query['distinct']=true;
  9406. return $this->select($columns);
  9407. }
  9408. public function getDistinct()
  9409. {
  9410. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  9411. }
  9412. public function setDistinct($value)
  9413. {
  9414. $this->_query['distinct']=$value;
  9415. }
  9416. public function from($tables)
  9417. {
  9418. if(is_string($tables) && strpos($tables,'(')!==false)
  9419. $this->_query['from']=$tables;
  9420. else
  9421. {
  9422. if(!is_array($tables))
  9423. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  9424. foreach($tables as $i=>$table)
  9425. {
  9426. if(strpos($table,'(')===false)
  9427. {
  9428. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9429. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9430. else
  9431. $tables[$i]=$this->_connection->quoteTableName($table);
  9432. }
  9433. }
  9434. $this->_query['from']=implode(', ',$tables);
  9435. }
  9436. return $this;
  9437. }
  9438. public function getFrom()
  9439. {
  9440. return isset($this->_query['from']) ? $this->_query['from'] : '';
  9441. }
  9442. public function setFrom($value)
  9443. {
  9444. $this->from($value);
  9445. }
  9446. public function where($conditions, $params=array())
  9447. {
  9448. $this->_query['where']=$this->processConditions($conditions);
  9449. foreach($params as $name=>$value)
  9450. $this->params[$name]=$value;
  9451. return $this;
  9452. }
  9453. public function andWhere($conditions,$params=array())
  9454. {
  9455. if(isset($this->_query['where']))
  9456. $this->_query['where']=$this->processConditions(array('AND',$this->_query['where'],$conditions));
  9457. else
  9458. $this->_query['where']=$this->processConditions($conditions);
  9459. foreach($params as $name=>$value)
  9460. $this->params[$name]=$value;
  9461. return $this;
  9462. }
  9463. public function orWhere($conditions,$params=array())
  9464. {
  9465. if(isset($this->_query['where']))
  9466. $this->_query['where']=$this->processConditions(array('OR',$this->_query['where'],$conditions));
  9467. else
  9468. $this->_query['where']=$this->processConditions($conditions);
  9469. foreach($params as $name=>$value)
  9470. $this->params[$name]=$value;
  9471. return $this;
  9472. }
  9473. public function getWhere()
  9474. {
  9475. return isset($this->_query['where']) ? $this->_query['where'] : '';
  9476. }
  9477. public function setWhere($value)
  9478. {
  9479. $this->where($value);
  9480. }
  9481. public function join($table, $conditions, $params=array())
  9482. {
  9483. return $this->joinInternal('join', $table, $conditions, $params);
  9484. }
  9485. public function getJoin()
  9486. {
  9487. return isset($this->_query['join']) ? $this->_query['join'] : '';
  9488. }
  9489. public function setJoin($value)
  9490. {
  9491. $this->_query['join']=$value;
  9492. }
  9493. public function leftJoin($table, $conditions, $params=array())
  9494. {
  9495. return $this->joinInternal('left join', $table, $conditions, $params);
  9496. }
  9497. public function rightJoin($table, $conditions, $params=array())
  9498. {
  9499. return $this->joinInternal('right join', $table, $conditions, $params);
  9500. }
  9501. public function crossJoin($table)
  9502. {
  9503. return $this->joinInternal('cross join', $table);
  9504. }
  9505. public function naturalJoin($table)
  9506. {
  9507. return $this->joinInternal('natural join', $table);
  9508. }
  9509. public function group($columns)
  9510. {
  9511. if(is_string($columns) && strpos($columns,'(')!==false)
  9512. $this->_query['group']=$columns;
  9513. else
  9514. {
  9515. if(!is_array($columns))
  9516. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9517. foreach($columns as $i=>$column)
  9518. {
  9519. if(is_object($column))
  9520. $columns[$i]=(string)$column;
  9521. elseif(strpos($column,'(')===false)
  9522. $columns[$i]=$this->_connection->quoteColumnName($column);
  9523. }
  9524. $this->_query['group']=implode(', ',$columns);
  9525. }
  9526. return $this;
  9527. }
  9528. public function getGroup()
  9529. {
  9530. return isset($this->_query['group']) ? $this->_query['group'] : '';
  9531. }
  9532. public function setGroup($value)
  9533. {
  9534. $this->group($value);
  9535. }
  9536. public function having($conditions, $params=array())
  9537. {
  9538. $this->_query['having']=$this->processConditions($conditions);
  9539. foreach($params as $name=>$value)
  9540. $this->params[$name]=$value;
  9541. return $this;
  9542. }
  9543. public function getHaving()
  9544. {
  9545. return isset($this->_query['having']) ? $this->_query['having'] : '';
  9546. }
  9547. public function setHaving($value)
  9548. {
  9549. $this->having($value);
  9550. }
  9551. public function order($columns)
  9552. {
  9553. if(is_string($columns) && strpos($columns,'(')!==false)
  9554. $this->_query['order']=$columns;
  9555. else
  9556. {
  9557. if(!is_array($columns))
  9558. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9559. foreach($columns as $i=>$column)
  9560. {
  9561. if(is_object($column))
  9562. $columns[$i]=(string)$column;
  9563. elseif(strpos($column,'(')===false)
  9564. {
  9565. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  9566. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  9567. else
  9568. $columns[$i]=$this->_connection->quoteColumnName($column);
  9569. }
  9570. }
  9571. $this->_query['order']=implode(', ',$columns);
  9572. }
  9573. return $this;
  9574. }
  9575. public function getOrder()
  9576. {
  9577. return isset($this->_query['order']) ? $this->_query['order'] : '';
  9578. }
  9579. public function setOrder($value)
  9580. {
  9581. $this->order($value);
  9582. }
  9583. public function limit($limit, $offset=null)
  9584. {
  9585. $this->_query['limit']=(int)$limit;
  9586. if($offset!==null)
  9587. $this->offset($offset);
  9588. return $this;
  9589. }
  9590. public function getLimit()
  9591. {
  9592. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  9593. }
  9594. public function setLimit($value)
  9595. {
  9596. $this->limit($value);
  9597. }
  9598. public function offset($offset)
  9599. {
  9600. $this->_query['offset']=(int)$offset;
  9601. return $this;
  9602. }
  9603. public function getOffset()
  9604. {
  9605. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  9606. }
  9607. public function setOffset($value)
  9608. {
  9609. $this->offset($value);
  9610. }
  9611. public function union($sql)
  9612. {
  9613. if(isset($this->_query['union']) && is_string($this->_query['union']))
  9614. $this->_query['union']=array($this->_query['union']);
  9615. $this->_query['union'][]=$sql;
  9616. return $this;
  9617. }
  9618. public function getUnion()
  9619. {
  9620. return isset($this->_query['union']) ? $this->_query['union'] : '';
  9621. }
  9622. public function setUnion($value)
  9623. {
  9624. $this->_query['union']=$value;
  9625. }
  9626. public function insert($table, $columns)
  9627. {
  9628. $params=array();
  9629. $names=array();
  9630. $placeholders=array();
  9631. foreach($columns as $name=>$value)
  9632. {
  9633. $names[]=$this->_connection->quoteColumnName($name);
  9634. if($value instanceof CDbExpression)
  9635. {
  9636. $placeholders[] = $value->expression;
  9637. foreach($value->params as $n => $v)
  9638. $params[$n] = $v;
  9639. }
  9640. else
  9641. {
  9642. $placeholders[] = ':' . $name;
  9643. $params[':' . $name] = $value;
  9644. }
  9645. }
  9646. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  9647. . ' (' . implode(', ',$names) . ') VALUES ('
  9648. . implode(', ', $placeholders) . ')';
  9649. return $this->setText($sql)->execute($params);
  9650. }
  9651. public function update($table, $columns, $conditions='', $params=array())
  9652. {
  9653. $lines=array();
  9654. foreach($columns as $name=>$value)
  9655. {
  9656. if($value instanceof CDbExpression)
  9657. {
  9658. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  9659. foreach($value->params as $n => $v)
  9660. $params[$n] = $v;
  9661. }
  9662. else
  9663. {
  9664. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  9665. $params[':' . $name]=$value;
  9666. }
  9667. }
  9668. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  9669. if(($where=$this->processConditions($conditions))!='')
  9670. $sql.=' WHERE '.$where;
  9671. return $this->setText($sql)->execute($params);
  9672. }
  9673. public function delete($table, $conditions='', $params=array())
  9674. {
  9675. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  9676. if(($where=$this->processConditions($conditions))!='')
  9677. $sql.=' WHERE '.$where;
  9678. return $this->setText($sql)->execute($params);
  9679. }
  9680. public function createTable($table, $columns, $options=null)
  9681. {
  9682. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  9683. }
  9684. public function renameTable($table, $newName)
  9685. {
  9686. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  9687. }
  9688. public function dropTable($table)
  9689. {
  9690. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  9691. }
  9692. public function truncateTable($table)
  9693. {
  9694. $schema=$this->getConnection()->getSchema();
  9695. $n=$this->setText($schema->truncateTable($table))->execute();
  9696. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  9697. $schema->resetSequence($schema->getTable($table));
  9698. return $n;
  9699. }
  9700. public function addColumn($table, $column, $type)
  9701. {
  9702. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  9703. }
  9704. public function dropColumn($table, $column)
  9705. {
  9706. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  9707. }
  9708. public function renameColumn($table, $name, $newName)
  9709. {
  9710. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  9711. }
  9712. public function alterColumn($table, $column, $type)
  9713. {
  9714. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  9715. }
  9716. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9717. {
  9718. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  9719. }
  9720. public function dropForeignKey($name, $table)
  9721. {
  9722. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  9723. }
  9724. public function createIndex($name, $table, $column, $unique=false)
  9725. {
  9726. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $column, $unique))->execute();
  9727. }
  9728. public function dropIndex($name, $table)
  9729. {
  9730. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  9731. }
  9732. private function processConditions($conditions)
  9733. {
  9734. if(!is_array($conditions))
  9735. return $conditions;
  9736. elseif($conditions===array())
  9737. return '';
  9738. $n=count($conditions);
  9739. $operator=strtoupper($conditions[0]);
  9740. if($operator==='OR' || $operator==='AND')
  9741. {
  9742. $parts=array();
  9743. for($i=1;$i<$n;++$i)
  9744. {
  9745. $condition=$this->processConditions($conditions[$i]);
  9746. if($condition!=='')
  9747. $parts[]='('.$condition.')';
  9748. }
  9749. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  9750. }
  9751. if(!isset($conditions[1],$conditions[2]))
  9752. return '';
  9753. $column=$conditions[1];
  9754. if(strpos($column,'(')===false)
  9755. $column=$this->_connection->quoteColumnName($column);
  9756. $values=$conditions[2];
  9757. if(!is_array($values))
  9758. $values=array($values);
  9759. if($operator==='IN' || $operator==='NOT IN')
  9760. {
  9761. if($values===array())
  9762. return $operator==='IN' ? '0=1' : '';
  9763. foreach($values as $i=>$value)
  9764. {
  9765. if(is_string($value))
  9766. $values[$i]=$this->_connection->quoteValue($value);
  9767. else
  9768. $values[$i]=(string)$value;
  9769. }
  9770. return $column.' '.$operator.' ('.implode(', ',$values).')';
  9771. }
  9772. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  9773. {
  9774. if($values===array())
  9775. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  9776. if($operator==='LIKE' || $operator==='NOT LIKE')
  9777. $andor=' AND ';
  9778. else
  9779. {
  9780. $andor=' OR ';
  9781. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  9782. }
  9783. $expressions=array();
  9784. foreach($values as $value)
  9785. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  9786. return implode($andor,$expressions);
  9787. }
  9788. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  9789. }
  9790. private function joinInternal($type, $table, $conditions='', $params=array())
  9791. {
  9792. if(strpos($table,'(')===false)
  9793. {
  9794. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9795. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9796. else
  9797. $table=$this->_connection->quoteTableName($table);
  9798. }
  9799. $conditions=$this->processConditions($conditions);
  9800. if($conditions!='')
  9801. $conditions=' ON '.$conditions;
  9802. if(isset($this->_query['join']) && is_string($this->_query['join']))
  9803. $this->_query['join']=array($this->_query['join']);
  9804. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  9805. foreach($params as $name=>$value)
  9806. $this->params[$name]=$value;
  9807. return $this;
  9808. }
  9809. public function addPrimaryKey($name,$table,$columns)
  9810. {
  9811. return $this->setText($this->getConnection()->getSchema()->addPrimaryKey($name,$table,$columns))->execute();
  9812. }
  9813. public function dropPrimaryKey($name,$table)
  9814. {
  9815. return $this->setText($this->getConnection()->getSchema()->dropPrimaryKey($name,$table))->execute();
  9816. }
  9817. }
  9818. class CDbColumnSchema extends CComponent
  9819. {
  9820. public $name;
  9821. public $rawName;
  9822. public $allowNull;
  9823. public $dbType;
  9824. public $type;
  9825. public $defaultValue;
  9826. public $size;
  9827. public $precision;
  9828. public $scale;
  9829. public $isPrimaryKey;
  9830. public $isForeignKey;
  9831. public $autoIncrement=false;
  9832. public $comment='';
  9833. public function init($dbType, $defaultValue)
  9834. {
  9835. $this->dbType=$dbType;
  9836. $this->extractType($dbType);
  9837. $this->extractLimit($dbType);
  9838. if($defaultValue!==null)
  9839. $this->extractDefault($defaultValue);
  9840. }
  9841. protected function extractType($dbType)
  9842. {
  9843. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  9844. $this->type='integer';
  9845. elseif(stripos($dbType,'bool')!==false)
  9846. $this->type='boolean';
  9847. elseif(preg_match('/(real|floa|doub)/i',$dbType))
  9848. $this->type='double';
  9849. else
  9850. $this->type='string';
  9851. }
  9852. protected function extractLimit($dbType)
  9853. {
  9854. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  9855. {
  9856. $values=explode(',',$matches[1]);
  9857. $this->size=$this->precision=(int)$values[0];
  9858. if(isset($values[1]))
  9859. $this->scale=(int)$values[1];
  9860. }
  9861. }
  9862. protected function extractDefault($defaultValue)
  9863. {
  9864. $this->defaultValue=$this->typecast($defaultValue);
  9865. }
  9866. public function typecast($value)
  9867. {
  9868. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  9869. return $value;
  9870. if($value==='' && $this->allowNull)
  9871. return $this->type==='string' ? '' : null;
  9872. switch($this->type)
  9873. {
  9874. case 'string': return (string)$value;
  9875. case 'integer': return (integer)$value;
  9876. case 'boolean': return (boolean)$value;
  9877. case 'double':
  9878. default: return $value;
  9879. }
  9880. }
  9881. }
  9882. class CSqliteColumnSchema extends CDbColumnSchema
  9883. {
  9884. protected function extractDefault($defaultValue)
  9885. {
  9886. if($this->dbType==='timestamp' && $defaultValue==='CURRENT_TIMESTAMP')
  9887. $this->defaultValue=null;
  9888. else
  9889. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  9890. if($this->type==='string' && $this->defaultValue!==null) // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  9891. $this->defaultValue=trim($this->defaultValue,"'\"");
  9892. }
  9893. }
  9894. abstract class CValidator extends CComponent
  9895. {
  9896. public static $builtInValidators=array(
  9897. 'required'=>'CRequiredValidator',
  9898. 'filter'=>'CFilterValidator',
  9899. 'match'=>'CRegularExpressionValidator',
  9900. 'email'=>'CEmailValidator',
  9901. 'url'=>'CUrlValidator',
  9902. 'unique'=>'CUniqueValidator',
  9903. 'compare'=>'CCompareValidator',
  9904. 'length'=>'CStringValidator',
  9905. 'in'=>'CRangeValidator',
  9906. 'numerical'=>'CNumberValidator',
  9907. 'captcha'=>'CCaptchaValidator',
  9908. 'type'=>'CTypeValidator',
  9909. 'file'=>'CFileValidator',
  9910. 'default'=>'CDefaultValueValidator',
  9911. 'exist'=>'CExistValidator',
  9912. 'boolean'=>'CBooleanValidator',
  9913. 'safe'=>'CSafeValidator',
  9914. 'unsafe'=>'CUnsafeValidator',
  9915. 'date'=>'CDateValidator',
  9916. );
  9917. public $attributes;
  9918. public $message;
  9919. public $skipOnError=false;
  9920. public $on;
  9921. public $except;
  9922. public $safe=true;
  9923. public $enableClientValidation=true;
  9924. abstract protected function validateAttribute($object,$attribute);
  9925. public static function createValidator($name,$object,$attributes,$params=array())
  9926. {
  9927. if(is_string($attributes))
  9928. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  9929. if(isset($params['on']))
  9930. {
  9931. if(is_array($params['on']))
  9932. $on=$params['on'];
  9933. else
  9934. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  9935. }
  9936. else
  9937. $on=array();
  9938. if(isset($params['except']))
  9939. {
  9940. if(is_array($params['except']))
  9941. $except=$params['except'];
  9942. else
  9943. $except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
  9944. }
  9945. else
  9946. $except=array();
  9947. if(method_exists($object,$name))
  9948. {
  9949. $validator=new CInlineValidator;
  9950. $validator->attributes=$attributes;
  9951. $validator->method=$name;
  9952. if(isset($params['clientValidate']))
  9953. {
  9954. $validator->clientValidate=$params['clientValidate'];
  9955. unset($params['clientValidate']);
  9956. }
  9957. $validator->params=$params;
  9958. if(isset($params['skipOnError']))
  9959. $validator->skipOnError=$params['skipOnError'];
  9960. }
  9961. else
  9962. {
  9963. $params['attributes']=$attributes;
  9964. if(isset(self::$builtInValidators[$name]))
  9965. $className=Yii::import(self::$builtInValidators[$name],true);
  9966. else
  9967. $className=Yii::import($name,true);
  9968. $validator=new $className;
  9969. foreach($params as $name=>$value)
  9970. $validator->$name=$value;
  9971. }
  9972. $validator->on=empty($on) ? array() : array_combine($on,$on);
  9973. $validator->except=empty($except) ? array() : array_combine($except,$except);
  9974. return $validator;
  9975. }
  9976. public function validate($object,$attributes=null)
  9977. {
  9978. if(is_array($attributes))
  9979. $attributes=array_intersect($this->attributes,$attributes);
  9980. else
  9981. $attributes=$this->attributes;
  9982. foreach($attributes as $attribute)
  9983. {
  9984. if(!$this->skipOnError || !$object->hasErrors($attribute))
  9985. $this->validateAttribute($object,$attribute);
  9986. }
  9987. }
  9988. public function clientValidateAttribute($object,$attribute)
  9989. {
  9990. }
  9991. public function applyTo($scenario)
  9992. {
  9993. if(isset($this->except[$scenario]))
  9994. return false;
  9995. return empty($this->on) || isset($this->on[$scenario]);
  9996. }
  9997. protected function addError($object,$attribute,$message,$params=array())
  9998. {
  9999. $params['{attribute}']=$object->getAttributeLabel($attribute);
  10000. $object->addError($attribute,strtr($message,$params));
  10001. }
  10002. protected function isEmpty($value,$trim=false)
  10003. {
  10004. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  10005. }
  10006. }
  10007. class CStringValidator extends CValidator
  10008. {
  10009. public $max;
  10010. public $min;
  10011. public $is;
  10012. public $tooShort;
  10013. public $tooLong;
  10014. public $allowEmpty=true;
  10015. public $encoding;
  10016. protected function validateAttribute($object,$attribute)
  10017. {
  10018. $value=$object->$attribute;
  10019. if($this->allowEmpty && $this->isEmpty($value))
  10020. return;
  10021. if(is_array($value))
  10022. {
  10023. // https://github.com/yiisoft/yii/issues/1955
  10024. $this->addError($object,$attribute,Yii::t('yii','{attribute} is invalid.'));
  10025. return;
  10026. }
  10027. if(function_exists('mb_strlen') && $this->encoding!==false)
  10028. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  10029. else
  10030. $length=strlen($value);
  10031. if($this->min!==null && $length<$this->min)
  10032. {
  10033. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  10034. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  10035. }
  10036. if($this->max!==null && $length>$this->max)
  10037. {
  10038. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  10039. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  10040. }
  10041. if($this->is!==null && $length!==$this->is)
  10042. {
  10043. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  10044. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  10045. }
  10046. }
  10047. public function clientValidateAttribute($object,$attribute)
  10048. {
  10049. $label=$object->getAttributeLabel($attribute);
  10050. if(($message=$this->message)===null)
  10051. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  10052. $message=strtr($message, array(
  10053. '{attribute}'=>$label,
  10054. '{length}'=>$this->is,
  10055. ));
  10056. if(($tooShort=$this->tooShort)===null)
  10057. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  10058. $tooShort=strtr($tooShort, array(
  10059. '{attribute}'=>$label,
  10060. '{min}'=>$this->min,
  10061. ));
  10062. if(($tooLong=$this->tooLong)===null)
  10063. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  10064. $tooLong=strtr($tooLong, array(
  10065. '{attribute}'=>$label,
  10066. '{max}'=>$this->max,
  10067. ));
  10068. $js='';
  10069. if($this->min!==null)
  10070. {
  10071. $js.="
  10072. if(value.length<{$this->min}) {
  10073. messages.push(".CJSON::encode($tooShort).");
  10074. }
  10075. ";
  10076. }
  10077. if($this->max!==null)
  10078. {
  10079. $js.="
  10080. if(value.length>{$this->max}) {
  10081. messages.push(".CJSON::encode($tooLong).");
  10082. }
  10083. ";
  10084. }
  10085. if($this->is!==null)
  10086. {
  10087. $js.="
  10088. if(value.length!={$this->is}) {
  10089. messages.push(".CJSON::encode($message).");
  10090. }
  10091. ";
  10092. }
  10093. if($this->allowEmpty)
  10094. {
  10095. $js="
  10096. if(jQuery.trim(value)!='') {
  10097. $js
  10098. }
  10099. ";
  10100. }
  10101. return $js;
  10102. }
  10103. }
  10104. class CRequiredValidator extends CValidator
  10105. {
  10106. public $requiredValue;
  10107. public $strict=false;
  10108. public $trim=true;
  10109. protected function validateAttribute($object,$attribute)
  10110. {
  10111. $value=$object->$attribute;
  10112. if($this->requiredValue!==null)
  10113. {
  10114. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  10115. {
  10116. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  10117. array('{value}'=>$this->requiredValue));
  10118. $this->addError($object,$attribute,$message);
  10119. }
  10120. }
  10121. elseif($this->isEmpty($value,$this->trim))
  10122. {
  10123. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  10124. $this->addError($object,$attribute,$message);
  10125. }
  10126. }
  10127. public function clientValidateAttribute($object,$attribute)
  10128. {
  10129. $message=$this->message;
  10130. if($this->requiredValue!==null)
  10131. {
  10132. if($message===null)
  10133. $message=Yii::t('yii','{attribute} must be {value}.');
  10134. $message=strtr($message, array(
  10135. '{value}'=>$this->requiredValue,
  10136. '{attribute}'=>$object->getAttributeLabel($attribute),
  10137. ));
  10138. return "
  10139. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  10140. messages.push(".CJSON::encode($message).");
  10141. }
  10142. ";
  10143. }
  10144. else
  10145. {
  10146. if($message===null)
  10147. $message=Yii::t('yii','{attribute} cannot be blank.');
  10148. $message=strtr($message, array(
  10149. '{attribute}'=>$object->getAttributeLabel($attribute),
  10150. ));
  10151. if($this->trim)
  10152. $emptyCondition = "jQuery.trim(value)==''";
  10153. else
  10154. $emptyCondition = "value==''";
  10155. return "
  10156. if({$emptyCondition}) {
  10157. messages.push(".CJSON::encode($message).");
  10158. }
  10159. ";
  10160. }
  10161. }
  10162. }
  10163. class CNumberValidator extends CValidator
  10164. {
  10165. public $integerOnly=false;
  10166. public $allowEmpty=true;
  10167. public $max;
  10168. public $min;
  10169. public $tooBig;
  10170. public $tooSmall;
  10171. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  10172. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  10173. protected function validateAttribute($object,$attribute)
  10174. {
  10175. $value=$object->$attribute;
  10176. if($this->allowEmpty && $this->isEmpty($value))
  10177. return;
  10178. if(!is_numeric($value))
  10179. {
  10180. // https://github.com/yiisoft/yii/issues/1955
  10181. // https://github.com/yiisoft/yii/issues/1669
  10182. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  10183. $this->addError($object,$attribute,$message);
  10184. return;
  10185. }
  10186. if($this->integerOnly)
  10187. {
  10188. if(!preg_match($this->integerPattern,"$value"))
  10189. {
  10190. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  10191. $this->addError($object,$attribute,$message);
  10192. }
  10193. }
  10194. else
  10195. {
  10196. if(!preg_match($this->numberPattern,"$value"))
  10197. {
  10198. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  10199. $this->addError($object,$attribute,$message);
  10200. }
  10201. }
  10202. if($this->min!==null && $value<$this->min)
  10203. {
  10204. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  10205. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  10206. }
  10207. if($this->max!==null && $value>$this->max)
  10208. {
  10209. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  10210. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  10211. }
  10212. }
  10213. public function clientValidateAttribute($object,$attribute)
  10214. {
  10215. $label=$object->getAttributeLabel($attribute);
  10216. if(($message=$this->message)===null)
  10217. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  10218. $message=strtr($message, array(
  10219. '{attribute}'=>$label,
  10220. ));
  10221. if(($tooBig=$this->tooBig)===null)
  10222. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  10223. $tooBig=strtr($tooBig, array(
  10224. '{attribute}'=>$label,
  10225. '{max}'=>$this->max,
  10226. ));
  10227. if(($tooSmall=$this->tooSmall)===null)
  10228. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  10229. $tooSmall=strtr($tooSmall, array(
  10230. '{attribute}'=>$label,
  10231. '{min}'=>$this->min,
  10232. ));
  10233. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  10234. $js="
  10235. if(!value.match($pattern)) {
  10236. messages.push(".CJSON::encode($message).");
  10237. }
  10238. ";
  10239. if($this->min!==null)
  10240. {
  10241. $js.="
  10242. if(value<{$this->min}) {
  10243. messages.push(".CJSON::encode($tooSmall).");
  10244. }
  10245. ";
  10246. }
  10247. if($this->max!==null)
  10248. {
  10249. $js.="
  10250. if(value>{$this->max}) {
  10251. messages.push(".CJSON::encode($tooBig).");
  10252. }
  10253. ";
  10254. }
  10255. if($this->allowEmpty)
  10256. {
  10257. $js="
  10258. if(jQuery.trim(value)!='') {
  10259. $js
  10260. }
  10261. ";
  10262. }
  10263. return $js;
  10264. }
  10265. }
  10266. class CListIterator implements Iterator
  10267. {
  10268. private $_d;
  10269. private $_i;
  10270. private $_c;
  10271. public function __construct(&$data)
  10272. {
  10273. $this->_d=&$data;
  10274. $this->_i=0;
  10275. $this->_c=count($this->_d);
  10276. }
  10277. public function rewind()
  10278. {
  10279. $this->_i=0;
  10280. }
  10281. public function key()
  10282. {
  10283. return $this->_i;
  10284. }
  10285. public function current()
  10286. {
  10287. return $this->_d[$this->_i];
  10288. }
  10289. public function next()
  10290. {
  10291. $this->_i++;
  10292. }
  10293. public function valid()
  10294. {
  10295. return $this->_i<$this->_c;
  10296. }
  10297. }
  10298. interface IApplicationComponent
  10299. {
  10300. public function init();
  10301. public function getIsInitialized();
  10302. }
  10303. interface ICache
  10304. {
  10305. public function get($id);
  10306. public function mget($ids);
  10307. public function set($id,$value,$expire=0,$dependency=null);
  10308. public function add($id,$value,$expire=0,$dependency=null);
  10309. public function delete($id);
  10310. public function flush();
  10311. }
  10312. interface ICacheDependency
  10313. {
  10314. public function evaluateDependency();
  10315. public function getHasChanged();
  10316. }
  10317. interface IStatePersister
  10318. {
  10319. public function load();
  10320. public function save($state);
  10321. }
  10322. interface IFilter
  10323. {
  10324. public function filter($filterChain);
  10325. }
  10326. interface IAction
  10327. {
  10328. public function getId();
  10329. public function getController();
  10330. }
  10331. interface IWebServiceProvider
  10332. {
  10333. public function beforeWebMethod($service);
  10334. public function afterWebMethod($service);
  10335. }
  10336. interface IViewRenderer
  10337. {
  10338. public function renderFile($context,$file,$data,$return);
  10339. }
  10340. interface IUserIdentity
  10341. {
  10342. public function authenticate();
  10343. public function getIsAuthenticated();
  10344. public function getId();
  10345. public function getName();
  10346. public function getPersistentStates();
  10347. }
  10348. interface IWebUser
  10349. {
  10350. public function getId();
  10351. public function getName();
  10352. public function getIsGuest();
  10353. public function checkAccess($operation,$params=array());
  10354. public function loginRequired();
  10355. }
  10356. interface IAuthManager
  10357. {
  10358. public function checkAccess($itemName,$userId,$params=array());
  10359. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  10360. public function removeAuthItem($name);
  10361. public function getAuthItems($type=null,$userId=null);
  10362. public function getAuthItem($name);
  10363. public function saveAuthItem($item,$oldName=null);
  10364. public function addItemChild($itemName,$childName);
  10365. public function removeItemChild($itemName,$childName);
  10366. public function hasItemChild($itemName,$childName);
  10367. public function getItemChildren($itemName);
  10368. public function assign($itemName,$userId,$bizRule=null,$data=null);
  10369. public function revoke($itemName,$userId);
  10370. public function isAssigned($itemName,$userId);
  10371. public function getAuthAssignment($itemName,$userId);
  10372. public function getAuthAssignments($userId);
  10373. public function saveAuthAssignment($assignment);
  10374. public function clearAll();
  10375. public function clearAuthAssignments();
  10376. public function save();
  10377. public function executeBizRule($bizRule,$params,$data);
  10378. }
  10379. interface IBehavior
  10380. {
  10381. public function attach($component);
  10382. public function detach($component);
  10383. public function getEnabled();
  10384. public function setEnabled($value);
  10385. }
  10386. interface IWidgetFactory
  10387. {
  10388. public function createWidget($owner,$className,$properties=array());
  10389. }
  10390. interface IDataProvider
  10391. {
  10392. public function getId();
  10393. public function getItemCount($refresh=false);
  10394. public function getTotalItemCount($refresh=false);
  10395. public function getData($refresh=false);
  10396. public function getKeys($refresh=false);
  10397. public function getSort();
  10398. public function getPagination();
  10399. }
  10400. interface ILogFilter
  10401. {
  10402. public function filter(&$logs);
  10403. }
  10404. ?>