PageRenderTime 110ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/yii/framework/yiilite.php

https://bitbucket.org/ddonthula/zurmounl
PHP | 10023 lines | 9966 code | 2 blank | 55 comment | 707 complexity | 9f23d140de371469908a3c3fab54062e MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, LGPL-3.0, LGPL-2.1, BSD-2-Clause, GPL-2.0
  1. <?php
  2. /**
  3. * Yii bootstrap file.
  4. *
  5. * This file is automatically generated using 'build lite' command.
  6. * It is the result of merging commonly used Yii class files with
  7. * comments and trace statements removed away.
  8. *
  9. * By using this file instead of yii.php, an Yii application may
  10. * improve performance due to the reduction of PHP parsing time.
  11. * The performance improvement is especially obvious when PHP APC extension
  12. * is enabled.
  13. *
  14. * DO NOT modify this file manually.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @link http://www.yiiframework.com/
  18. * @copyright Copyright &copy; 2008-2012 Yii Software LLC
  19. * @license http://www.yiiframework.com/license/
  20. * @version $Id: $
  21. * @since 1.0
  22. */
  23. defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME',microtime(true));
  24. defined('YII_DEBUG') or define('YII_DEBUG',false);
  25. defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',0);
  26. defined('YII_ENABLE_EXCEPTION_HANDLER') or define('YII_ENABLE_EXCEPTION_HANDLER',true);
  27. defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER',true);
  28. defined('YII_PATH') or define('YII_PATH',dirname(__FILE__));
  29. defined('YII_ZII_PATH') or define('YII_ZII_PATH',YII_PATH.DIRECTORY_SEPARATOR.'zii');
  30. class YiiBase
  31. {
  32. public static $classMap=array();
  33. public static $enableIncludePath=true;
  34. private static $_aliases=array('system'=>YII_PATH,'zii'=>YII_ZII_PATH); // alias => path
  35. private static $_imports=array(); // alias => class name or directory
  36. private static $_includePaths; // list of include paths
  37. private static $_app;
  38. private static $_logger;
  39. public static function getVersion()
  40. {
  41. return '1.1.13';
  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. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory.',
  136. array('{alias}'=>$namespace)));
  137. }
  138. if(($pos=strrpos($alias,'.'))===false) // a simple class name
  139. {
  140. if($forceInclude && self::autoload($alias))
  141. self::$_imports[$alias]=$alias;
  142. return $alias;
  143. }
  144. $className=(string)substr($alias,$pos+1);
  145. $isClass=$className!=='*';
  146. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  147. return self::$_imports[$alias]=$className;
  148. if(($path=self::getPathOfAlias($alias))!==false)
  149. {
  150. if($isClass)
  151. {
  152. if($forceInclude)
  153. {
  154. if(is_file($path.'.php'))
  155. require($path.'.php');
  156. else
  157. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
  158. self::$_imports[$alias]=$className;
  159. }
  160. else
  161. self::$classMap[$className]=$path.'.php';
  162. return $className;
  163. }
  164. else // a directory
  165. {
  166. if(self::$_includePaths===null)
  167. {
  168. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  169. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  170. unset(self::$_includePaths[$pos]);
  171. }
  172. array_unshift(self::$_includePaths,$path);
  173. if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  174. self::$enableIncludePath=false;
  175. return self::$_imports[$alias]=$path;
  176. }
  177. }
  178. else
  179. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  180. array('{alias}'=>$alias)));
  181. }
  182. public static function getPathOfAlias($alias)
  183. {
  184. if(isset(self::$_aliases[$alias]))
  185. return self::$_aliases[$alias];
  186. elseif(($pos=strpos($alias,'.'))!==false)
  187. {
  188. $rootAlias=substr($alias,0,$pos);
  189. if(isset(self::$_aliases[$rootAlias]))
  190. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  191. elseif(self::$_app instanceof CWebApplication)
  192. {
  193. if(self::$_app->findModule($rootAlias)!==null)
  194. return self::getPathOfAlias($alias);
  195. }
  196. }
  197. return false;
  198. }
  199. public static function setPathOfAlias($alias,$path)
  200. {
  201. if(empty($path))
  202. unset(self::$_aliases[$alias]);
  203. else
  204. self::$_aliases[$alias]=rtrim($path,'\\/');
  205. }
  206. public static function autoload($className)
  207. {
  208. // use include so that the error PHP file may appear
  209. if(isset(self::$classMap[$className]))
  210. include(self::$classMap[$className]);
  211. elseif(isset(self::$_coreClasses[$className]))
  212. include(YII_PATH.self::$_coreClasses[$className]);
  213. else
  214. {
  215. // include class file relying on include_path
  216. if(strpos($className,'\\')===false) // class without namespace
  217. {
  218. if(self::$enableIncludePath===false)
  219. {
  220. foreach(self::$_includePaths as $path)
  221. {
  222. $classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
  223. if(is_file($classFile))
  224. {
  225. include($classFile);
  226. if(YII_DEBUG && basename(realpath($classFile))!==$className.'.php')
  227. throw new CException(Yii::t('yii','Class name "{class}" does not match class file "{file}".', array(
  228. '{class}'=>$className,
  229. '{file}'=>$classFile,
  230. )));
  231. break;
  232. }
  233. }
  234. }
  235. else
  236. include($className.'.php');
  237. }
  238. else // class name with namespace in PHP 5.3
  239. {
  240. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  241. if(($path=self::getPathOfAlias($namespace))!==false)
  242. include($path.'.php');
  243. else
  244. return false;
  245. }
  246. return class_exists($className,false) || interface_exists($className,false);
  247. }
  248. return true;
  249. }
  250. public static function trace($msg,$category='application')
  251. {
  252. if(YII_DEBUG)
  253. self::log($msg,CLogger::LEVEL_TRACE,$category);
  254. }
  255. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  256. {
  257. if(self::$_logger===null)
  258. self::$_logger=new CLogger;
  259. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  260. {
  261. $traces=debug_backtrace();
  262. $count=0;
  263. foreach($traces as $trace)
  264. {
  265. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  266. {
  267. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  268. if(++$count>=YII_TRACE_LEVEL)
  269. break;
  270. }
  271. }
  272. }
  273. self::$_logger->log($msg,$level,$category);
  274. }
  275. public static function beginProfile($token,$category='application')
  276. {
  277. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  278. }
  279. public static function endProfile($token,$category='application')
  280. {
  281. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  282. }
  283. public static function getLogger()
  284. {
  285. if(self::$_logger!==null)
  286. return self::$_logger;
  287. else
  288. return self::$_logger=new CLogger;
  289. }
  290. public static function setLogger($logger)
  291. {
  292. self::$_logger=$logger;
  293. }
  294. public static function powered()
  295. {
  296. return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
  297. }
  298. public static function t($category,$message,$params=array(),$source=null,$language=null)
  299. {
  300. if(self::$_app!==null)
  301. {
  302. if($source===null)
  303. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  304. if(($source=self::$_app->getComponent($source))!==null)
  305. $message=$source->translate($category,$message,$language);
  306. }
  307. if($params===array())
  308. return $message;
  309. if(!is_array($params))
  310. $params=array($params);
  311. if(isset($params[0])) // number choice
  312. {
  313. if(strpos($message,'|')!==false)
  314. {
  315. if(strpos($message,'#')===false)
  316. {
  317. $chunks=explode('|',$message);
  318. $expressions=self::$_app->getLocale($language)->getPluralRules();
  319. if($n=min(count($chunks),count($expressions)))
  320. {
  321. for($i=0;$i<$n;$i++)
  322. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  323. $message=implode('|',$chunks);
  324. }
  325. }
  326. $message=CChoiceFormat::format($message,$params[0]);
  327. }
  328. if(!isset($params['{n}']))
  329. $params['{n}']=$params[0];
  330. unset($params[0]);
  331. }
  332. return $params!==array() ? strtr($message,$params) : $message;
  333. }
  334. public static function registerAutoloader($callback, $append=false)
  335. {
  336. if($append)
  337. {
  338. self::$enableIncludePath=false;
  339. spl_autoload_register($callback);
  340. }
  341. else
  342. {
  343. spl_autoload_unregister(array('YiiBase','autoload'));
  344. spl_autoload_register($callback);
  345. spl_autoload_register(array('YiiBase','autoload'));
  346. }
  347. }
  348. private static $_coreClasses=array(
  349. 'CApplication' => '/base/CApplication.php',
  350. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  351. 'CBehavior' => '/base/CBehavior.php',
  352. 'CComponent' => '/base/CComponent.php',
  353. 'CErrorEvent' => '/base/CErrorEvent.php',
  354. 'CErrorHandler' => '/base/CErrorHandler.php',
  355. 'CException' => '/base/CException.php',
  356. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  357. 'CHttpException' => '/base/CHttpException.php',
  358. 'CModel' => '/base/CModel.php',
  359. 'CModelBehavior' => '/base/CModelBehavior.php',
  360. 'CModelEvent' => '/base/CModelEvent.php',
  361. 'CModule' => '/base/CModule.php',
  362. 'CSecurityManager' => '/base/CSecurityManager.php',
  363. 'CStatePersister' => '/base/CStatePersister.php',
  364. 'CApcCache' => '/caching/CApcCache.php',
  365. 'CCache' => '/caching/CCache.php',
  366. 'CDbCache' => '/caching/CDbCache.php',
  367. 'CDummyCache' => '/caching/CDummyCache.php',
  368. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  369. 'CFileCache' => '/caching/CFileCache.php',
  370. 'CMemCache' => '/caching/CMemCache.php',
  371. 'CWinCache' => '/caching/CWinCache.php',
  372. 'CXCache' => '/caching/CXCache.php',
  373. 'CZendDataCache' => '/caching/CZendDataCache.php',
  374. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  375. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  376. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  377. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  378. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  379. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  380. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  381. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  382. 'CConfiguration' => '/collections/CConfiguration.php',
  383. 'CList' => '/collections/CList.php',
  384. 'CListIterator' => '/collections/CListIterator.php',
  385. 'CMap' => '/collections/CMap.php',
  386. 'CMapIterator' => '/collections/CMapIterator.php',
  387. 'CQueue' => '/collections/CQueue.php',
  388. 'CQueueIterator' => '/collections/CQueueIterator.php',
  389. 'CStack' => '/collections/CStack.php',
  390. 'CStackIterator' => '/collections/CStackIterator.php',
  391. 'CTypedList' => '/collections/CTypedList.php',
  392. 'CTypedMap' => '/collections/CTypedMap.php',
  393. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  394. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  395. 'CConsoleCommandBehavior' => '/console/CConsoleCommandBehavior.php',
  396. 'CConsoleCommandEvent' => '/console/CConsoleCommandEvent.php',
  397. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  398. 'CHelpCommand' => '/console/CHelpCommand.php',
  399. 'CDbCommand' => '/db/CDbCommand.php',
  400. 'CDbConnection' => '/db/CDbConnection.php',
  401. 'CDbDataReader' => '/db/CDbDataReader.php',
  402. 'CDbException' => '/db/CDbException.php',
  403. 'CDbMigration' => '/db/CDbMigration.php',
  404. 'CDbTransaction' => '/db/CDbTransaction.php',
  405. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  406. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  407. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  408. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  409. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  410. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  411. 'CDbExpression' => '/db/schema/CDbExpression.php',
  412. 'CDbSchema' => '/db/schema/CDbSchema.php',
  413. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  414. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  415. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  416. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  417. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  418. 'CMssqlSqlsrvPdoAdapter' => '/db/schema/mssql/CMssqlSqlsrvPdoAdapter.php',
  419. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  420. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  421. 'CMysqlCommandBuilder' => '/db/schema/mysql/CMysqlCommandBuilder.php',
  422. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  423. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  424. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  425. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  426. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  427. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  428. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  429. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  430. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  431. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  432. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  433. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  434. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  435. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  436. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  437. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  438. 'CLocale' => '/i18n/CLocale.php',
  439. 'CMessageSource' => '/i18n/CMessageSource.php',
  440. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  441. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  442. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  443. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  444. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  445. 'CChainedLogFilter' => '/logging/CChainedLogFilter.php',
  446. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  447. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  448. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  449. 'CLogFilter' => '/logging/CLogFilter.php',
  450. 'CLogRoute' => '/logging/CLogRoute.php',
  451. 'CLogRouter' => '/logging/CLogRouter.php',
  452. 'CLogger' => '/logging/CLogger.php',
  453. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  454. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  455. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  456. 'CFileHelper' => '/utils/CFileHelper.php',
  457. 'CFormatter' => '/utils/CFormatter.php',
  458. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  459. 'CPropertyValue' => '/utils/CPropertyValue.php',
  460. 'CTimestamp' => '/utils/CTimestamp.php',
  461. 'CVarDumper' => '/utils/CVarDumper.php',
  462. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  463. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  464. 'CCompareValidator' => '/validators/CCompareValidator.php',
  465. 'CDateValidator' => '/validators/CDateValidator.php',
  466. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  467. 'CEmailValidator' => '/validators/CEmailValidator.php',
  468. 'CExistValidator' => '/validators/CExistValidator.php',
  469. 'CFileValidator' => '/validators/CFileValidator.php',
  470. 'CFilterValidator' => '/validators/CFilterValidator.php',
  471. 'CInlineValidator' => '/validators/CInlineValidator.php',
  472. 'CNumberValidator' => '/validators/CNumberValidator.php',
  473. 'CRangeValidator' => '/validators/CRangeValidator.php',
  474. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  475. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  476. 'CSafeValidator' => '/validators/CSafeValidator.php',
  477. 'CStringValidator' => '/validators/CStringValidator.php',
  478. 'CTypeValidator' => '/validators/CTypeValidator.php',
  479. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  480. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  481. 'CUrlValidator' => '/validators/CUrlValidator.php',
  482. 'CValidator' => '/validators/CValidator.php',
  483. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  484. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  485. 'CAssetManager' => '/web/CAssetManager.php',
  486. 'CBaseController' => '/web/CBaseController.php',
  487. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  488. 'CClientScript' => '/web/CClientScript.php',
  489. 'CController' => '/web/CController.php',
  490. 'CDataProvider' => '/web/CDataProvider.php',
  491. 'CDataProviderIterator' => '/web/CDataProviderIterator.php',
  492. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  493. 'CExtController' => '/web/CExtController.php',
  494. 'CFormModel' => '/web/CFormModel.php',
  495. 'CHttpCookie' => '/web/CHttpCookie.php',
  496. 'CHttpRequest' => '/web/CHttpRequest.php',
  497. 'CHttpSession' => '/web/CHttpSession.php',
  498. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  499. 'COutputEvent' => '/web/COutputEvent.php',
  500. 'CPagination' => '/web/CPagination.php',
  501. 'CSort' => '/web/CSort.php',
  502. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  503. 'CTheme' => '/web/CTheme.php',
  504. 'CThemeManager' => '/web/CThemeManager.php',
  505. 'CUploadedFile' => '/web/CUploadedFile.php',
  506. 'CUrlManager' => '/web/CUrlManager.php',
  507. 'CWebApplication' => '/web/CWebApplication.php',
  508. 'CWebModule' => '/web/CWebModule.php',
  509. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  510. 'CAction' => '/web/actions/CAction.php',
  511. 'CInlineAction' => '/web/actions/CInlineAction.php',
  512. 'CViewAction' => '/web/actions/CViewAction.php',
  513. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  514. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  515. 'CAuthItem' => '/web/auth/CAuthItem.php',
  516. 'CAuthManager' => '/web/auth/CAuthManager.php',
  517. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  518. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  519. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  520. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  521. 'CWebUser' => '/web/auth/CWebUser.php',
  522. 'CFilter' => '/web/filters/CFilter.php',
  523. 'CFilterChain' => '/web/filters/CFilterChain.php',
  524. 'CHttpCacheFilter' => '/web/filters/CHttpCacheFilter.php',
  525. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  526. 'CForm' => '/web/form/CForm.php',
  527. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  528. 'CFormElement' => '/web/form/CFormElement.php',
  529. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  530. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  531. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  532. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  533. 'CHtml' => '/web/helpers/CHtml.php',
  534. 'CJSON' => '/web/helpers/CJSON.php',
  535. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  536. 'CJavaScriptExpression' => '/web/helpers/CJavaScriptExpression.php',
  537. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  538. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  539. 'CWebService' => '/web/services/CWebService.php',
  540. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  541. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  542. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  543. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  544. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  545. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  546. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  547. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  548. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  549. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  550. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  551. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  552. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  553. 'COutputCache' => '/web/widgets/COutputCache.php',
  554. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  555. 'CStarRating' => '/web/widgets/CStarRating.php',
  556. 'CTabView' => '/web/widgets/CTabView.php',
  557. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  558. 'CTreeView' => '/web/widgets/CTreeView.php',
  559. 'CWidget' => '/web/widgets/CWidget.php',
  560. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  561. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  562. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  563. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  564. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  565. );
  566. }
  567. spl_autoload_register(array('YiiBase','autoload'));
  568. class Yii extends YiiBase
  569. {
  570. }
  571. class CComponent
  572. {
  573. private $_e;
  574. private $_m;
  575. public function __get($name)
  576. {
  577. $getter='get'.$name;
  578. if(method_exists($this,$getter))
  579. return $this->$getter();
  580. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  581. {
  582. // duplicating getEventHandlers() here for performance
  583. $name=strtolower($name);
  584. if(!isset($this->_e[$name]))
  585. $this->_e[$name]=new CList;
  586. return $this->_e[$name];
  587. }
  588. elseif(isset($this->_m[$name]))
  589. return $this->_m[$name];
  590. elseif(is_array($this->_m))
  591. {
  592. foreach($this->_m as $object)
  593. {
  594. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  595. return $object->$name;
  596. }
  597. }
  598. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  599. array('{class}'=>get_class($this), '{property}'=>$name)));
  600. }
  601. public function __set($name,$value)
  602. {
  603. $setter='set'.$name;
  604. if(method_exists($this,$setter))
  605. return $this->$setter($value);
  606. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  607. {
  608. // duplicating getEventHandlers() here for performance
  609. $name=strtolower($name);
  610. if(!isset($this->_e[$name]))
  611. $this->_e[$name]=new CList;
  612. return $this->_e[$name]->add($value);
  613. }
  614. elseif(is_array($this->_m))
  615. {
  616. foreach($this->_m as $object)
  617. {
  618. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  619. return $object->$name=$value;
  620. }
  621. }
  622. if(method_exists($this,'get'.$name))
  623. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  624. array('{class}'=>get_class($this), '{property}'=>$name)));
  625. else
  626. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  627. array('{class}'=>get_class($this), '{property}'=>$name)));
  628. }
  629. public function __isset($name)
  630. {
  631. $getter='get'.$name;
  632. if(method_exists($this,$getter))
  633. return $this->$getter()!==null;
  634. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  635. {
  636. $name=strtolower($name);
  637. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  638. }
  639. elseif(is_array($this->_m))
  640. {
  641. if(isset($this->_m[$name]))
  642. return true;
  643. foreach($this->_m as $object)
  644. {
  645. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  646. return $object->$name!==null;
  647. }
  648. }
  649. return false;
  650. }
  651. public function __unset($name)
  652. {
  653. $setter='set'.$name;
  654. if(method_exists($this,$setter))
  655. $this->$setter(null);
  656. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  657. unset($this->_e[strtolower($name)]);
  658. elseif(is_array($this->_m))
  659. {
  660. if(isset($this->_m[$name]))
  661. $this->detachBehavior($name);
  662. else
  663. {
  664. foreach($this->_m as $object)
  665. {
  666. if($object->getEnabled())
  667. {
  668. if(property_exists($object,$name))
  669. return $object->$name=null;
  670. elseif($object->canSetProperty($name))
  671. return $object->$setter(null);
  672. }
  673. }
  674. }
  675. }
  676. elseif(method_exists($this,'get'.$name))
  677. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  678. array('{class}'=>get_class($this), '{property}'=>$name)));
  679. }
  680. public function __call($name,$parameters)
  681. {
  682. if($this->_m!==null)
  683. {
  684. foreach($this->_m as $object)
  685. {
  686. if($object->getEnabled() && method_exists($object,$name))
  687. return call_user_func_array(array($object,$name),$parameters);
  688. }
  689. }
  690. if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)
  691. return call_user_func_array($this->$name, $parameters);
  692. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  693. array('{class}'=>get_class($this), '{name}'=>$name)));
  694. }
  695. public function asa($behavior)
  696. {
  697. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  698. }
  699. public function attachBehaviors($behaviors)
  700. {
  701. foreach($behaviors as $name=>$behavior)
  702. $this->attachBehavior($name,$behavior);
  703. }
  704. public function detachBehaviors()
  705. {
  706. if($this->_m!==null)
  707. {
  708. foreach($this->_m as $name=>$behavior)
  709. $this->detachBehavior($name);
  710. $this->_m=null;
  711. }
  712. }
  713. public function attachBehavior($name,$behavior)
  714. {
  715. if(!($behavior instanceof IBehavior))
  716. $behavior=Yii::createComponent($behavior);
  717. $behavior->setEnabled(true);
  718. $behavior->attach($this);
  719. return $this->_m[$name]=$behavior;
  720. }
  721. public function detachBehavior($name)
  722. {
  723. if(isset($this->_m[$name]))
  724. {
  725. $this->_m[$name]->detach($this);
  726. $behavior=$this->_m[$name];
  727. unset($this->_m[$name]);
  728. return $behavior;
  729. }
  730. }
  731. public function enableBehaviors()
  732. {
  733. if($this->_m!==null)
  734. {
  735. foreach($this->_m as $behavior)
  736. $behavior->setEnabled(true);
  737. }
  738. }
  739. public function disableBehaviors()
  740. {
  741. if($this->_m!==null)
  742. {
  743. foreach($this->_m as $behavior)
  744. $behavior->setEnabled(false);
  745. }
  746. }
  747. public function enableBehavior($name)
  748. {
  749. if(isset($this->_m[$name]))
  750. $this->_m[$name]->setEnabled(true);
  751. }
  752. public function disableBehavior($name)
  753. {
  754. if(isset($this->_m[$name]))
  755. $this->_m[$name]->setEnabled(false);
  756. }
  757. public function hasProperty($name)
  758. {
  759. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  760. }
  761. public function canGetProperty($name)
  762. {
  763. return method_exists($this,'get'.$name);
  764. }
  765. public function canSetProperty($name)
  766. {
  767. return method_exists($this,'set'.$name);
  768. }
  769. public function hasEvent($name)
  770. {
  771. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  772. }
  773. public function hasEventHandler($name)
  774. {
  775. $name=strtolower($name);
  776. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  777. }
  778. public function getEventHandlers($name)
  779. {
  780. if($this->hasEvent($name))
  781. {
  782. $name=strtolower($name);
  783. if(!isset($this->_e[$name]))
  784. $this->_e[$name]=new CList;
  785. return $this->_e[$name];
  786. }
  787. else
  788. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  789. array('{class}'=>get_class($this), '{event}'=>$name)));
  790. }
  791. public function attachEventHandler($name,$handler)
  792. {
  793. $this->getEventHandlers($name)->add($handler);
  794. }
  795. public function detachEventHandler($name,$handler)
  796. {
  797. if($this->hasEventHandler($name))
  798. return $this->getEventHandlers($name)->remove($handler)!==false;
  799. else
  800. return false;
  801. }
  802. public function raiseEvent($name,$event)
  803. {
  804. $name=strtolower($name);
  805. if(isset($this->_e[$name]))
  806. {
  807. foreach($this->_e[$name] as $handler)
  808. {
  809. if(is_string($handler))
  810. call_user_func($handler,$event);
  811. elseif(is_callable($handler,true))
  812. {
  813. if(is_array($handler))
  814. {
  815. // an array: 0 - object, 1 - method name
  816. list($object,$method)=$handler;
  817. if(is_string($object)) // static method call
  818. call_user_func($handler,$event);
  819. elseif(method_exists($object,$method))
  820. $object->$method($event);
  821. else
  822. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  823. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  824. }
  825. else // PHP 5.3: anonymous function
  826. call_user_func($handler,$event);
  827. }
  828. else
  829. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  830. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  831. // stop further handling if param.handled is set true
  832. if(($event instanceof CEvent) && $event->handled)
  833. return;
  834. }
  835. }
  836. elseif(YII_DEBUG && !$this->hasEvent($name))
  837. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  838. array('{class}'=>get_class($this), '{event}'=>$name)));
  839. }
  840. public function evaluateExpression($_expression_,$_data_=array())
  841. {
  842. if(is_string($_expression_))
  843. {
  844. extract($_data_);
  845. return eval('return '.$_expression_.';');
  846. }
  847. else
  848. {
  849. $_data_[]=$this;
  850. return call_user_func_array($_expression_, $_data_);
  851. }
  852. }
  853. }
  854. class CEvent extends CComponent
  855. {
  856. public $sender;
  857. public $handled=false;
  858. public $params;
  859. public function __construct($sender=null,$params=null)
  860. {
  861. $this->sender=$sender;
  862. $this->params=$params;
  863. }
  864. }
  865. class CEnumerable
  866. {
  867. }
  868. abstract class CModule extends CComponent
  869. {
  870. public $preload=array();
  871. public $behaviors=array();
  872. private $_id;
  873. private $_parentModule;
  874. private $_basePath;
  875. private $_modulePath;
  876. private $_params;
  877. private $_modules=array();
  878. private $_moduleConfig=array();
  879. private $_components=array();
  880. private $_componentConfig=array();
  881. public function __construct($id,$parent,$config=null)
  882. {
  883. $this->_id=$id;
  884. $this->_parentModule=$parent;
  885. // set basePath at early as possible to avoid trouble
  886. if(is_string($config))
  887. $config=require($config);
  888. if(isset($config['basePath']))
  889. {
  890. $this->setBasePath($config['basePath']);
  891. unset($config['basePath']);
  892. }
  893. Yii::setPathOfAlias($id,$this->getBasePath());
  894. $this->preinit();
  895. $this->configure($config);
  896. $this->attachBehaviors($this->behaviors);
  897. $this->preloadComponents();
  898. $this->init();
  899. }
  900. public function __get($name)
  901. {
  902. if($this->hasComponent($name))
  903. return $this->getComponent($name);
  904. else
  905. return parent::__get($name);
  906. }
  907. public function __isset($name)
  908. {
  909. if($this->hasComponent($name))
  910. return $this->getComponent($name)!==null;
  911. else
  912. return parent::__isset($name);
  913. }
  914. public function getId()
  915. {
  916. return $this->_id;
  917. }
  918. public function setId($id)
  919. {
  920. $this->_id=$id;
  921. }
  922. public function getBasePath()
  923. {
  924. if($this->_basePath===null)
  925. {
  926. $class=new ReflectionClass(get_class($this));
  927. $this->_basePath=dirname($class->getFileName());
  928. }
  929. return $this->_basePath;
  930. }
  931. public function setBasePath($path)
  932. {
  933. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  934. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  935. array('{path}'=>$path)));
  936. }
  937. public function getParams()
  938. {
  939. if($this->_params!==null)
  940. return $this->_params;
  941. else
  942. {
  943. $this->_params=new CAttributeCollection;
  944. $this->_params->caseSensitive=true;
  945. return $this->_params;
  946. }
  947. }
  948. public function setParams($value)
  949. {
  950. $params=$this->getParams();
  951. foreach($value as $k=>$v)
  952. $params->add($k,$v);
  953. }
  954. public function getModulePath()
  955. {
  956. if($this->_modulePath!==null)
  957. return $this->_modulePath;
  958. else
  959. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  960. }
  961. public function setModulePath($value)
  962. {
  963. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  964. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  965. array('{path}'=>$value)));
  966. }
  967. public function setImport($aliases)
  968. {
  969. foreach($aliases as $alias)
  970. Yii::import($alias);
  971. }
  972. public function setAliases($mappings)
  973. {
  974. foreach($mappings as $name=>$alias)
  975. {
  976. if(($path=Yii::getPathOfAlias($alias))!==false)
  977. Yii::setPathOfAlias($name,$path);
  978. else
  979. Yii::setPathOfAlias($name,$alias);
  980. }
  981. }
  982. public function getParentModule()
  983. {
  984. return $this->_parentModule;
  985. }
  986. public function getModule($id)
  987. {
  988. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  989. return $this->_modules[$id];
  990. elseif(isset($this->_moduleConfig[$id]))
  991. {
  992. $config=$this->_moduleConfig[$id];
  993. if(!isset($config['enabled']) || $config['enabled'])
  994. {
  995. $class=$config['class'];
  996. unset($config['class'], $config['enabled']);
  997. if($this===Yii::app())
  998. $module=Yii::createComponent($class,$id,null,$config);
  999. else
  1000. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  1001. return $this->_modules[$id]=$module;
  1002. }
  1003. }
  1004. }
  1005. public function hasModule($id)
  1006. {
  1007. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  1008. }
  1009. public function getModules()
  1010. {
  1011. return $this->_moduleConfig;
  1012. }
  1013. public function setModules($modules)
  1014. {
  1015. foreach($modules as $id=>$module)
  1016. {
  1017. if(is_int($id))
  1018. {
  1019. $id=$module;
  1020. $module=array();
  1021. }
  1022. if(!isset($module['class']))
  1023. {
  1024. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1025. $module['class']=$id.'.'.ucfirst($id).'Module';
  1026. }
  1027. if(isset($this->_moduleConfig[$id]))
  1028. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1029. else
  1030. $this->_moduleConfig[$id]=$module;
  1031. }
  1032. }
  1033. public function hasComponent($id)
  1034. {
  1035. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1036. }
  1037. public function getComponent($id,$createIfNull=true)
  1038. {
  1039. if(isset($this->_components[$id]))
  1040. return $this->_components[$id];
  1041. elseif(isset($this->_componentConfig[$id]) && $createIfNull)
  1042. {
  1043. $config=$this->_componentConfig[$id];
  1044. if(!isset($config['enabled']) || $config['enabled'])
  1045. {
  1046. unset($config['enabled']);
  1047. $component=Yii::createComponent($config);
  1048. $component->init();
  1049. return $this->_components[$id]=$component;
  1050. }
  1051. }
  1052. }
  1053. public function setComponent($id,$component,$merge=true)
  1054. {
  1055. if($component===null)
  1056. {
  1057. unset($this->_components[$id]);
  1058. return;
  1059. }
  1060. elseif($component instanceof IApplicationComponent)
  1061. {
  1062. $this->_components[$id]=$component;
  1063. if(!$component->getIsInitialized())
  1064. $component->init();
  1065. return;
  1066. }
  1067. elseif(isset($this->_components[$id]))
  1068. {
  1069. if(isset($component['class']) && get_class($this->_components[$id])!==$component['class'])
  1070. {
  1071. unset($this->_components[$id]);
  1072. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1073. return;
  1074. }
  1075. foreach($component as $key=>$value)
  1076. {
  1077. if($key!=='class')
  1078. $this->_components[$id]->$key=$value;
  1079. }
  1080. }
  1081. elseif(isset($this->_componentConfig[$id]['class'],$component['class'])
  1082. && $this->_componentConfig[$id]['class']!==$component['class'])
  1083. {
  1084. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1085. return;
  1086. }
  1087. if(isset($this->_componentConfig[$id]) && $merge)
  1088. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1089. else
  1090. $this->_componentConfig[$id]=$component;
  1091. }
  1092. public function getComponents($loadedOnly=true)
  1093. {
  1094. if($loadedOnly)
  1095. return $this->_components;
  1096. else
  1097. return array_merge($this->_componentConfig, $this->_components);
  1098. }
  1099. public function setComponents($components,$merge=true)
  1100. {
  1101. foreach($components as $id=>$component)
  1102. $this->setComponent($id,$component,$merge);
  1103. }
  1104. public function configure($config)
  1105. {
  1106. if(is_array($config))
  1107. {
  1108. foreach($config as $key=>$value)
  1109. $this->$key=$value;
  1110. }
  1111. }
  1112. protected function preloadComponents()
  1113. {
  1114. foreach($this->preload as $id)
  1115. $this->getComponent($id);
  1116. }
  1117. protected function preinit()
  1118. {
  1119. }
  1120. protected function init()
  1121. {
  1122. }
  1123. }
  1124. abstract class CApplication extends CModule
  1125. {
  1126. public $name='My Application';
  1127. public $charset='UTF-8';
  1128. public $sourceLanguage='en_us';
  1129. private $_id;
  1130. private $_basePath;
  1131. private $_runtimePath;
  1132. private $_extensionPath;
  1133. private $_globalState;
  1134. private $_stateChanged;
  1135. private $_ended=false;
  1136. private $_language;
  1137. private $_homeUrl;
  1138. abstract public function processRequest();
  1139. public function __construct($config=null)
  1140. {
  1141. Yii::setApplication($this);
  1142. // set basePath at early as possible to avoid trouble
  1143. if(is_string($config))
  1144. $config=require($config);
  1145. if(isset($config['basePath']))
  1146. {
  1147. $this->setBasePath($config['basePath']);
  1148. unset($config['basePath']);
  1149. }
  1150. else
  1151. $this->setBasePath('protected');
  1152. Yii::setPathOfAlias('application',$this->getBasePath());
  1153. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1154. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1155. $this->preinit();
  1156. $this->initSystemHandlers();
  1157. $this->registerCoreComponents();
  1158. $this->configure($config);
  1159. $this->attachBehaviors($this->behaviors);
  1160. $this->preloadComponents();
  1161. $this->init();
  1162. }
  1163. public function run()
  1164. {
  1165. if($this->hasEventHandler('onBeginRequest'))
  1166. $this->onBeginRequest(new CEvent($this));
  1167. register_shutdown_function(array($this,'end'),0,false);
  1168. $this->processRequest();
  1169. if($this->hasEventHandler('onEndRequest'))
  1170. $this->onEndRequest(new CEvent($this));
  1171. }
  1172. public function end($status=0,$exit=true)
  1173. {
  1174. if($this->hasEventHandler('onEndRequest'))
  1175. $this->onEndRequest(new CEvent($this));
  1176. if($exit)
  1177. exit($status);
  1178. }
  1179. public function onBeginRequest($event)
  1180. {
  1181. $this->raiseEvent('onBeginRequest',$event);
  1182. }
  1183. public function onEndRequest($event)
  1184. {
  1185. if(!$this->_ended)
  1186. {
  1187. $this->_ended=true;
  1188. $this->raiseEvent('onEndRequest',$event);
  1189. }
  1190. }
  1191. public function getId()
  1192. {
  1193. if($this->_id!==null)
  1194. return $this->_id;
  1195. else
  1196. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1197. }
  1198. public function setId($id)
  1199. {
  1200. $this->_id=$id;
  1201. }
  1202. public function getBasePath()
  1203. {
  1204. return $this->_basePath;
  1205. }
  1206. public function setBasePath($path)
  1207. {
  1208. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1209. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1210. array('{path}'=>$path)));
  1211. }
  1212. public function getRuntimePath()
  1213. {
  1214. if($this->_runtimePath!==null)
  1215. return $this->_runtimePath;
  1216. else
  1217. {
  1218. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1219. return $this->_runtimePath;
  1220. }
  1221. }
  1222. public function setRuntimePath($path)
  1223. {
  1224. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1225. 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.',
  1226. array('{path}'=>$path)));
  1227. $this->_runtimePath=$runtimePath;
  1228. }
  1229. public function getExtensionPath()
  1230. {
  1231. return Yii::getPathOfAlias('ext');
  1232. }
  1233. public function setExtensionPath($path)
  1234. {
  1235. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1236. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1237. array('{path}'=>$path)));
  1238. Yii::setPathOfAlias('ext',$extensionPath);
  1239. }
  1240. public function getLanguage()
  1241. {
  1242. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1243. }
  1244. public function setLanguage($language)
  1245. {
  1246. $this->_language=$language;
  1247. }
  1248. public function getTimeZone()
  1249. {
  1250. return date_default_timezone_get();
  1251. }
  1252. public function setTimeZone($value)
  1253. {
  1254. date_default_timezone_set($value);
  1255. }
  1256. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1257. {
  1258. if($srcLanguage===null)
  1259. $srcLanguage=$this->sourceLanguage;
  1260. if($language===null)
  1261. $language=$this->getLanguage();
  1262. if($language===$srcLanguage)
  1263. return $srcFile;
  1264. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1265. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1266. }
  1267. public function getLocale($localeID=null)
  1268. {
  1269. return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID);
  1270. }
  1271. public function getLocaleDataPath()
  1272. {
  1273. return CLocale::$dataPath===null ? Yii::getPathOfAlias('system.i18n.data') : CLocale::$dataPath;
  1274. }
  1275. public function setLocaleDataPath($value)
  1276. {
  1277. CLocale::$dataPath=$value;
  1278. }
  1279. public function getNumberFormatter()
  1280. {
  1281. return $this->getLocale()->getNumberFormatter();
  1282. }
  1283. public function getDateFormatter()
  1284. {
  1285. return $this->getLocale()->getDateFormatter();
  1286. }
  1287. public function getDb()
  1288. {
  1289. return $this->getComponent('db');
  1290. }
  1291. public function getErrorHandler()
  1292. {
  1293. return $this->getComponent('errorHandler');
  1294. }
  1295. public function getSecurityManager()
  1296. {
  1297. return $this->getComponent('securityManager');
  1298. }
  1299. public function getStatePersister()
  1300. {
  1301. return $this->getComponent('statePersister');
  1302. }
  1303. public function getCache()
  1304. {
  1305. return $this->getComponent('cache');
  1306. }
  1307. public function getCoreMessages()
  1308. {
  1309. return $this->getComponent('coreMessages');
  1310. }
  1311. public function getMessages()
  1312. {
  1313. return $this->getComponent('messages');
  1314. }
  1315. public function getRequest()
  1316. {
  1317. return $this->getComponent('request');
  1318. }
  1319. public function getUrlManager()
  1320. {
  1321. return $this->getComponent('urlManager');
  1322. }
  1323. public function getController()
  1324. {
  1325. return null;
  1326. }
  1327. public function createUrl($route,$params=array(),$ampersand='&')
  1328. {
  1329. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1330. }
  1331. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1332. {
  1333. $url=$this->createUrl($route,$params,$ampersand);
  1334. if(strpos($url,'http')===0)
  1335. return $url;
  1336. else
  1337. return $this->getRequest()->getHostInfo($schema).$url;
  1338. }
  1339. public function getBaseUrl($absolute=false)
  1340. {
  1341. return $this->getRequest()->getBaseUrl($absolute);
  1342. }
  1343. public function getHomeUrl()
  1344. {
  1345. if($this->_homeUrl===null)
  1346. {
  1347. if($this->getUrlManager()->showScriptName)
  1348. return $this->getRequest()->getScriptUrl();
  1349. else
  1350. return $this->getRequest()->getBaseUrl().'/';
  1351. }
  1352. else
  1353. return $this->_homeUrl;
  1354. }
  1355. public function setHomeUrl($value)
  1356. {
  1357. $this->_homeUrl=$value;
  1358. }
  1359. public function getGlobalState($key,$defaultValue=null)
  1360. {
  1361. if($this->_globalState===null)
  1362. $this->loadGlobalState();
  1363. if(isset($this->_globalState[$key]))
  1364. return $this->_globalState[$key];
  1365. else
  1366. return $defaultValue;
  1367. }
  1368. public function setGlobalState($key,$value,$defaultValue=null)
  1369. {
  1370. if($this->_globalState===null)
  1371. $this->loadGlobalState();
  1372. $changed=$this->_stateChanged;
  1373. if($value===$defaultValue)
  1374. {
  1375. if(isset($this->_globalState[$key]))
  1376. {
  1377. unset($this->_globalState[$key]);
  1378. $this->_stateChanged=true;
  1379. }
  1380. }
  1381. elseif(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1382. {
  1383. $this->_globalState[$key]=$value;
  1384. $this->_stateChanged=true;
  1385. }
  1386. if($this->_stateChanged!==$changed)
  1387. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1388. }
  1389. public function clearGlobalState($key)
  1390. {
  1391. $this->setGlobalState($key,true,true);
  1392. }
  1393. public function loadGlobalState()
  1394. {
  1395. $persister=$this->getStatePersister();
  1396. if(($this->_globalState=$persister->load())===null)
  1397. $this->_globalState=array();
  1398. $this->_stateChanged=false;
  1399. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1400. }
  1401. public function saveGlobalState()
  1402. {
  1403. if($this->_stateChanged)
  1404. {
  1405. $this->_stateChanged=false;
  1406. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1407. $this->getStatePersister()->save($this->_globalState);
  1408. }
  1409. }
  1410. public function handleException($exception)
  1411. {
  1412. // disable error capturing to avoid recursive errors
  1413. restore_error_handler();
  1414. restore_exception_handler();
  1415. $category='exception.'.get_class($exception);
  1416. if($exception instanceof CHttpException)
  1417. $category.='.'.$exception->statusCode;
  1418. // php <5.2 doesn't support string conversion auto-magically
  1419. $message=$exception->__toString();
  1420. if(isset($_SERVER['REQUEST_URI']))
  1421. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  1422. if(isset($_SERVER['HTTP_REFERER']))
  1423. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  1424. $message.="\n---";
  1425. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1426. try
  1427. {
  1428. $event=new CExceptionEvent($this,$exception);
  1429. $this->onException($event);
  1430. if(!$event->handled)
  1431. {
  1432. // try an error handler
  1433. if(($handler=$this->getErrorHandler())!==null)
  1434. $handler->handle($event);
  1435. else
  1436. $this->displayException($exception);
  1437. }
  1438. }
  1439. catch(Exception $e)
  1440. {
  1441. $this->displayException($e);
  1442. }
  1443. try
  1444. {
  1445. $this->end(1);
  1446. }
  1447. catch(Exception $e)
  1448. {
  1449. // use the most primitive way to log error
  1450. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1451. $msg .= $e->getTraceAsString()."\n";
  1452. $msg .= "Previous exception:\n";
  1453. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1454. $msg .= $exception->getTraceAsString()."\n";
  1455. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1456. error_log($msg);
  1457. exit(1);
  1458. }
  1459. }
  1460. public function handleError($code,$message,$file,$line)
  1461. {
  1462. if($code & error_reporting())
  1463. {
  1464. // disable error capturing to avoid recursive errors
  1465. restore_error_handler();
  1466. restore_exception_handler();
  1467. $log="$message ($file:$line)\nStack trace:\n";
  1468. $trace=debug_backtrace();
  1469. // skip the first 3 stacks as they do not tell the error position
  1470. if(count($trace)>3)
  1471. $trace=array_slice($trace,3);
  1472. foreach($trace as $i=>$t)
  1473. {
  1474. if(!isset($t['file']))
  1475. $t['file']='unknown';
  1476. if(!isset($t['line']))
  1477. $t['line']=0;
  1478. if(!isset($t['function']))
  1479. $t['function']='unknown';
  1480. $log.="#$i {$t['file']}({$t['line']}): ";
  1481. if(isset($t['object']) && is_object($t['object']))
  1482. $log.=get_class($t['object']).'->';
  1483. $log.="{$t['function']}()\n";
  1484. }
  1485. if(isset($_SERVER['REQUEST_URI']))
  1486. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1487. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1488. try
  1489. {
  1490. Yii::import('CErrorEvent',true);
  1491. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1492. $this->onError($event);
  1493. if(!$event->handled)
  1494. {
  1495. // try an error handler
  1496. if(($handler=$this->getErrorHandler())!==null)
  1497. $handler->handle($event);
  1498. else
  1499. $this->displayError($code,$message,$file,$line);
  1500. }
  1501. }
  1502. catch(Exception $e)
  1503. {
  1504. $this->displayException($e);
  1505. }
  1506. try
  1507. {
  1508. $this->end(1);
  1509. }
  1510. catch(Exception $e)
  1511. {
  1512. // use the most primitive way to log error
  1513. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1514. $msg .= $e->getTraceAsString()."\n";
  1515. $msg .= "Previous error:\n";
  1516. $msg .= $log."\n";
  1517. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1518. error_log($msg);
  1519. exit(1);
  1520. }
  1521. }
  1522. }
  1523. public function onException($event)
  1524. {
  1525. $this->raiseEvent('onException',$event);
  1526. }
  1527. public function onError($event)
  1528. {
  1529. $this->raiseEvent('onError',$event);
  1530. }
  1531. public function displayError($code,$message,$file,$line)
  1532. {
  1533. if(YII_DEBUG)
  1534. {
  1535. echo "<h1>PHP Error [$code]</h1>\n";
  1536. echo "<p>$message ($file:$line)</p>\n";
  1537. echo '<pre>';
  1538. $trace=debug_backtrace();
  1539. // skip the first 3 stacks as they do not tell the error position
  1540. if(count($trace)>3)
  1541. $trace=array_slice($trace,3);
  1542. foreach($trace as $i=>$t)
  1543. {
  1544. if(!isset($t['file']))
  1545. $t['file']='unknown';
  1546. if(!isset($t['line']))
  1547. $t['line']=0;
  1548. if(!isset($t['function']))
  1549. $t['function']='unknown';
  1550. echo "#$i {$t['file']}({$t['line']}): ";
  1551. if(isset($t['object']) && is_object($t['object']))
  1552. echo get_class($t['object']).'->';
  1553. echo "{$t['function']}()\n";
  1554. }
  1555. echo '</pre>';
  1556. }
  1557. else
  1558. {
  1559. echo "<h1>PHP Error [$code]</h1>\n";
  1560. echo "<p>$message</p>\n";
  1561. }
  1562. }
  1563. public function displayException($exception)
  1564. {
  1565. if(YII_DEBUG)
  1566. {
  1567. echo '<h1>'.get_class($exception)."</h1>\n";
  1568. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1569. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1570. }
  1571. else
  1572. {
  1573. echo '<h1>'.get_class($exception)."</h1>\n";
  1574. echo '<p>'.$exception->getMessage().'</p>';
  1575. }
  1576. }
  1577. protected function initSystemHandlers()
  1578. {
  1579. if(YII_ENABLE_EXCEPTION_HANDLER)
  1580. set_exception_handler(array($this,'handleException'));
  1581. if(YII_ENABLE_ERROR_HANDLER)
  1582. set_error_handler(array($this,'handleError'),error_reporting());
  1583. }
  1584. protected function registerCoreComponents()
  1585. {
  1586. $components=array(
  1587. 'coreMessages'=>array(
  1588. 'class'=>'CPhpMessageSource',
  1589. 'language'=>'en_us',
  1590. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1591. ),
  1592. 'db'=>array(
  1593. 'class'=>'CDbConnection',
  1594. ),
  1595. 'messages'=>array(
  1596. 'class'=>'CPhpMessageSource',
  1597. ),
  1598. 'errorHandler'=>array(
  1599. 'class'=>'CErrorHandler',
  1600. ),
  1601. 'securityManager'=>array(
  1602. 'class'=>'CSecurityManager',
  1603. ),
  1604. 'statePersister'=>array(
  1605. 'class'=>'CStatePersister',
  1606. ),
  1607. 'urlManager'=>array(
  1608. 'class'=>'CUrlManager',
  1609. ),
  1610. 'request'=>array(
  1611. 'class'=>'CHttpRequest',
  1612. ),
  1613. 'format'=>array(
  1614. 'class'=>'CFormatter',
  1615. ),
  1616. );
  1617. $this->setComponents($components);
  1618. }
  1619. }
  1620. class CWebApplication extends CApplication
  1621. {
  1622. public $defaultController='site';
  1623. public $layout='main';
  1624. public $controllerMap=array();
  1625. public $catchAllRequest;
  1626. public $controllerNamespace;
  1627. private $_controllerPath;
  1628. private $_viewPath;
  1629. private $_systemViewPath;
  1630. private $_layoutPath;
  1631. private $_controller;
  1632. private $_theme;
  1633. public function processRequest()
  1634. {
  1635. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1636. {
  1637. $route=$this->catchAllRequest[0];
  1638. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1639. $_GET[$name]=$value;
  1640. }
  1641. else
  1642. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1643. $this->runController($route);
  1644. }
  1645. protected function registerCoreComponents()
  1646. {
  1647. parent::registerCoreComponents();
  1648. $components=array(
  1649. 'session'=>array(
  1650. 'class'=>'CHttpSession',
  1651. ),
  1652. 'assetManager'=>array(
  1653. 'class'=>'CAssetManager',
  1654. ),
  1655. 'user'=>array(
  1656. 'class'=>'CWebUser',
  1657. ),
  1658. 'themeManager'=>array(
  1659. 'class'=>'CThemeManager',
  1660. ),
  1661. 'authManager'=>array(
  1662. 'class'=>'CPhpAuthManager',
  1663. ),
  1664. 'clientScript'=>array(
  1665. 'class'=>'CClientScript',
  1666. ),
  1667. 'widgetFactory'=>array(
  1668. 'class'=>'CWidgetFactory',
  1669. ),
  1670. );
  1671. $this->setComponents($components);
  1672. }
  1673. public function getAuthManager()
  1674. {
  1675. return $this->getComponent('authManager');
  1676. }
  1677. public function getAssetManager()
  1678. {
  1679. return $this->getComponent('assetManager');
  1680. }
  1681. public function getSession()
  1682. {
  1683. return $this->getComponent('session');
  1684. }
  1685. public function getUser()
  1686. {
  1687. return $this->getComponent('user');
  1688. }
  1689. public function getViewRenderer()
  1690. {
  1691. return $this->getComponent('viewRenderer');
  1692. }
  1693. public function getClientScript()
  1694. {
  1695. return $this->getComponent('clientScript');
  1696. }
  1697. public function getWidgetFactory()
  1698. {
  1699. return $this->getComponent('widgetFactory');
  1700. }
  1701. public function getThemeManager()
  1702. {
  1703. return $this->getComponent('themeManager');
  1704. }
  1705. public function getTheme()
  1706. {
  1707. if(is_string($this->_theme))
  1708. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1709. return $this->_theme;
  1710. }
  1711. public function setTheme($value)
  1712. {
  1713. $this->_theme=$value;
  1714. }
  1715. public function runController($route)
  1716. {
  1717. if(($ca=$this->createController($route))!==null)
  1718. {
  1719. list($controller,$actionID)=$ca;
  1720. $oldController=$this->_controller;
  1721. $this->_controller=$controller;
  1722. $controller->init();
  1723. $controller->run($actionID);
  1724. $this->_controller=$oldController;
  1725. }
  1726. else
  1727. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1728. array('{route}'=>$route===''?$this->defaultController:$route)));
  1729. }
  1730. public function createController($route,$owner=null)
  1731. {
  1732. if($owner===null)
  1733. $owner=$this;
  1734. if(($route=trim($route,'/'))==='')
  1735. $route=$owner->defaultController;
  1736. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1737. $route.='/';
  1738. while(($pos=strpos($route,'/'))!==false)
  1739. {
  1740. $id=substr($route,0,$pos);
  1741. if(!preg_match('/^\w+$/',$id))
  1742. return null;
  1743. if(!$caseSensitive)
  1744. $id=strtolower($id);
  1745. $route=(string)substr($route,$pos+1);
  1746. if(!isset($basePath)) // first segment
  1747. {
  1748. if(isset($owner->controllerMap[$id]))
  1749. {
  1750. return array(
  1751. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1752. $this->parseActionParams($route),
  1753. );
  1754. }
  1755. if(($module=$owner->getModule($id))!==null)
  1756. return $this->createController($route,$module);
  1757. $basePath=$owner->getControllerPath();
  1758. $controllerID='';
  1759. }
  1760. else
  1761. $controllerID.='/';
  1762. $className=ucfirst($id).'Controller';
  1763. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1764. if($owner->controllerNamespace!==null)
  1765. $className=$owner->controllerNamespace.'\\'.$className;
  1766. if(is_file($classFile))
  1767. {
  1768. if(!class_exists($className,false))
  1769. require($classFile);
  1770. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1771. {
  1772. $id[0]=strtolower($id[0]);
  1773. return array(
  1774. new $className($controllerID.$id,$owner===$this?null:$owner),
  1775. $this->parseActionParams($route),
  1776. );
  1777. }
  1778. return null;
  1779. }
  1780. $controllerID.=$id;
  1781. $basePath.=DIRECTORY_SEPARATOR.$id;
  1782. }
  1783. }
  1784. protected function parseActionParams($pathInfo)
  1785. {
  1786. if(($pos=strpos($pathInfo,'/'))!==false)
  1787. {
  1788. $manager=$this->getUrlManager();
  1789. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1790. $actionID=substr($pathInfo,0,$pos);
  1791. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1792. }
  1793. else
  1794. return $pathInfo;
  1795. }
  1796. public function getController()
  1797. {
  1798. return $this->_controller;
  1799. }
  1800. public function setController($value)
  1801. {
  1802. $this->_controller=$value;
  1803. }
  1804. public function getControllerPath()
  1805. {
  1806. if($this->_controllerPath!==null)
  1807. return $this->_controllerPath;
  1808. else
  1809. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1810. }
  1811. public function setControllerPath($value)
  1812. {
  1813. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1814. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1815. array('{path}'=>$value)));
  1816. }
  1817. public function getViewPath()
  1818. {
  1819. if($this->_viewPath!==null)
  1820. return $this->_viewPath;
  1821. else
  1822. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1823. }
  1824. public function setViewPath($path)
  1825. {
  1826. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1827. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1828. array('{path}'=>$path)));
  1829. }
  1830. public function getSystemViewPath()
  1831. {
  1832. if($this->_systemViewPath!==null)
  1833. return $this->_systemViewPath;
  1834. else
  1835. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1836. }
  1837. public function setSystemViewPath($path)
  1838. {
  1839. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1840. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1841. array('{path}'=>$path)));
  1842. }
  1843. public function getLayoutPath()
  1844. {
  1845. if($this->_layoutPath!==null)
  1846. return $this->_layoutPath;
  1847. else
  1848. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1849. }
  1850. public function setLayoutPath($path)
  1851. {
  1852. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1853. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1854. array('{path}'=>$path)));
  1855. }
  1856. public function beforeControllerAction($controller,$action)
  1857. {
  1858. return true;
  1859. }
  1860. public function afterControllerAction($controller,$action)
  1861. {
  1862. }
  1863. public function findModule($id)
  1864. {
  1865. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1866. {
  1867. do
  1868. {
  1869. if(($m=$module->getModule($id))!==null)
  1870. return $m;
  1871. } while(($module=$module->getParentModule())!==null);
  1872. }
  1873. if(($m=$this->getModule($id))!==null)
  1874. return $m;
  1875. }
  1876. protected function init()
  1877. {
  1878. parent::init();
  1879. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1880. $this->getRequest();
  1881. }
  1882. }
  1883. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1884. {
  1885. private $_d=array();
  1886. private $_r=false;
  1887. public function __construct($data=null,$readOnly=false)
  1888. {
  1889. if($data!==null)
  1890. $this->copyFrom($data);
  1891. $this->setReadOnly($readOnly);
  1892. }
  1893. public function getReadOnly()
  1894. {
  1895. return $this->_r;
  1896. }
  1897. protected function setReadOnly($value)
  1898. {
  1899. $this->_r=$value;
  1900. }
  1901. public function getIterator()
  1902. {
  1903. return new CMapIterator($this->_d);
  1904. }
  1905. public function count()
  1906. {
  1907. return $this->getCount();
  1908. }
  1909. public function getCount()
  1910. {
  1911. return count($this->_d);
  1912. }
  1913. public function getKeys()
  1914. {
  1915. return array_keys($this->_d);
  1916. }
  1917. public function itemAt($key)
  1918. {
  1919. if(isset($this->_d[$key]))
  1920. return $this->_d[$key];
  1921. else
  1922. return null;
  1923. }
  1924. public function add($key,$value)
  1925. {
  1926. if(!$this->_r)
  1927. {
  1928. if($key===null)
  1929. $this->_d[]=$value;
  1930. else
  1931. $this->_d[$key]=$value;
  1932. }
  1933. else
  1934. throw new CException(Yii::t('yii','The map is read only.'));
  1935. }
  1936. public function remove($key)
  1937. {
  1938. if(!$this->_r)
  1939. {
  1940. if(isset($this->_d[$key]))
  1941. {
  1942. $value=$this->_d[$key];
  1943. unset($this->_d[$key]);
  1944. return $value;
  1945. }
  1946. else
  1947. {
  1948. // it is possible the value is null, which is not detected by isset
  1949. unset($this->_d[$key]);
  1950. return null;
  1951. }
  1952. }
  1953. else
  1954. throw new CException(Yii::t('yii','The map is read only.'));
  1955. }
  1956. public function clear()
  1957. {
  1958. foreach(array_keys($this->_d) as $key)
  1959. $this->remove($key);
  1960. }
  1961. public function contains($key)
  1962. {
  1963. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  1964. }
  1965. public function toArray()
  1966. {
  1967. return $this->_d;
  1968. }
  1969. public function copyFrom($data)
  1970. {
  1971. if(is_array($data) || $data instanceof Traversable)
  1972. {
  1973. if($this->getCount()>0)
  1974. $this->clear();
  1975. if($data instanceof CMap)
  1976. $data=$data->_d;
  1977. foreach($data as $key=>$value)
  1978. $this->add($key,$value);
  1979. }
  1980. elseif($data!==null)
  1981. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1982. }
  1983. public function mergeWith($data,$recursive=true)
  1984. {
  1985. if(is_array($data) || $data instanceof Traversable)
  1986. {
  1987. if($data instanceof CMap)
  1988. $data=$data->_d;
  1989. if($recursive)
  1990. {
  1991. if($data instanceof Traversable)
  1992. {
  1993. $d=array();
  1994. foreach($data as $key=>$value)
  1995. $d[$key]=$value;
  1996. $this->_d=self::mergeArray($this->_d,$d);
  1997. }
  1998. else
  1999. $this->_d=self::mergeArray($this->_d,$data);
  2000. }
  2001. else
  2002. {
  2003. foreach($data as $key=>$value)
  2004. $this->add($key,$value);
  2005. }
  2006. }
  2007. elseif($data!==null)
  2008. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  2009. }
  2010. public static function mergeArray($a,$b)
  2011. {
  2012. $args=func_get_args();
  2013. $res=array_shift($args);
  2014. while(!empty($args))
  2015. {
  2016. $next=array_shift($args);
  2017. foreach($next as $k => $v)
  2018. {
  2019. if(is_integer($k))
  2020. isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
  2021. elseif(is_array($v) && isset($res[$k]) && is_array($res[$k]))
  2022. $res[$k]=self::mergeArray($res[$k],$v);
  2023. else
  2024. $res[$k]=$v;
  2025. }
  2026. }
  2027. return $res;
  2028. }
  2029. public function offsetExists($offset)
  2030. {
  2031. return $this->contains($offset);
  2032. }
  2033. public function offsetGet($offset)
  2034. {
  2035. return $this->itemAt($offset);
  2036. }
  2037. public function offsetSet($offset,$item)
  2038. {
  2039. $this->add($offset,$item);
  2040. }
  2041. public function offsetUnset($offset)
  2042. {
  2043. $this->remove($offset);
  2044. }
  2045. }
  2046. class CLogger extends CComponent
  2047. {
  2048. const LEVEL_TRACE='trace';
  2049. const LEVEL_WARNING='warning';
  2050. const LEVEL_ERROR='error';
  2051. const LEVEL_INFO='info';
  2052. const LEVEL_PROFILE='profile';
  2053. public $autoFlush=10000;
  2054. public $autoDump=false;
  2055. private $_logs=array();
  2056. private $_logCount=0;
  2057. private $_levels;
  2058. private $_categories;
  2059. private $_except=array();
  2060. private $_timings;
  2061. private $_processing=false;
  2062. public function log($message,$level='info',$category='application')
  2063. {
  2064. $this->_logs[]=array($message,$level,$category,microtime(true));
  2065. $this->_logCount++;
  2066. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
  2067. {
  2068. $this->_processing=true;
  2069. $this->flush($this->autoDump);
  2070. $this->_processing=false;
  2071. }
  2072. }
  2073. public function getLogs($levels='',$categories=array(), $except=array())
  2074. {
  2075. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2076. if (is_string($categories))
  2077. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2078. else
  2079. $this->_categories=array_filter(array_map('strtolower',$categories));
  2080. if (is_string($except))
  2081. $this->_except=preg_split('/[\s,]+/',strtolower($except),-1,PREG_SPLIT_NO_EMPTY);
  2082. else
  2083. $this->_except=array_filter(array_map('strtolower',$except));
  2084. $ret=$this->_logs;
  2085. if(!empty($levels))
  2086. $ret=array_values(array_filter($ret,array($this,'filterByLevel')));
  2087. if(!empty($this->_categories) || !empty($this->_except))
  2088. $ret=array_values(array_filter($ret,array($this,'filterByCategory')));
  2089. return $ret;
  2090. }
  2091. private function filterByCategory($value)
  2092. {
  2093. return $this->filterAllCategories($value, 2);
  2094. }
  2095. private function filterTimingByCategory($value)
  2096. {
  2097. return $this->filterAllCategories($value, 1);
  2098. }
  2099. private function filterAllCategories($value, $index)
  2100. {
  2101. $cat=strtolower($value[$index]);
  2102. $ret=empty($this->_categories);
  2103. foreach($this->_categories as $category)
  2104. {
  2105. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2106. $ret=true;
  2107. }
  2108. if($ret)
  2109. {
  2110. foreach($this->_except as $category)
  2111. {
  2112. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2113. $ret=false;
  2114. }
  2115. }
  2116. return $ret;
  2117. }
  2118. private function filterByLevel($value)
  2119. {
  2120. return in_array(strtolower($value[1]),$this->_levels);
  2121. }
  2122. public function getExecutionTime()
  2123. {
  2124. return microtime(true)-YII_BEGIN_TIME;
  2125. }
  2126. public function getMemoryUsage()
  2127. {
  2128. if(function_exists('memory_get_usage'))
  2129. return memory_get_usage();
  2130. else
  2131. {
  2132. $output=array();
  2133. if(strncmp(PHP_OS,'WIN',3)===0)
  2134. {
  2135. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2136. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2137. }
  2138. else
  2139. {
  2140. $pid=getmypid();
  2141. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2142. $output=explode(" ",$output[0]);
  2143. return isset($output[1]) ? $output[1]*1024 : 0;
  2144. }
  2145. }
  2146. }
  2147. public function getProfilingResults($token=null,$categories=null,$refresh=false)
  2148. {
  2149. if($this->_timings===null || $refresh)
  2150. $this->calculateTimings();
  2151. if($token===null && $categories===null)
  2152. return $this->_timings;
  2153. $timings = $this->_timings;
  2154. if($categories!==null) {
  2155. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2156. $timings=array_filter($timings,array($this,'filterTimingByCategory'));
  2157. }
  2158. $results=array();
  2159. foreach($timings as $timing)
  2160. {
  2161. if($token===null || $timing[0]===$token)
  2162. $results[]=$timing[2];
  2163. }
  2164. return $results;
  2165. }
  2166. private function calculateTimings()
  2167. {
  2168. $this->_timings=array();
  2169. $stack=array();
  2170. foreach($this->_logs as $log)
  2171. {
  2172. if($log[1]!==CLogger::LEVEL_PROFILE)
  2173. continue;
  2174. list($message,$level,$category,$timestamp)=$log;
  2175. if(!strncasecmp($message,'begin:',6))
  2176. {
  2177. $log[0]=substr($message,6);
  2178. $stack[]=$log;
  2179. }
  2180. elseif(!strncasecmp($message,'end:',4))
  2181. {
  2182. $token=substr($message,4);
  2183. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2184. {
  2185. $delta=$log[3]-$last[3];
  2186. $this->_timings[]=array($message,$category,$delta);
  2187. }
  2188. else
  2189. 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.',
  2190. array('{token}'=>$token)));
  2191. }
  2192. }
  2193. $now=microtime(true);
  2194. while(($last=array_pop($stack))!==null)
  2195. {
  2196. $delta=$now-$last[3];
  2197. $this->_timings[]=array($last[0],$last[2],$delta);
  2198. }
  2199. }
  2200. public function flush($dumpLogs=false)
  2201. {
  2202. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2203. $this->_logs=array();
  2204. $this->_logCount=0;
  2205. }
  2206. public function onFlush($event)
  2207. {
  2208. $this->raiseEvent('onFlush', $event);
  2209. }
  2210. }
  2211. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2212. {
  2213. public $behaviors=array();
  2214. private $_initialized=false;
  2215. public function init()
  2216. {
  2217. $this->attachBehaviors($this->behaviors);
  2218. $this->_initialized=true;
  2219. }
  2220. public function getIsInitialized()
  2221. {
  2222. return $this->_initialized;
  2223. }
  2224. }
  2225. class CHttpRequest extends CApplicationComponent
  2226. {
  2227. public $enableCookieValidation=false;
  2228. public $enableCsrfValidation=false;
  2229. public $csrfTokenName='YII_CSRF_TOKEN';
  2230. public $csrfCookie;
  2231. private $_requestUri;
  2232. private $_pathInfo;
  2233. private $_scriptFile;
  2234. private $_scriptUrl;
  2235. private $_hostInfo;
  2236. private $_baseUrl;
  2237. private $_cookies;
  2238. private $_preferredLanguages;
  2239. private $_csrfToken;
  2240. private $_restParams;
  2241. public function init()
  2242. {
  2243. parent::init();
  2244. $this->normalizeRequest();
  2245. }
  2246. protected function normalizeRequest()
  2247. {
  2248. // normalize request
  2249. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2250. {
  2251. if(isset($_GET))
  2252. $_GET=$this->stripSlashes($_GET);
  2253. if(isset($_POST))
  2254. $_POST=$this->stripSlashes($_POST);
  2255. if(isset($_REQUEST))
  2256. $_REQUEST=$this->stripSlashes($_REQUEST);
  2257. if(isset($_COOKIE))
  2258. $_COOKIE=$this->stripSlashes($_COOKIE);
  2259. }
  2260. if($this->enableCsrfValidation)
  2261. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2262. }
  2263. public function stripSlashes(&$data)
  2264. {
  2265. return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
  2266. }
  2267. public function getParam($name,$defaultValue=null)
  2268. {
  2269. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2270. }
  2271. public function getQuery($name,$defaultValue=null)
  2272. {
  2273. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2274. }
  2275. public function getPost($name,$defaultValue=null)
  2276. {
  2277. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2278. }
  2279. public function getDelete($name,$defaultValue=null)
  2280. {
  2281. if($this->getIsDeleteViaPostRequest())
  2282. return $this->getPost($name, $defaultValue);
  2283. if($this->getIsDeleteRequest())
  2284. {
  2285. $this->getRestParams();
  2286. return isset($this->_restParams[$name]) ? $this->_restParams[$name] : $defaultValue;
  2287. }
  2288. else
  2289. return $defaultValue;
  2290. }
  2291. public function getPut($name,$defaultValue=null)
  2292. {
  2293. if($this->getIsPutViaPostRequest())
  2294. return $this->getPost($name, $defaultValue);
  2295. if($this->getIsPutRequest())
  2296. {
  2297. $this->getRestParams();
  2298. return isset($this->_restParams[$name]) ? $this->_restParams[$name] : $defaultValue;
  2299. }
  2300. else
  2301. return $defaultValue;
  2302. }
  2303. public function getRestParams()
  2304. {
  2305. if($this->_restParams===null)
  2306. {
  2307. $result=array();
  2308. if(function_exists('mb_parse_str'))
  2309. mb_parse_str($this->getRawBody(), $result);
  2310. else
  2311. parse_str($this->getRawBody(), $result);
  2312. $this->_restParams=$result;
  2313. }
  2314. return $this->_restParams;
  2315. }
  2316. public function getRawBody()
  2317. {
  2318. static $rawBody;
  2319. if($rawBody===null)
  2320. $rawBody=file_get_contents('php://input');
  2321. return $rawBody;
  2322. }
  2323. public function getUrl()
  2324. {
  2325. return $this->getRequestUri();
  2326. }
  2327. public function getHostInfo($schema='')
  2328. {
  2329. if($this->_hostInfo===null)
  2330. {
  2331. if($secure=$this->getIsSecureConnection())
  2332. $http='https';
  2333. else
  2334. $http='http';
  2335. if(isset($_SERVER['HTTP_HOST']))
  2336. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2337. else
  2338. {
  2339. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2340. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2341. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2342. $this->_hostInfo.=':'.$port;
  2343. }
  2344. }
  2345. if($schema!=='')
  2346. {
  2347. $secure=$this->getIsSecureConnection();
  2348. if($secure && $schema==='https' || !$secure && $schema==='http')
  2349. return $this->_hostInfo;
  2350. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2351. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2352. $port=':'.$port;
  2353. else
  2354. $port='';
  2355. $pos=strpos($this->_hostInfo,':');
  2356. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2357. }
  2358. else
  2359. return $this->_hostInfo;
  2360. }
  2361. public function setHostInfo($value)
  2362. {
  2363. $this->_hostInfo=rtrim($value,'/');
  2364. }
  2365. public function getBaseUrl($absolute=false)
  2366. {
  2367. if($this->_baseUrl===null)
  2368. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2369. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2370. }
  2371. public function setBaseUrl($value)
  2372. {
  2373. $this->_baseUrl=$value;
  2374. }
  2375. public function getScriptUrl()
  2376. {
  2377. if($this->_scriptUrl===null)
  2378. {
  2379. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2380. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2381. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2382. elseif(basename($_SERVER['PHP_SELF'])===$scriptName)
  2383. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2384. elseif(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2385. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2386. elseif(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2387. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2388. elseif(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2389. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2390. else
  2391. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2392. }
  2393. return $this->_scriptUrl;
  2394. }
  2395. public function setScriptUrl($value)
  2396. {
  2397. $this->_scriptUrl='/'.trim($value,'/');
  2398. }
  2399. public function getPathInfo()
  2400. {
  2401. if($this->_pathInfo===null)
  2402. {
  2403. $pathInfo=$this->getRequestUri();
  2404. if(($pos=strpos($pathInfo,'?'))!==false)
  2405. $pathInfo=substr($pathInfo,0,$pos);
  2406. $pathInfo=$this->decodePathInfo($pathInfo);
  2407. $scriptUrl=$this->getScriptUrl();
  2408. $baseUrl=$this->getBaseUrl();
  2409. if(strpos($pathInfo,$scriptUrl)===0)
  2410. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2411. elseif($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2412. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2413. elseif(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2414. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2415. else
  2416. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2417. $this->_pathInfo=trim($pathInfo,'/');
  2418. }
  2419. return $this->_pathInfo;
  2420. }
  2421. protected function decodePathInfo($pathInfo)
  2422. {
  2423. $pathInfo = urldecode($pathInfo);
  2424. // is it UTF-8?
  2425. // http://w3.org/International/questions/qa-forms-utf-8.html
  2426. if(preg_match('%^(?:
  2427. [\x09\x0A\x0D\x20-\x7E] # ASCII
  2428. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  2429. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  2430. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  2431. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  2432. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  2433. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  2434. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  2435. )*$%xs', $pathInfo))
  2436. {
  2437. return $pathInfo;
  2438. }
  2439. else
  2440. {
  2441. return utf8_encode($pathInfo);
  2442. }
  2443. }
  2444. public function getRequestUri()
  2445. {
  2446. if($this->_requestUri===null)
  2447. {
  2448. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2449. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2450. elseif(isset($_SERVER['REQUEST_URI']))
  2451. {
  2452. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2453. if(!empty($_SERVER['HTTP_HOST']))
  2454. {
  2455. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2456. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2457. }
  2458. else
  2459. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2460. }
  2461. elseif(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2462. {
  2463. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2464. if(!empty($_SERVER['QUERY_STRING']))
  2465. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2466. }
  2467. else
  2468. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2469. }
  2470. return $this->_requestUri;
  2471. }
  2472. public function getQueryString()
  2473. {
  2474. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2475. }
  2476. public function getIsSecureConnection()
  2477. {
  2478. return !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'],'off');
  2479. }
  2480. public function getRequestType()
  2481. {
  2482. if(isset($_POST['_method']))
  2483. return strtoupper($_POST['_method']);
  2484. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2485. }
  2486. public function getIsPostRequest()
  2487. {
  2488. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2489. }
  2490. public function getIsDeleteRequest()
  2491. {
  2492. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE')) || $this->getIsDeleteViaPostRequest();
  2493. }
  2494. protected function getIsDeleteViaPostRequest()
  2495. {
  2496. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'DELETE');
  2497. }
  2498. public function getIsPutRequest()
  2499. {
  2500. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT')) || $this->getIsPutViaPostRequest();
  2501. }
  2502. protected function getIsPutViaPostRequest()
  2503. {
  2504. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PUT');
  2505. }
  2506. public function getIsAjaxRequest()
  2507. {
  2508. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2509. }
  2510. public function getIsFlashRequest()
  2511. {
  2512. return isset($_SERVER['HTTP_USER_AGENT']) && (stripos($_SERVER['HTTP_USER_AGENT'],'Shockwave')!==false || stripos($_SERVER['HTTP_USER_AGENT'],'Flash')!==false);
  2513. }
  2514. public function getServerName()
  2515. {
  2516. return $_SERVER['SERVER_NAME'];
  2517. }
  2518. public function getServerPort()
  2519. {
  2520. return $_SERVER['SERVER_PORT'];
  2521. }
  2522. public function getUrlReferrer()
  2523. {
  2524. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2525. }
  2526. public function getUserAgent()
  2527. {
  2528. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2529. }
  2530. public function getUserHostAddress()
  2531. {
  2532. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2533. }
  2534. public function getUserHost()
  2535. {
  2536. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2537. }
  2538. public function getScriptFile()
  2539. {
  2540. if($this->_scriptFile!==null)
  2541. return $this->_scriptFile;
  2542. else
  2543. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2544. }
  2545. public function getBrowser($userAgent=null)
  2546. {
  2547. return get_browser($userAgent,true);
  2548. }
  2549. public function getAcceptTypes()
  2550. {
  2551. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2552. }
  2553. private $_port;
  2554. public function getPort()
  2555. {
  2556. if($this->_port===null)
  2557. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2558. return $this->_port;
  2559. }
  2560. public function setPort($value)
  2561. {
  2562. $this->_port=(int)$value;
  2563. $this->_hostInfo=null;
  2564. }
  2565. private $_securePort;
  2566. public function getSecurePort()
  2567. {
  2568. if($this->_securePort===null)
  2569. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2570. return $this->_securePort;
  2571. }
  2572. public function setSecurePort($value)
  2573. {
  2574. $this->_securePort=(int)$value;
  2575. $this->_hostInfo=null;
  2576. }
  2577. public function getCookies()
  2578. {
  2579. if($this->_cookies!==null)
  2580. return $this->_cookies;
  2581. else
  2582. return $this->_cookies=new CCookieCollection($this);
  2583. }
  2584. public function redirect($url,$terminate=true,$statusCode=302)
  2585. {
  2586. if(strpos($url,'/')===0 && strpos($url,'//')!==0)
  2587. $url=$this->getHostInfo().$url;
  2588. header('Location: '.$url, true, $statusCode);
  2589. if($terminate)
  2590. Yii::app()->end();
  2591. }
  2592. public function getPreferredLanguages()
  2593. {
  2594. if($this->_preferredLanguages===null)
  2595. {
  2596. $sortedLanguages=array();
  2597. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $n=preg_match_all('/([\w\-_]+)(?:\s*;\s*q\s*=\s*(\d*\.?\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))
  2598. {
  2599. $languages=array();
  2600. for($i=0;$i<$n;++$i)
  2601. {
  2602. $q=$matches[2][$i];
  2603. if($q==='')
  2604. $q=1;
  2605. if($q)
  2606. $languages[]=array((float)$q,$matches[1][$i]);
  2607. }
  2608. usort($languages,create_function('$a,$b','if($a[0]==$b[0]) {return 0;} return ($a[0]<$b[0]) ? 1 : -1;'));
  2609. foreach($languages as $language)
  2610. $sortedLanguages[]=$language[1];
  2611. }
  2612. $this->_preferredLanguages=$sortedLanguages;
  2613. }
  2614. return $this->_preferredLanguages;
  2615. }
  2616. public function getPreferredLanguage()
  2617. {
  2618. $preferredLanguages=$this->getPreferredLanguages();
  2619. return !empty($preferredLanguages) ? CLocale::getCanonicalID($preferredLanguages[0]) : false;
  2620. }
  2621. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2622. {
  2623. if($mimeType===null)
  2624. {
  2625. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2626. $mimeType='text/plain';
  2627. }
  2628. header('Pragma: public');
  2629. header('Expires: 0');
  2630. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2631. header("Content-type: $mimeType");
  2632. header('Content-Length: '.(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content)));
  2633. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2634. header('Content-Transfer-Encoding: binary');
  2635. if($terminate)
  2636. {
  2637. // clean up the application first because the file downloading could take long time
  2638. // which may cause timeout of some resources (such as DB connection)
  2639. ob_start();
  2640. Yii::app()->end(0,false);
  2641. ob_end_clean();
  2642. echo $content;
  2643. exit(0);
  2644. }
  2645. else
  2646. echo $content;
  2647. }
  2648. public function xSendFile($filePath, $options=array())
  2649. {
  2650. if(!isset($options['forceDownload']) || $options['forceDownload'])
  2651. $disposition='attachment';
  2652. else
  2653. $disposition='inline';
  2654. if(!isset($options['saveName']))
  2655. $options['saveName']=basename($filePath);
  2656. if(!isset($options['mimeType']))
  2657. {
  2658. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2659. $options['mimeType']='text/plain';
  2660. }
  2661. if(!isset($options['xHeader']))
  2662. $options['xHeader']='X-Sendfile';
  2663. if($options['mimeType'] !== null)
  2664. header('Content-type: '.$options['mimeType']);
  2665. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  2666. if(isset($options['addHeaders']))
  2667. {
  2668. foreach($options['addHeaders'] as $header=>$value)
  2669. header($header.': '.$value);
  2670. }
  2671. header(trim($options['xHeader']).': '.$filePath);
  2672. if(!isset($options['terminate']) || $options['terminate'])
  2673. Yii::app()->end();
  2674. }
  2675. public function getCsrfToken()
  2676. {
  2677. if($this->_csrfToken===null)
  2678. {
  2679. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2680. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2681. {
  2682. $cookie=$this->createCsrfCookie();
  2683. $this->_csrfToken=$cookie->value;
  2684. $this->getCookies()->add($cookie->name,$cookie);
  2685. }
  2686. }
  2687. return $this->_csrfToken;
  2688. }
  2689. protected function createCsrfCookie()
  2690. {
  2691. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2692. if(is_array($this->csrfCookie))
  2693. {
  2694. foreach($this->csrfCookie as $name=>$value)
  2695. $cookie->$name=$value;
  2696. }
  2697. return $cookie;
  2698. }
  2699. public function validateCsrfToken($event)
  2700. {
  2701. if ($this->getIsPostRequest() ||
  2702. $this->getIsPutRequest() ||
  2703. $this->getIsDeleteRequest())
  2704. {
  2705. $cookies=$this->getCookies();
  2706. $method=$this->getRequestType();
  2707. switch($method)
  2708. {
  2709. case 'POST':
  2710. $userToken=$this->getPost($this->csrfTokenName);
  2711. break;
  2712. case 'PUT':
  2713. $userToken=$this->getPut($this->csrfTokenName);
  2714. break;
  2715. case 'DELETE':
  2716. $userToken=$this->getDelete($this->csrfTokenName);
  2717. }
  2718. if (!empty($userToken) && $cookies->contains($this->csrfTokenName))
  2719. {
  2720. $cookieToken=$cookies->itemAt($this->csrfTokenName)->value;
  2721. $valid=$cookieToken===$userToken;
  2722. }
  2723. else
  2724. $valid = false;
  2725. if (!$valid)
  2726. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2727. }
  2728. }
  2729. }
  2730. class CCookieCollection extends CMap
  2731. {
  2732. private $_request;
  2733. private $_initialized=false;
  2734. public function __construct(CHttpRequest $request)
  2735. {
  2736. $this->_request=$request;
  2737. $this->copyfrom($this->getCookies());
  2738. $this->_initialized=true;
  2739. }
  2740. public function getRequest()
  2741. {
  2742. return $this->_request;
  2743. }
  2744. protected function getCookies()
  2745. {
  2746. $cookies=array();
  2747. if($this->_request->enableCookieValidation)
  2748. {
  2749. $sm=Yii::app()->getSecurityManager();
  2750. foreach($_COOKIE as $name=>$value)
  2751. {
  2752. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  2753. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  2754. }
  2755. }
  2756. else
  2757. {
  2758. foreach($_COOKIE as $name=>$value)
  2759. $cookies[$name]=new CHttpCookie($name,$value);
  2760. }
  2761. return $cookies;
  2762. }
  2763. public function add($name,$cookie)
  2764. {
  2765. if($cookie instanceof CHttpCookie)
  2766. {
  2767. $this->remove($name);
  2768. parent::add($name,$cookie);
  2769. if($this->_initialized)
  2770. $this->addCookie($cookie);
  2771. }
  2772. else
  2773. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  2774. }
  2775. public function remove($name,$options=array())
  2776. {
  2777. if(($cookie=parent::remove($name))!==null)
  2778. {
  2779. if($this->_initialized)
  2780. {
  2781. $cookie->configure($options);
  2782. $this->removeCookie($cookie);
  2783. }
  2784. }
  2785. return $cookie;
  2786. }
  2787. protected function addCookie($cookie)
  2788. {
  2789. $value=$cookie->value;
  2790. if($this->_request->enableCookieValidation)
  2791. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  2792. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2793. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2794. else
  2795. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  2796. }
  2797. protected function removeCookie($cookie)
  2798. {
  2799. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2800. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2801. else
  2802. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure);
  2803. }
  2804. }
  2805. class CUrlManager extends CApplicationComponent
  2806. {
  2807. const CACHE_KEY='Yii.CUrlManager.rules';
  2808. const GET_FORMAT='get';
  2809. const PATH_FORMAT='path';
  2810. public $rules=array();
  2811. public $urlSuffix='';
  2812. public $showScriptName=true;
  2813. public $appendParams=true;
  2814. public $routeVar='r';
  2815. public $caseSensitive=true;
  2816. public $matchValue=false;
  2817. public $cacheID='cache';
  2818. public $useStrictParsing=false;
  2819. public $urlRuleClass='CUrlRule';
  2820. private $_urlFormat=self::GET_FORMAT;
  2821. private $_rules=array();
  2822. private $_baseUrl;
  2823. public function init()
  2824. {
  2825. parent::init();
  2826. $this->processRules();
  2827. }
  2828. protected function processRules()
  2829. {
  2830. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  2831. return;
  2832. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  2833. {
  2834. $hash=md5(serialize($this->rules));
  2835. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  2836. {
  2837. $this->_rules=$data[0];
  2838. return;
  2839. }
  2840. }
  2841. foreach($this->rules as $pattern=>$route)
  2842. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2843. if(isset($cache))
  2844. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  2845. }
  2846. public function addRules($rules,$append=true)
  2847. {
  2848. if ($append)
  2849. {
  2850. foreach($rules as $pattern=>$route)
  2851. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2852. }
  2853. else
  2854. {
  2855. $rules=array_reverse($rules);
  2856. foreach($rules as $pattern=>$route)
  2857. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  2858. }
  2859. }
  2860. protected function createUrlRule($route,$pattern)
  2861. {
  2862. if(is_array($route) && isset($route['class']))
  2863. return $route;
  2864. else
  2865. return new $this->urlRuleClass($route,$pattern);
  2866. }
  2867. public function createUrl($route,$params=array(),$ampersand='&')
  2868. {
  2869. unset($params[$this->routeVar]);
  2870. foreach($params as $i=>$param)
  2871. if($param===null)
  2872. $params[$i]='';
  2873. if(isset($params['#']))
  2874. {
  2875. $anchor='#'.$params['#'];
  2876. unset($params['#']);
  2877. }
  2878. else
  2879. $anchor='';
  2880. $route=trim($route,'/');
  2881. foreach($this->_rules as $i=>$rule)
  2882. {
  2883. if(is_array($rule))
  2884. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2885. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  2886. {
  2887. if($rule->hasHostInfo)
  2888. return $url==='' ? '/'.$anchor : $url.$anchor;
  2889. else
  2890. return $this->getBaseUrl().'/'.$url.$anchor;
  2891. }
  2892. }
  2893. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  2894. }
  2895. protected function createUrlDefault($route,$params,$ampersand)
  2896. {
  2897. if($this->getUrlFormat()===self::PATH_FORMAT)
  2898. {
  2899. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  2900. if($this->appendParams)
  2901. {
  2902. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  2903. return $route==='' ? $url : $url.$this->urlSuffix;
  2904. }
  2905. else
  2906. {
  2907. if($route!=='')
  2908. $url.=$this->urlSuffix;
  2909. $query=$this->createPathInfo($params,'=',$ampersand);
  2910. return $query==='' ? $url : $url.'?'.$query;
  2911. }
  2912. }
  2913. else
  2914. {
  2915. $url=$this->getBaseUrl();
  2916. if(!$this->showScriptName)
  2917. $url.='/';
  2918. if($route!=='')
  2919. {
  2920. $url.='?'.$this->routeVar.'='.$route;
  2921. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2922. $url.=$ampersand.$query;
  2923. }
  2924. elseif(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2925. $url.='?'.$query;
  2926. return $url;
  2927. }
  2928. }
  2929. public function parseUrl($request)
  2930. {
  2931. if($this->getUrlFormat()===self::PATH_FORMAT)
  2932. {
  2933. $rawPathInfo=$request->getPathInfo();
  2934. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  2935. foreach($this->_rules as $i=>$rule)
  2936. {
  2937. if(is_array($rule))
  2938. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2939. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  2940. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  2941. }
  2942. if($this->useStrictParsing)
  2943. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  2944. array('{route}'=>$pathInfo)));
  2945. else
  2946. return $pathInfo;
  2947. }
  2948. elseif(isset($_GET[$this->routeVar]))
  2949. return $_GET[$this->routeVar];
  2950. elseif(isset($_POST[$this->routeVar]))
  2951. return $_POST[$this->routeVar];
  2952. else
  2953. return '';
  2954. }
  2955. public function parsePathInfo($pathInfo)
  2956. {
  2957. if($pathInfo==='')
  2958. return;
  2959. $segs=explode('/',$pathInfo.'/');
  2960. $n=count($segs);
  2961. for($i=0;$i<$n-1;$i+=2)
  2962. {
  2963. $key=$segs[$i];
  2964. if($key==='') continue;
  2965. $value=$segs[$i+1];
  2966. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  2967. {
  2968. $name=substr($key,0,$pos);
  2969. for($j=$m-1;$j>=0;--$j)
  2970. {
  2971. if($matches[1][$j]==='')
  2972. $value=array($value);
  2973. else
  2974. $value=array($matches[1][$j]=>$value);
  2975. }
  2976. if(isset($_GET[$name]) && is_array($_GET[$name]))
  2977. $value=CMap::mergeArray($_GET[$name],$value);
  2978. $_REQUEST[$name]=$_GET[$name]=$value;
  2979. }
  2980. else
  2981. $_REQUEST[$key]=$_GET[$key]=$value;
  2982. }
  2983. }
  2984. public function createPathInfo($params,$equal,$ampersand, $key=null)
  2985. {
  2986. $pairs = array();
  2987. foreach($params as $k => $v)
  2988. {
  2989. if ($key!==null)
  2990. $k = $key.'['.$k.']';
  2991. if (is_array($v))
  2992. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  2993. else
  2994. $pairs[]=urlencode($k).$equal.urlencode($v);
  2995. }
  2996. return implode($ampersand,$pairs);
  2997. }
  2998. public function removeUrlSuffix($pathInfo,$urlSuffix)
  2999. {
  3000. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  3001. return substr($pathInfo,0,-strlen($urlSuffix));
  3002. else
  3003. return $pathInfo;
  3004. }
  3005. public function getBaseUrl()
  3006. {
  3007. if($this->_baseUrl!==null)
  3008. return $this->_baseUrl;
  3009. else
  3010. {
  3011. if($this->showScriptName)
  3012. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  3013. else
  3014. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  3015. return $this->_baseUrl;
  3016. }
  3017. }
  3018. public function setBaseUrl($value)
  3019. {
  3020. $this->_baseUrl=$value;
  3021. }
  3022. public function getUrlFormat()
  3023. {
  3024. return $this->_urlFormat;
  3025. }
  3026. public function setUrlFormat($value)
  3027. {
  3028. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  3029. $this->_urlFormat=$value;
  3030. else
  3031. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  3032. }
  3033. }
  3034. abstract class CBaseUrlRule extends CComponent
  3035. {
  3036. public $hasHostInfo=false;
  3037. abstract public function createUrl($manager,$route,$params,$ampersand);
  3038. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  3039. }
  3040. class CUrlRule extends CBaseUrlRule
  3041. {
  3042. public $urlSuffix;
  3043. public $caseSensitive;
  3044. public $defaultParams=array();
  3045. public $matchValue;
  3046. public $verb;
  3047. public $parsingOnly=false;
  3048. public $route;
  3049. public $references=array();
  3050. public $routePattern;
  3051. public $pattern;
  3052. public $template;
  3053. public $params=array();
  3054. public $append;
  3055. public $hasHostInfo;
  3056. public function __construct($route,$pattern)
  3057. {
  3058. if(is_array($route))
  3059. {
  3060. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  3061. {
  3062. if(isset($route[$name]))
  3063. $this->$name=$route[$name];
  3064. }
  3065. if(isset($route['pattern']))
  3066. $pattern=$route['pattern'];
  3067. $route=$route[0];
  3068. }
  3069. $this->route=trim($route,'/');
  3070. $tr2['/']=$tr['/']='\\/';
  3071. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  3072. {
  3073. foreach($matches2[1] as $name)
  3074. $this->references[$name]="<$name>";
  3075. }
  3076. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  3077. if($this->verb!==null)
  3078. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  3079. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  3080. {
  3081. $tokens=array_combine($matches[1],$matches[2]);
  3082. foreach($tokens as $name=>$value)
  3083. {
  3084. if($value==='')
  3085. $value='[^\/]+';
  3086. $tr["<$name>"]="(?P<$name>$value)";
  3087. if(isset($this->references[$name]))
  3088. $tr2["<$name>"]=$tr["<$name>"];
  3089. else
  3090. $this->params[$name]=$value;
  3091. }
  3092. }
  3093. $p=rtrim($pattern,'*');
  3094. $this->append=$p!==$pattern;
  3095. $p=trim($p,'/');
  3096. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  3097. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  3098. if($this->append)
  3099. $this->pattern.='/u';
  3100. else
  3101. $this->pattern.='$/u';
  3102. if($this->references!==array())
  3103. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  3104. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  3105. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  3106. array('{route}'=>$route,'{pattern}'=>$pattern)));
  3107. }
  3108. public function createUrl($manager,$route,$params,$ampersand)
  3109. {
  3110. if($this->parsingOnly)
  3111. return false;
  3112. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3113. $case='';
  3114. else
  3115. $case='i';
  3116. $tr=array();
  3117. if($route!==$this->route)
  3118. {
  3119. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  3120. {
  3121. foreach($this->references as $key=>$name)
  3122. $tr[$name]=$matches[$key];
  3123. }
  3124. else
  3125. return false;
  3126. }
  3127. foreach($this->defaultParams as $key=>$value)
  3128. {
  3129. if(isset($params[$key]))
  3130. {
  3131. if($params[$key]==$value)
  3132. unset($params[$key]);
  3133. else
  3134. return false;
  3135. }
  3136. }
  3137. foreach($this->params as $key=>$value)
  3138. if(!isset($params[$key]))
  3139. return false;
  3140. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  3141. {
  3142. foreach($this->params as $key=>$value)
  3143. {
  3144. if(!preg_match('/\A'.$value.'\z/u'.$case,$params[$key]))
  3145. return false;
  3146. }
  3147. }
  3148. foreach($this->params as $key=>$value)
  3149. {
  3150. $tr["<$key>"]=urlencode($params[$key]);
  3151. unset($params[$key]);
  3152. }
  3153. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3154. $url=strtr($this->template,$tr);
  3155. if($this->hasHostInfo)
  3156. {
  3157. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  3158. if(stripos($url,$hostInfo)===0)
  3159. $url=substr($url,strlen($hostInfo));
  3160. }
  3161. if(empty($params))
  3162. return $url!=='' ? $url.$suffix : $url;
  3163. if($this->append)
  3164. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  3165. else
  3166. {
  3167. if($url!=='')
  3168. $url.=$suffix;
  3169. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  3170. }
  3171. return $url;
  3172. }
  3173. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  3174. {
  3175. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  3176. return false;
  3177. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3178. $case='';
  3179. else
  3180. $case='i';
  3181. if($this->urlSuffix!==null)
  3182. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3183. // URL suffix required, but not found in the requested URL
  3184. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3185. {
  3186. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3187. if($urlSuffix!='' && $urlSuffix!=='/')
  3188. return false;
  3189. }
  3190. if($this->hasHostInfo)
  3191. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3192. $pathInfo.='/';
  3193. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3194. {
  3195. foreach($this->defaultParams as $name=>$value)
  3196. {
  3197. if(!isset($_GET[$name]))
  3198. $_REQUEST[$name]=$_GET[$name]=$value;
  3199. }
  3200. $tr=array();
  3201. foreach($matches as $key=>$value)
  3202. {
  3203. if(isset($this->references[$key]))
  3204. $tr[$this->references[$key]]=$value;
  3205. elseif(isset($this->params[$key]))
  3206. $_REQUEST[$key]=$_GET[$key]=$value;
  3207. }
  3208. if($pathInfo!==$matches[0]) // there're additional GET params
  3209. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3210. if($this->routePattern!==null)
  3211. return strtr($this->route,$tr);
  3212. else
  3213. return $this->route;
  3214. }
  3215. else
  3216. return false;
  3217. }
  3218. }
  3219. abstract class CBaseController extends CComponent
  3220. {
  3221. private $_widgetStack=array();
  3222. abstract public function getViewFile($viewName);
  3223. public function renderFile($viewFile,$data=null,$return=false)
  3224. {
  3225. $widgetCount=count($this->_widgetStack);
  3226. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3227. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3228. else
  3229. $content=$this->renderInternal($viewFile,$data,$return);
  3230. if(count($this->_widgetStack)===$widgetCount)
  3231. return $content;
  3232. else
  3233. {
  3234. $widget=end($this->_widgetStack);
  3235. 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.',
  3236. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3237. }
  3238. }
  3239. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3240. {
  3241. // we use special variable names here to avoid conflict when extracting data
  3242. if(is_array($_data_))
  3243. extract($_data_,EXTR_PREFIX_SAME,'data');
  3244. else
  3245. $data=$_data_;
  3246. if($_return_)
  3247. {
  3248. ob_start();
  3249. ob_implicit_flush(false);
  3250. require($_viewFile_);
  3251. return ob_get_clean();
  3252. }
  3253. else
  3254. require($_viewFile_);
  3255. }
  3256. public function createWidget($className,$properties=array())
  3257. {
  3258. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3259. $widget->init();
  3260. return $widget;
  3261. }
  3262. public function widget($className,$properties=array(),$captureOutput=false)
  3263. {
  3264. if($captureOutput)
  3265. {
  3266. ob_start();
  3267. ob_implicit_flush(false);
  3268. $widget=$this->createWidget($className,$properties);
  3269. $widget->run();
  3270. return ob_get_clean();
  3271. }
  3272. else
  3273. {
  3274. $widget=$this->createWidget($className,$properties);
  3275. $widget->run();
  3276. return $widget;
  3277. }
  3278. }
  3279. public function beginWidget($className,$properties=array())
  3280. {
  3281. $widget=$this->createWidget($className,$properties);
  3282. $this->_widgetStack[]=$widget;
  3283. return $widget;
  3284. }
  3285. public function endWidget($id='')
  3286. {
  3287. if(($widget=array_pop($this->_widgetStack))!==null)
  3288. {
  3289. $widget->run();
  3290. return $widget;
  3291. }
  3292. else
  3293. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3294. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3295. }
  3296. public function beginClip($id,$properties=array())
  3297. {
  3298. $properties['id']=$id;
  3299. $this->beginWidget('CClipWidget',$properties);
  3300. }
  3301. public function endClip()
  3302. {
  3303. $this->endWidget('CClipWidget');
  3304. }
  3305. public function beginCache($id,$properties=array())
  3306. {
  3307. $properties['id']=$id;
  3308. $cache=$this->beginWidget('COutputCache',$properties);
  3309. if($cache->getIsContentCached())
  3310. {
  3311. $this->endCache();
  3312. return false;
  3313. }
  3314. else
  3315. return true;
  3316. }
  3317. public function endCache()
  3318. {
  3319. $this->endWidget('COutputCache');
  3320. }
  3321. public function beginContent($view=null,$data=array())
  3322. {
  3323. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3324. }
  3325. public function endContent()
  3326. {
  3327. $this->endWidget('CContentDecorator');
  3328. }
  3329. }
  3330. class CController extends CBaseController
  3331. {
  3332. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3333. public $layout;
  3334. public $defaultAction='index';
  3335. private $_id;
  3336. private $_action;
  3337. private $_pageTitle;
  3338. private $_cachingStack;
  3339. private $_clips;
  3340. private $_dynamicOutput;
  3341. private $_pageStates;
  3342. private $_module;
  3343. public function __construct($id,$module=null)
  3344. {
  3345. $this->_id=$id;
  3346. $this->_module=$module;
  3347. $this->attachBehaviors($this->behaviors());
  3348. }
  3349. public function init()
  3350. {
  3351. }
  3352. public function filters()
  3353. {
  3354. return array();
  3355. }
  3356. public function actions()
  3357. {
  3358. return array();
  3359. }
  3360. public function behaviors()
  3361. {
  3362. return array();
  3363. }
  3364. public function accessRules()
  3365. {
  3366. return array();
  3367. }
  3368. public function run($actionID)
  3369. {
  3370. if(($action=$this->createAction($actionID))!==null)
  3371. {
  3372. if(($parent=$this->getModule())===null)
  3373. $parent=Yii::app();
  3374. if($parent->beforeControllerAction($this,$action))
  3375. {
  3376. $this->runActionWithFilters($action,$this->filters());
  3377. $parent->afterControllerAction($this,$action);
  3378. }
  3379. }
  3380. else
  3381. $this->missingAction($actionID);
  3382. }
  3383. public function runActionWithFilters($action,$filters)
  3384. {
  3385. if(empty($filters))
  3386. $this->runAction($action);
  3387. else
  3388. {
  3389. $priorAction=$this->_action;
  3390. $this->_action=$action;
  3391. CFilterChain::create($this,$action,$filters)->run();
  3392. $this->_action=$priorAction;
  3393. }
  3394. }
  3395. public function runAction($action)
  3396. {
  3397. $priorAction=$this->_action;
  3398. $this->_action=$action;
  3399. if($this->beforeAction($action))
  3400. {
  3401. if($action->runWithParams($this->getActionParams())===false)
  3402. $this->invalidActionParams($action);
  3403. else
  3404. $this->afterAction($action);
  3405. }
  3406. $this->_action=$priorAction;
  3407. }
  3408. public function getActionParams()
  3409. {
  3410. return $_GET;
  3411. }
  3412. public function invalidActionParams($action)
  3413. {
  3414. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3415. }
  3416. public function processOutput($output)
  3417. {
  3418. Yii::app()->getClientScript()->render($output);
  3419. // if using page caching, we should delay dynamic output replacement
  3420. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3421. {
  3422. $output=$this->processDynamicOutput($output);
  3423. $this->_dynamicOutput=null;
  3424. }
  3425. if($this->_pageStates===null)
  3426. $this->_pageStates=$this->loadPageStates();
  3427. if(!empty($this->_pageStates))
  3428. $this->savePageStates($this->_pageStates,$output);
  3429. return $output;
  3430. }
  3431. public function processDynamicOutput($output)
  3432. {
  3433. if($this->_dynamicOutput)
  3434. {
  3435. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3436. }
  3437. return $output;
  3438. }
  3439. protected function replaceDynamicOutput($matches)
  3440. {
  3441. $content=$matches[0];
  3442. if(isset($this->_dynamicOutput[$matches[1]]))
  3443. {
  3444. $content=$this->_dynamicOutput[$matches[1]];
  3445. $this->_dynamicOutput[$matches[1]]=null;
  3446. }
  3447. return $content;
  3448. }
  3449. public function createAction($actionID)
  3450. {
  3451. if($actionID==='')
  3452. $actionID=$this->defaultAction;
  3453. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3454. return new CInlineAction($this,$actionID);
  3455. else
  3456. {
  3457. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3458. if($action!==null && !method_exists($action,'run'))
  3459. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3460. return $action;
  3461. }
  3462. }
  3463. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3464. {
  3465. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3466. {
  3467. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3468. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3469. }
  3470. elseif($pos===false)
  3471. return null;
  3472. // the action is defined in a provider
  3473. $prefix=substr($actionID,0,$pos+1);
  3474. if(!isset($actionMap[$prefix]))
  3475. return null;
  3476. $actionID=(string)substr($actionID,$pos+1);
  3477. $provider=$actionMap[$prefix];
  3478. if(is_string($provider))
  3479. $providerType=$provider;
  3480. elseif(is_array($provider) && isset($provider['class']))
  3481. {
  3482. $providerType=$provider['class'];
  3483. if(isset($provider[$actionID]))
  3484. {
  3485. if(is_string($provider[$actionID]))
  3486. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3487. else
  3488. $config=array_merge($provider[$actionID],$config);
  3489. }
  3490. }
  3491. else
  3492. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3493. $class=Yii::import($providerType,true);
  3494. $map=call_user_func(array($class,'actions'));
  3495. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3496. }
  3497. public function missingAction($actionID)
  3498. {
  3499. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3500. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3501. }
  3502. public function getAction()
  3503. {
  3504. return $this->_action;
  3505. }
  3506. public function setAction($value)
  3507. {
  3508. $this->_action=$value;
  3509. }
  3510. public function getId()
  3511. {
  3512. return $this->_id;
  3513. }
  3514. public function getUniqueId()
  3515. {
  3516. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3517. }
  3518. public function getRoute()
  3519. {
  3520. if(($action=$this->getAction())!==null)
  3521. return $this->getUniqueId().'/'.$action->getId();
  3522. else
  3523. return $this->getUniqueId();
  3524. }
  3525. public function getModule()
  3526. {
  3527. return $this->_module;
  3528. }
  3529. public function getViewPath()
  3530. {
  3531. if(($module=$this->getModule())===null)
  3532. $module=Yii::app();
  3533. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3534. }
  3535. public function getViewFile($viewName)
  3536. {
  3537. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3538. return $viewFile;
  3539. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3540. if(($module=$this->getModule())!==null)
  3541. $moduleViewPath=$module->getViewPath();
  3542. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3543. }
  3544. public function getLayoutFile($layoutName)
  3545. {
  3546. if($layoutName===false)
  3547. return false;
  3548. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3549. return $layoutFile;
  3550. if(empty($layoutName))
  3551. {
  3552. $module=$this->getModule();
  3553. while($module!==null)
  3554. {
  3555. if($module->layout===false)
  3556. return false;
  3557. if(!empty($module->layout))
  3558. break;
  3559. $module=$module->getParentModule();
  3560. }
  3561. if($module===null)
  3562. $module=Yii::app();
  3563. $layoutName=$module->layout;
  3564. }
  3565. elseif(($module=$this->getModule())===null)
  3566. $module=Yii::app();
  3567. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3568. }
  3569. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3570. {
  3571. if(empty($viewName))
  3572. return false;
  3573. if($moduleViewPath===null)
  3574. $moduleViewPath=$basePath;
  3575. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3576. $extension=$renderer->fileExtension;
  3577. else
  3578. $extension='.php';
  3579. if($viewName[0]==='/')
  3580. {
  3581. if(strncmp($viewName,'//',2)===0)
  3582. $viewFile=$basePath.$viewName;
  3583. else
  3584. $viewFile=$moduleViewPath.$viewName;
  3585. }
  3586. elseif(strpos($viewName,'.'))
  3587. $viewFile=Yii::getPathOfAlias($viewName);
  3588. else
  3589. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3590. if(is_file($viewFile.$extension))
  3591. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3592. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  3593. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3594. else
  3595. return false;
  3596. }
  3597. public function getClips()
  3598. {
  3599. if($this->_clips!==null)
  3600. return $this->_clips;
  3601. else
  3602. return $this->_clips=new CMap;
  3603. }
  3604. public function forward($route,$exit=true)
  3605. {
  3606. if(strpos($route,'/')===false)
  3607. $this->run($route);
  3608. else
  3609. {
  3610. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3611. $route=$module->getId().'/'.$route;
  3612. Yii::app()->runController($route);
  3613. }
  3614. if($exit)
  3615. Yii::app()->end();
  3616. }
  3617. public function render($view,$data=null,$return=false)
  3618. {
  3619. if($this->beforeRender($view))
  3620. {
  3621. $output=$this->renderPartial($view,$data,true);
  3622. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3623. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3624. $this->afterRender($view,$output);
  3625. $output=$this->processOutput($output);
  3626. if($return)
  3627. return $output;
  3628. else
  3629. echo $output;
  3630. }
  3631. }
  3632. protected function beforeRender($view)
  3633. {
  3634. return true;
  3635. }
  3636. protected function afterRender($view, &$output)
  3637. {
  3638. }
  3639. public function renderText($text,$return=false)
  3640. {
  3641. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3642. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3643. $text=$this->processOutput($text);
  3644. if($return)
  3645. return $text;
  3646. else
  3647. echo $text;
  3648. }
  3649. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3650. {
  3651. if(($viewFile=$this->getViewFile($view))!==false)
  3652. {
  3653. $output=$this->renderFile($viewFile,$data,true);
  3654. if($processOutput)
  3655. $output=$this->processOutput($output);
  3656. if($return)
  3657. return $output;
  3658. else
  3659. echo $output;
  3660. }
  3661. else
  3662. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3663. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3664. }
  3665. public function renderClip($name,$params=array(),$return=false)
  3666. {
  3667. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  3668. if($return)
  3669. return $text;
  3670. else
  3671. echo $text;
  3672. }
  3673. public function renderDynamic($callback)
  3674. {
  3675. $n=count($this->_dynamicOutput);
  3676. echo "<###dynamic-$n###>";
  3677. $params=func_get_args();
  3678. array_shift($params);
  3679. $this->renderDynamicInternal($callback,$params);
  3680. }
  3681. public function renderDynamicInternal($callback,$params)
  3682. {
  3683. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3684. if(is_string($callback) && method_exists($this,$callback))
  3685. $callback=array($this,$callback);
  3686. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3687. }
  3688. public function createUrl($route,$params=array(),$ampersand='&')
  3689. {
  3690. if($route==='')
  3691. $route=$this->getId().'/'.$this->getAction()->getId();
  3692. elseif(strpos($route,'/')===false)
  3693. $route=$this->getId().'/'.$route;
  3694. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3695. $route=$module->getId().'/'.$route;
  3696. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3697. }
  3698. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3699. {
  3700. $url=$this->createUrl($route,$params,$ampersand);
  3701. if(strpos($url,'http')===0)
  3702. return $url;
  3703. else
  3704. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  3705. }
  3706. public function getPageTitle()
  3707. {
  3708. if($this->_pageTitle!==null)
  3709. return $this->_pageTitle;
  3710. else
  3711. {
  3712. $name=ucfirst(basename($this->getId()));
  3713. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3714. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3715. else
  3716. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3717. }
  3718. }
  3719. public function setPageTitle($value)
  3720. {
  3721. $this->_pageTitle=$value;
  3722. }
  3723. public function redirect($url,$terminate=true,$statusCode=302)
  3724. {
  3725. if(is_array($url))
  3726. {
  3727. $route=isset($url[0]) ? $url[0] : '';
  3728. $url=$this->createUrl($route,array_splice($url,1));
  3729. }
  3730. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  3731. }
  3732. public function refresh($terminate=true,$anchor='')
  3733. {
  3734. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  3735. }
  3736. public function recordCachingAction($context,$method,$params)
  3737. {
  3738. if($this->_cachingStack) // record only when there is an active output cache
  3739. {
  3740. foreach($this->_cachingStack as $cache)
  3741. $cache->recordAction($context,$method,$params);
  3742. }
  3743. }
  3744. public function getCachingStack($createIfNull=true)
  3745. {
  3746. if(!$this->_cachingStack)
  3747. $this->_cachingStack=new CStack;
  3748. return $this->_cachingStack;
  3749. }
  3750. public function isCachingStackEmpty()
  3751. {
  3752. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  3753. }
  3754. protected function beforeAction($action)
  3755. {
  3756. return true;
  3757. }
  3758. protected function afterAction($action)
  3759. {
  3760. }
  3761. public function filterPostOnly($filterChain)
  3762. {
  3763. if(Yii::app()->getRequest()->getIsPostRequest())
  3764. $filterChain->run();
  3765. else
  3766. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3767. }
  3768. public function filterAjaxOnly($filterChain)
  3769. {
  3770. if(Yii::app()->getRequest()->getIsAjaxRequest())
  3771. $filterChain->run();
  3772. else
  3773. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3774. }
  3775. public function filterAccessControl($filterChain)
  3776. {
  3777. $filter=new CAccessControlFilter;
  3778. $filter->setRules($this->accessRules());
  3779. $filter->filter($filterChain);
  3780. }
  3781. public function getPageState($name,$defaultValue=null)
  3782. {
  3783. if($this->_pageStates===null)
  3784. $this->_pageStates=$this->loadPageStates();
  3785. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  3786. }
  3787. public function setPageState($name,$value,$defaultValue=null)
  3788. {
  3789. if($this->_pageStates===null)
  3790. $this->_pageStates=$this->loadPageStates();
  3791. if($value===$defaultValue)
  3792. unset($this->_pageStates[$name]);
  3793. else
  3794. $this->_pageStates[$name]=$value;
  3795. $params=func_get_args();
  3796. $this->recordCachingAction('','setPageState',$params);
  3797. }
  3798. public function clearPageStates()
  3799. {
  3800. $this->_pageStates=array();
  3801. }
  3802. protected function loadPageStates()
  3803. {
  3804. if(!empty($_POST[self::STATE_INPUT_NAME]))
  3805. {
  3806. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  3807. {
  3808. if(extension_loaded('zlib'))
  3809. $data=@gzuncompress($data);
  3810. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  3811. return unserialize($data);
  3812. }
  3813. }
  3814. return array();
  3815. }
  3816. protected function savePageStates($states,&$output)
  3817. {
  3818. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  3819. if(extension_loaded('zlib'))
  3820. $data=gzcompress($data);
  3821. $value=base64_encode($data);
  3822. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  3823. }
  3824. }
  3825. abstract class CAction extends CComponent implements IAction
  3826. {
  3827. private $_id;
  3828. private $_controller;
  3829. public function __construct($controller,$id)
  3830. {
  3831. $this->_controller=$controller;
  3832. $this->_id=$id;
  3833. }
  3834. public function getController()
  3835. {
  3836. return $this->_controller;
  3837. }
  3838. public function getId()
  3839. {
  3840. return $this->_id;
  3841. }
  3842. public function runWithParams($params)
  3843. {
  3844. $method=new ReflectionMethod($this, 'run');
  3845. if($method->getNumberOfParameters()>0)
  3846. return $this->runWithParamsInternal($this, $method, $params);
  3847. else
  3848. return $this->run();
  3849. }
  3850. protected function runWithParamsInternal($object, $method, $params)
  3851. {
  3852. $ps=array();
  3853. foreach($method->getParameters() as $i=>$param)
  3854. {
  3855. $name=$param->getName();
  3856. if(isset($params[$name]))
  3857. {
  3858. if($param->isArray())
  3859. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  3860. elseif(!is_array($params[$name]))
  3861. $ps[]=$params[$name];
  3862. else
  3863. return false;
  3864. }
  3865. elseif($param->isDefaultValueAvailable())
  3866. $ps[]=$param->getDefaultValue();
  3867. else
  3868. return false;
  3869. }
  3870. $method->invokeArgs($object,$ps);
  3871. return true;
  3872. }
  3873. }
  3874. class CInlineAction extends CAction
  3875. {
  3876. public function run()
  3877. {
  3878. $method='action'.$this->getId();
  3879. $this->getController()->$method();
  3880. }
  3881. public function runWithParams($params)
  3882. {
  3883. $methodName='action'.$this->getId();
  3884. $controller=$this->getController();
  3885. $method=new ReflectionMethod($controller, $methodName);
  3886. if($method->getNumberOfParameters()>0)
  3887. return $this->runWithParamsInternal($controller, $method, $params);
  3888. else
  3889. return $controller->$methodName();
  3890. }
  3891. }
  3892. class CWebUser extends CApplicationComponent implements IWebUser
  3893. {
  3894. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  3895. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  3896. const STATES_VAR='__states';
  3897. const AUTH_TIMEOUT_VAR='__timeout';
  3898. public $allowAutoLogin=false;
  3899. public $guestName='Guest';
  3900. public $loginUrl=array('/site/login');
  3901. public $identityCookie;
  3902. public $authTimeout;
  3903. public $autoRenewCookie=false;
  3904. public $autoUpdateFlash=true;
  3905. public $loginRequiredAjaxResponse;
  3906. private $_keyPrefix;
  3907. private $_access=array();
  3908. public function __get($name)
  3909. {
  3910. if($this->hasState($name))
  3911. return $this->getState($name);
  3912. else
  3913. return parent::__get($name);
  3914. }
  3915. public function __set($name,$value)
  3916. {
  3917. if($this->hasState($name))
  3918. $this->setState($name,$value);
  3919. else
  3920. parent::__set($name,$value);
  3921. }
  3922. public function __isset($name)
  3923. {
  3924. if($this->hasState($name))
  3925. return $this->getState($name)!==null;
  3926. else
  3927. return parent::__isset($name);
  3928. }
  3929. public function __unset($name)
  3930. {
  3931. if($this->hasState($name))
  3932. $this->setState($name,null);
  3933. else
  3934. parent::__unset($name);
  3935. }
  3936. public function init()
  3937. {
  3938. parent::init();
  3939. Yii::app()->getSession()->open();
  3940. if($this->getIsGuest() && $this->allowAutoLogin)
  3941. $this->restoreFromCookie();
  3942. elseif($this->autoRenewCookie && $this->allowAutoLogin)
  3943. $this->renewCookie();
  3944. if($this->autoUpdateFlash)
  3945. $this->updateFlash();
  3946. $this->updateAuthStatus();
  3947. }
  3948. public function login($identity,$duration=0)
  3949. {
  3950. $id=$identity->getId();
  3951. $states=$identity->getPersistentStates();
  3952. if($this->beforeLogin($id,$states,false))
  3953. {
  3954. $this->changeIdentity($id,$identity->getName(),$states);
  3955. if($duration>0)
  3956. {
  3957. if($this->allowAutoLogin)
  3958. $this->saveToCookie($duration);
  3959. else
  3960. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  3961. array('{class}'=>get_class($this))));
  3962. }
  3963. $this->afterLogin(false);
  3964. }
  3965. return !$this->getIsGuest();
  3966. }
  3967. public function logout($destroySession=true)
  3968. {
  3969. if($this->beforeLogout())
  3970. {
  3971. if($this->allowAutoLogin)
  3972. {
  3973. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  3974. if($this->identityCookie!==null)
  3975. {
  3976. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3977. $cookie->value=null;
  3978. $cookie->expire=0;
  3979. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  3980. }
  3981. }
  3982. if($destroySession)
  3983. Yii::app()->getSession()->destroy();
  3984. else
  3985. $this->clearStates();
  3986. $this->_access=array();
  3987. $this->afterLogout();
  3988. }
  3989. }
  3990. public function getIsGuest()
  3991. {
  3992. return $this->getState('__id')===null;
  3993. }
  3994. public function getId()
  3995. {
  3996. return $this->getState('__id');
  3997. }
  3998. public function setId($value)
  3999. {
  4000. $this->setState('__id',$value);
  4001. }
  4002. public function getName()
  4003. {
  4004. if(($name=$this->getState('__name'))!==null)
  4005. return $name;
  4006. else
  4007. return $this->guestName;
  4008. }
  4009. public function setName($value)
  4010. {
  4011. $this->setState('__name',$value);
  4012. }
  4013. public function getReturnUrl($defaultUrl=null)
  4014. {
  4015. if($defaultUrl===null)
  4016. {
  4017. $defaultReturnUrl=Yii::app()->getUrlManager()->showScriptName ? Yii::app()->getRequest()->getScriptUrl() : Yii::app()->getRequest()->getBaseUrl().'/';
  4018. }
  4019. else
  4020. {
  4021. $defaultReturnUrl=CHtml::normalizeUrl($defaultUrl);
  4022. }
  4023. return $this->getState('__returnUrl',$defaultReturnUrl);
  4024. }
  4025. public function setReturnUrl($value)
  4026. {
  4027. $this->setState('__returnUrl',$value);
  4028. }
  4029. public function loginRequired()
  4030. {
  4031. $app=Yii::app();
  4032. $request=$app->getRequest();
  4033. if(!$request->getIsAjaxRequest())
  4034. $this->setReturnUrl($request->getUrl());
  4035. elseif(isset($this->loginRequiredAjaxResponse))
  4036. {
  4037. echo $this->loginRequiredAjaxResponse;
  4038. Yii::app()->end();
  4039. }
  4040. if(($url=$this->loginUrl)!==null)
  4041. {
  4042. if(is_array($url))
  4043. {
  4044. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  4045. $url=$app->createUrl($route,array_splice($url,1));
  4046. }
  4047. $request->redirect($url);
  4048. }
  4049. else
  4050. throw new CHttpException(403,Yii::t('yii','Login Required'));
  4051. }
  4052. protected function beforeLogin($id,$states,$fromCookie)
  4053. {
  4054. return true;
  4055. }
  4056. protected function afterLogin($fromCookie)
  4057. {
  4058. }
  4059. protected function beforeLogout()
  4060. {
  4061. return true;
  4062. }
  4063. protected function afterLogout()
  4064. {
  4065. }
  4066. protected function restoreFromCookie()
  4067. {
  4068. $app=Yii::app();
  4069. $request=$app->getRequest();
  4070. $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  4071. if($cookie && !empty($cookie->value) && is_string($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  4072. {
  4073. $data=@unserialize($data);
  4074. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4075. {
  4076. list($id,$name,$duration,$states)=$data;
  4077. if($this->beforeLogin($id,$states,true))
  4078. {
  4079. $this->changeIdentity($id,$name,$states);
  4080. if($this->autoRenewCookie)
  4081. {
  4082. $cookie->expire=time()+$duration;
  4083. $request->getCookies()->add($cookie->name,$cookie);
  4084. }
  4085. $this->afterLogin(true);
  4086. }
  4087. }
  4088. }
  4089. }
  4090. protected function renewCookie()
  4091. {
  4092. $request=Yii::app()->getRequest();
  4093. $cookies=$request->getCookies();
  4094. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  4095. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  4096. {
  4097. $data=@unserialize($data);
  4098. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4099. {
  4100. $cookie->expire=time()+$data[2];
  4101. $cookies->add($cookie->name,$cookie);
  4102. }
  4103. }
  4104. }
  4105. protected function saveToCookie($duration)
  4106. {
  4107. $app=Yii::app();
  4108. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4109. $cookie->expire=time()+$duration;
  4110. $data=array(
  4111. $this->getId(),
  4112. $this->getName(),
  4113. $duration,
  4114. $this->saveIdentityStates(),
  4115. );
  4116. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  4117. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  4118. }
  4119. protected function createIdentityCookie($name)
  4120. {
  4121. $cookie=new CHttpCookie($name,'');
  4122. if(is_array($this->identityCookie))
  4123. {
  4124. foreach($this->identityCookie as $name=>$value)
  4125. $cookie->$name=$value;
  4126. }
  4127. return $cookie;
  4128. }
  4129. public function getStateKeyPrefix()
  4130. {
  4131. if($this->_keyPrefix!==null)
  4132. return $this->_keyPrefix;
  4133. else
  4134. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  4135. }
  4136. public function setStateKeyPrefix($value)
  4137. {
  4138. $this->_keyPrefix=$value;
  4139. }
  4140. public function getState($key,$defaultValue=null)
  4141. {
  4142. $key=$this->getStateKeyPrefix().$key;
  4143. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4144. }
  4145. public function setState($key,$value,$defaultValue=null)
  4146. {
  4147. $key=$this->getStateKeyPrefix().$key;
  4148. if($value===$defaultValue)
  4149. unset($_SESSION[$key]);
  4150. else
  4151. $_SESSION[$key]=$value;
  4152. }
  4153. public function hasState($key)
  4154. {
  4155. $key=$this->getStateKeyPrefix().$key;
  4156. return isset($_SESSION[$key]);
  4157. }
  4158. public function clearStates()
  4159. {
  4160. $keys=array_keys($_SESSION);
  4161. $prefix=$this->getStateKeyPrefix();
  4162. $n=strlen($prefix);
  4163. foreach($keys as $key)
  4164. {
  4165. if(!strncmp($key,$prefix,$n))
  4166. unset($_SESSION[$key]);
  4167. }
  4168. }
  4169. public function getFlashes($delete=true)
  4170. {
  4171. $flashes=array();
  4172. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  4173. $keys=array_keys($_SESSION);
  4174. $n=strlen($prefix);
  4175. foreach($keys as $key)
  4176. {
  4177. if(!strncmp($key,$prefix,$n))
  4178. {
  4179. $flashes[substr($key,$n)]=$_SESSION[$key];
  4180. if($delete)
  4181. unset($_SESSION[$key]);
  4182. }
  4183. }
  4184. if($delete)
  4185. $this->setState(self::FLASH_COUNTERS,array());
  4186. return $flashes;
  4187. }
  4188. public function getFlash($key,$defaultValue=null,$delete=true)
  4189. {
  4190. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4191. if($delete)
  4192. $this->setFlash($key,null);
  4193. return $value;
  4194. }
  4195. public function setFlash($key,$value,$defaultValue=null)
  4196. {
  4197. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4198. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4199. if($value===$defaultValue)
  4200. unset($counters[$key]);
  4201. else
  4202. $counters[$key]=0;
  4203. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4204. }
  4205. public function hasFlash($key)
  4206. {
  4207. return $this->getFlash($key, null, false)!==null;
  4208. }
  4209. protected function changeIdentity($id,$name,$states)
  4210. {
  4211. Yii::app()->getSession()->regenerateID(true);
  4212. $this->setId($id);
  4213. $this->setName($name);
  4214. $this->loadIdentityStates($states);
  4215. }
  4216. protected function saveIdentityStates()
  4217. {
  4218. $states=array();
  4219. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4220. $states[$name]=$this->getState($name);
  4221. return $states;
  4222. }
  4223. protected function loadIdentityStates($states)
  4224. {
  4225. $names=array();
  4226. if(is_array($states))
  4227. {
  4228. foreach($states as $name=>$value)
  4229. {
  4230. $this->setState($name,$value);
  4231. $names[$name]=true;
  4232. }
  4233. }
  4234. $this->setState(self::STATES_VAR,$names);
  4235. }
  4236. protected function updateFlash()
  4237. {
  4238. $counters=$this->getState(self::FLASH_COUNTERS);
  4239. if(!is_array($counters))
  4240. return;
  4241. foreach($counters as $key=>$count)
  4242. {
  4243. if($count)
  4244. {
  4245. unset($counters[$key]);
  4246. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4247. }
  4248. else
  4249. $counters[$key]++;
  4250. }
  4251. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4252. }
  4253. protected function updateAuthStatus()
  4254. {
  4255. if($this->authTimeout!==null && !$this->getIsGuest())
  4256. {
  4257. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4258. if ($expires!==null && $expires < time())
  4259. $this->logout(false);
  4260. else
  4261. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4262. }
  4263. }
  4264. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4265. {
  4266. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4267. return $this->_access[$operation];
  4268. $access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4269. if($allowCaching && $params===array())
  4270. $this->_access[$operation]=$access;
  4271. return $access;
  4272. }
  4273. }
  4274. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4275. {
  4276. public $autoStart=true;
  4277. public function init()
  4278. {
  4279. parent::init();
  4280. // default session gc probability is 1%
  4281. ini_set('session.gc_probability',1);
  4282. ini_set('session.gc_divisor',100);
  4283. if($this->autoStart)
  4284. $this->open();
  4285. register_shutdown_function(array($this,'close'));
  4286. }
  4287. public function getUseCustomStorage()
  4288. {
  4289. return false;
  4290. }
  4291. public function open()
  4292. {
  4293. if($this->getUseCustomStorage())
  4294. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4295. @session_start();
  4296. if(YII_DEBUG && session_id()=='')
  4297. {
  4298. $message=Yii::t('yii','Failed to start session.');
  4299. if(function_exists('error_get_last'))
  4300. {
  4301. $error=error_get_last();
  4302. if(isset($error['message']))
  4303. $message=$error['message'];
  4304. }
  4305. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4306. }
  4307. }
  4308. public function close()
  4309. {
  4310. if(session_id()!=='')
  4311. @session_write_close();
  4312. }
  4313. public function destroy()
  4314. {
  4315. if(session_id()!=='')
  4316. {
  4317. @session_unset();
  4318. @session_destroy();
  4319. }
  4320. }
  4321. public function getIsStarted()
  4322. {
  4323. return session_id()!=='';
  4324. }
  4325. public function getSessionID()
  4326. {
  4327. return session_id();
  4328. }
  4329. public function setSessionID($value)
  4330. {
  4331. session_id($value);
  4332. }
  4333. public function regenerateID($deleteOldSession=false)
  4334. {
  4335. session_regenerate_id($deleteOldSession);
  4336. }
  4337. public function getSessionName()
  4338. {
  4339. return session_name();
  4340. }
  4341. public function setSessionName($value)
  4342. {
  4343. session_name($value);
  4344. }
  4345. public function getSavePath()
  4346. {
  4347. return session_save_path();
  4348. }
  4349. public function setSavePath($value)
  4350. {
  4351. if(is_dir($value))
  4352. session_save_path($value);
  4353. else
  4354. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4355. array('{path}'=>$value)));
  4356. }
  4357. public function getCookieParams()
  4358. {
  4359. return session_get_cookie_params();
  4360. }
  4361. public function setCookieParams($value)
  4362. {
  4363. $data=session_get_cookie_params();
  4364. extract($data);
  4365. extract($value);
  4366. if(isset($httponly))
  4367. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4368. else
  4369. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4370. }
  4371. public function getCookieMode()
  4372. {
  4373. if(ini_get('session.use_cookies')==='0')
  4374. return 'none';
  4375. elseif(ini_get('session.use_only_cookies')==='0')
  4376. return 'allow';
  4377. else
  4378. return 'only';
  4379. }
  4380. public function setCookieMode($value)
  4381. {
  4382. if($value==='none')
  4383. {
  4384. ini_set('session.use_cookies','0');
  4385. ini_set('session.use_only_cookies','0');
  4386. }
  4387. elseif($value==='allow')
  4388. {
  4389. ini_set('session.use_cookies','1');
  4390. ini_set('session.use_only_cookies','0');
  4391. }
  4392. elseif($value==='only')
  4393. {
  4394. ini_set('session.use_cookies','1');
  4395. ini_set('session.use_only_cookies','1');
  4396. }
  4397. else
  4398. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4399. }
  4400. public function getGCProbability()
  4401. {
  4402. return (float)(ini_get('session.gc_probability')/ini_get('session.gc_divisor')*100);
  4403. }
  4404. public function setGCProbability($value)
  4405. {
  4406. if($value>=0 && $value<=100)
  4407. {
  4408. // percent * 21474837 / 2147483647 ≈ percent * 0.01
  4409. ini_set('session.gc_probability',floor($value*21474836.47));
  4410. ini_set('session.gc_divisor',2147483647);
  4411. }
  4412. else
  4413. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be a float between 0 and 100.',
  4414. array('{value}'=>$value)));
  4415. }
  4416. public function getUseTransparentSessionID()
  4417. {
  4418. return ini_get('session.use_trans_sid')==1;
  4419. }
  4420. public function setUseTransparentSessionID($value)
  4421. {
  4422. ini_set('session.use_trans_sid',$value?'1':'0');
  4423. }
  4424. public function getTimeout()
  4425. {
  4426. return (int)ini_get('session.gc_maxlifetime');
  4427. }
  4428. public function setTimeout($value)
  4429. {
  4430. ini_set('session.gc_maxlifetime',$value);
  4431. }
  4432. public function openSession($savePath,$sessionName)
  4433. {
  4434. return true;
  4435. }
  4436. public function closeSession()
  4437. {
  4438. return true;
  4439. }
  4440. public function readSession($id)
  4441. {
  4442. return '';
  4443. }
  4444. public function writeSession($id,$data)
  4445. {
  4446. return true;
  4447. }
  4448. public function destroySession($id)
  4449. {
  4450. return true;
  4451. }
  4452. public function gcSession($maxLifetime)
  4453. {
  4454. return true;
  4455. }
  4456. //------ The following methods enable CHttpSession to be CMap-like -----
  4457. public function getIterator()
  4458. {
  4459. return new CHttpSessionIterator;
  4460. }
  4461. public function getCount()
  4462. {
  4463. return count($_SESSION);
  4464. }
  4465. public function count()
  4466. {
  4467. return $this->getCount();
  4468. }
  4469. public function getKeys()
  4470. {
  4471. return array_keys($_SESSION);
  4472. }
  4473. public function get($key,$defaultValue=null)
  4474. {
  4475. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4476. }
  4477. public function itemAt($key)
  4478. {
  4479. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4480. }
  4481. public function add($key,$value)
  4482. {
  4483. $_SESSION[$key]=$value;
  4484. }
  4485. public function remove($key)
  4486. {
  4487. if(isset($_SESSION[$key]))
  4488. {
  4489. $value=$_SESSION[$key];
  4490. unset($_SESSION[$key]);
  4491. return $value;
  4492. }
  4493. else
  4494. return null;
  4495. }
  4496. public function clear()
  4497. {
  4498. foreach(array_keys($_SESSION) as $key)
  4499. unset($_SESSION[$key]);
  4500. }
  4501. public function contains($key)
  4502. {
  4503. return isset($_SESSION[$key]);
  4504. }
  4505. public function toArray()
  4506. {
  4507. return $_SESSION;
  4508. }
  4509. public function offsetExists($offset)
  4510. {
  4511. return isset($_SESSION[$offset]);
  4512. }
  4513. public function offsetGet($offset)
  4514. {
  4515. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4516. }
  4517. public function offsetSet($offset,$item)
  4518. {
  4519. $_SESSION[$offset]=$item;
  4520. }
  4521. public function offsetUnset($offset)
  4522. {
  4523. unset($_SESSION[$offset]);
  4524. }
  4525. }
  4526. class CHtml
  4527. {
  4528. const ID_PREFIX='yt';
  4529. public static $errorSummaryCss='errorSummary';
  4530. public static $errorMessageCss='errorMessage';
  4531. public static $errorCss='error';
  4532. public static $errorContainerTag='div';
  4533. public static $requiredCss='required';
  4534. public static $beforeRequiredLabel='';
  4535. public static $afterRequiredLabel=' <span class="required">*</span>';
  4536. public static $count=0;
  4537. public static $liveEvents=true;
  4538. public static $closeSingleTags=true;
  4539. public static $renderSpecialAttributesValue=true;
  4540. public static function encode($text)
  4541. {
  4542. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4543. }
  4544. public static function decode($text)
  4545. {
  4546. return htmlspecialchars_decode($text,ENT_QUOTES);
  4547. }
  4548. public static function encodeArray($data)
  4549. {
  4550. $d=array();
  4551. foreach($data as $key=>$value)
  4552. {
  4553. if(is_string($key))
  4554. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4555. if(is_string($value))
  4556. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4557. elseif(is_array($value))
  4558. $value=self::encodeArray($value);
  4559. $d[$key]=$value;
  4560. }
  4561. return $d;
  4562. }
  4563. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4564. {
  4565. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4566. if($content===false)
  4567. return $closeTag && self::$closeSingleTags ? $html.' />' : $html.'>';
  4568. else
  4569. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4570. }
  4571. public static function openTag($tag,$htmlOptions=array())
  4572. {
  4573. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4574. }
  4575. public static function closeTag($tag)
  4576. {
  4577. return '</'.$tag.'>';
  4578. }
  4579. public static function cdata($text)
  4580. {
  4581. return '<![CDATA[' . $text . ']]>';
  4582. }
  4583. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4584. {
  4585. if($name!==null)
  4586. $options['name']=$name;
  4587. if($httpEquiv!==null)
  4588. $options['http-equiv']=$httpEquiv;
  4589. $options['content']=$content;
  4590. return self::tag('meta',$options);
  4591. }
  4592. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4593. {
  4594. if($relation!==null)
  4595. $options['rel']=$relation;
  4596. if($type!==null)
  4597. $options['type']=$type;
  4598. if($href!==null)
  4599. $options['href']=$href;
  4600. if($media!==null)
  4601. $options['media']=$media;
  4602. return self::tag('link',$options);
  4603. }
  4604. public static function css($text,$media='')
  4605. {
  4606. if($media!=='')
  4607. $media=' media="'.$media.'"';
  4608. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4609. }
  4610. public static function refresh($seconds, $url='')
  4611. {
  4612. $content="$seconds";
  4613. if($url!=='')
  4614. $content.=';'.self::normalizeUrl($url);
  4615. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4616. }
  4617. public static function cssFile($url,$media='')
  4618. {
  4619. return CHtml::linkTag('stylesheet','text/css',$url,$media!=='' ? $media : null);
  4620. }
  4621. public static function script($text)
  4622. {
  4623. return "<script type=\"text/javascript\">\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</script>";
  4624. }
  4625. public static function scriptFile($url)
  4626. {
  4627. return '<script type="text/javascript" src="'.self::encode($url).'"></script>';
  4628. }
  4629. public static function form($action='',$method='post',$htmlOptions=array())
  4630. {
  4631. return self::beginForm($action,$method,$htmlOptions);
  4632. }
  4633. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4634. {
  4635. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4636. $htmlOptions['method']=$method;
  4637. $form=self::tag('form',$htmlOptions,false,false);
  4638. $hiddens=array();
  4639. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4640. {
  4641. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4642. {
  4643. if(($pos=strpos($pair,'='))!==false)
  4644. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4645. else
  4646. $hiddens[]=self::hiddenField(urldecode($pair),'',array('id'=>false));
  4647. }
  4648. }
  4649. $request=Yii::app()->request;
  4650. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4651. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4652. if($hiddens!==array())
  4653. $form.="\n".self::tag('div',array('style'=>'display:none'),implode("\n",$hiddens));
  4654. return $form;
  4655. }
  4656. public static function endForm()
  4657. {
  4658. return '</form>';
  4659. }
  4660. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4661. {
  4662. return self::form($action,$method,$htmlOptions)."\n".
  4663. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4664. }
  4665. public static function pageStateField($value)
  4666. {
  4667. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4668. }
  4669. public static function link($text,$url='#',$htmlOptions=array())
  4670. {
  4671. if($url!=='')
  4672. $htmlOptions['href']=self::normalizeUrl($url);
  4673. self::clientChange('click',$htmlOptions);
  4674. return self::tag('a',$htmlOptions,$text);
  4675. }
  4676. public static function mailto($text,$email='',$htmlOptions=array())
  4677. {
  4678. if($email==='')
  4679. $email=$text;
  4680. return self::link($text,'mailto:'.$email,$htmlOptions);
  4681. }
  4682. public static function image($src,$alt='',$htmlOptions=array())
  4683. {
  4684. $htmlOptions['src']=$src;
  4685. $htmlOptions['alt']=$alt;
  4686. return self::tag('img',$htmlOptions);
  4687. }
  4688. public static function button($label='button',$htmlOptions=array())
  4689. {
  4690. if(!isset($htmlOptions['name']))
  4691. {
  4692. if(!array_key_exists('name',$htmlOptions))
  4693. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4694. }
  4695. if(!isset($htmlOptions['type']))
  4696. $htmlOptions['type']='button';
  4697. if(!isset($htmlOptions['value']))
  4698. $htmlOptions['value']=$label;
  4699. self::clientChange('click',$htmlOptions);
  4700. return self::tag('input',$htmlOptions);
  4701. }
  4702. public static function htmlButton($label='button',$htmlOptions=array())
  4703. {
  4704. if(!isset($htmlOptions['name']))
  4705. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4706. if(!isset($htmlOptions['type']))
  4707. $htmlOptions['type']='button';
  4708. self::clientChange('click',$htmlOptions);
  4709. return self::tag('button',$htmlOptions,$label);
  4710. }
  4711. public static function submitButton($label='submit',$htmlOptions=array())
  4712. {
  4713. $htmlOptions['type']='submit';
  4714. return self::button($label,$htmlOptions);
  4715. }
  4716. public static function resetButton($label='reset',$htmlOptions=array())
  4717. {
  4718. $htmlOptions['type']='reset';
  4719. return self::button($label,$htmlOptions);
  4720. }
  4721. public static function imageButton($src,$htmlOptions=array())
  4722. {
  4723. $htmlOptions['src']=$src;
  4724. $htmlOptions['type']='image';
  4725. return self::button('submit',$htmlOptions);
  4726. }
  4727. public static function linkButton($label='submit',$htmlOptions=array())
  4728. {
  4729. if(!isset($htmlOptions['submit']))
  4730. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  4731. return self::link($label,'#',$htmlOptions);
  4732. }
  4733. public static function label($label,$for,$htmlOptions=array())
  4734. {
  4735. if($for===false)
  4736. unset($htmlOptions['for']);
  4737. else
  4738. $htmlOptions['for']=$for;
  4739. if(isset($htmlOptions['required']))
  4740. {
  4741. if($htmlOptions['required'])
  4742. {
  4743. if(isset($htmlOptions['class']))
  4744. $htmlOptions['class'].=' '.self::$requiredCss;
  4745. else
  4746. $htmlOptions['class']=self::$requiredCss;
  4747. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  4748. }
  4749. unset($htmlOptions['required']);
  4750. }
  4751. return self::tag('label',$htmlOptions,$label);
  4752. }
  4753. public static function textField($name,$value='',$htmlOptions=array())
  4754. {
  4755. self::clientChange('change',$htmlOptions);
  4756. return self::inputField('text',$name,$value,$htmlOptions);
  4757. }
  4758. public static function hiddenField($name,$value='',$htmlOptions=array())
  4759. {
  4760. return self::inputField('hidden',$name,$value,$htmlOptions);
  4761. }
  4762. public static function passwordField($name,$value='',$htmlOptions=array())
  4763. {
  4764. self::clientChange('change',$htmlOptions);
  4765. return self::inputField('password',$name,$value,$htmlOptions);
  4766. }
  4767. public static function fileField($name,$value='',$htmlOptions=array())
  4768. {
  4769. return self::inputField('file',$name,$value,$htmlOptions);
  4770. }
  4771. public static function textArea($name,$value='',$htmlOptions=array())
  4772. {
  4773. $htmlOptions['name']=$name;
  4774. if(!isset($htmlOptions['id']))
  4775. $htmlOptions['id']=self::getIdByName($name);
  4776. elseif($htmlOptions['id']===false)
  4777. unset($htmlOptions['id']);
  4778. self::clientChange('change',$htmlOptions);
  4779. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  4780. }
  4781. public static function radioButton($name,$checked=false,$htmlOptions=array())
  4782. {
  4783. if($checked)
  4784. $htmlOptions['checked']='checked';
  4785. else
  4786. unset($htmlOptions['checked']);
  4787. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4788. self::clientChange('click',$htmlOptions);
  4789. if(array_key_exists('uncheckValue',$htmlOptions))
  4790. {
  4791. $uncheck=$htmlOptions['uncheckValue'];
  4792. unset($htmlOptions['uncheckValue']);
  4793. }
  4794. else
  4795. $uncheck=null;
  4796. if($uncheck!==null)
  4797. {
  4798. // add a hidden field so that if the radio button is not selected, it still submits a value
  4799. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4800. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4801. else
  4802. $uncheckOptions=array('id'=>false);
  4803. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4804. }
  4805. else
  4806. $hidden='';
  4807. // add a hidden field so that if the radio button is not selected, it still submits a value
  4808. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  4809. }
  4810. public static function checkBox($name,$checked=false,$htmlOptions=array())
  4811. {
  4812. if($checked)
  4813. $htmlOptions['checked']='checked';
  4814. else
  4815. unset($htmlOptions['checked']);
  4816. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4817. self::clientChange('click',$htmlOptions);
  4818. if(array_key_exists('uncheckValue',$htmlOptions))
  4819. {
  4820. $uncheck=$htmlOptions['uncheckValue'];
  4821. unset($htmlOptions['uncheckValue']);
  4822. }
  4823. else
  4824. $uncheck=null;
  4825. if($uncheck!==null)
  4826. {
  4827. // add a hidden field so that if the check box is not checked, it still submits a value
  4828. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4829. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4830. else
  4831. $uncheckOptions=array('id'=>false);
  4832. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4833. }
  4834. else
  4835. $hidden='';
  4836. // add a hidden field so that if the check box is not checked, it still submits a value
  4837. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  4838. }
  4839. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  4840. {
  4841. $htmlOptions['name']=$name;
  4842. if(!isset($htmlOptions['id']))
  4843. $htmlOptions['id']=self::getIdByName($name);
  4844. elseif($htmlOptions['id']===false)
  4845. unset($htmlOptions['id']);
  4846. self::clientChange('change',$htmlOptions);
  4847. $options="\n".self::listOptions($select,$data,$htmlOptions);
  4848. $hidden='';
  4849. if(isset($htmlOptions['multiple']))
  4850. {
  4851. if(substr($htmlOptions['name'],-2)!=='[]')
  4852. $htmlOptions['name'].='[]';
  4853. if(isset($htmlOptions['unselectValue']))
  4854. {
  4855. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4856. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  4857. unset($htmlOptions['unselectValue']);
  4858. }
  4859. }
  4860. // add a hidden field so that if the option is not selected, it still submits a value
  4861. return $hidden . self::tag('select',$htmlOptions,$options);
  4862. }
  4863. public static function listBox($name,$select,$data,$htmlOptions=array())
  4864. {
  4865. if(!isset($htmlOptions['size']))
  4866. $htmlOptions['size']=4;
  4867. if(isset($htmlOptions['multiple']))
  4868. {
  4869. if(substr($name,-2)!=='[]')
  4870. $name.='[]';
  4871. }
  4872. return self::dropDownList($name,$select,$data,$htmlOptions);
  4873. }
  4874. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  4875. {
  4876. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4877. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4878. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  4879. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  4880. if(substr($name,-2)!=='[]')
  4881. $name.='[]';
  4882. if(isset($htmlOptions['checkAll']))
  4883. {
  4884. $checkAllLabel=$htmlOptions['checkAll'];
  4885. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  4886. }
  4887. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  4888. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4889. unset($htmlOptions['labelOptions']);
  4890. $items=array();
  4891. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  4892. unset($htmlOptions['baseID']);
  4893. $id=0;
  4894. $checkAll=true;
  4895. foreach($data as $value=>$label)
  4896. {
  4897. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  4898. $checkAll=$checkAll && $checked;
  4899. $htmlOptions['value']=$value;
  4900. $htmlOptions['id']=$baseID.'_'.$id++;
  4901. $option=self::checkBox($name,$checked,$htmlOptions);
  4902. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4903. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4904. }
  4905. if(isset($checkAllLabel))
  4906. {
  4907. $htmlOptions['value']=1;
  4908. $htmlOptions['id']=$id=$baseID.'_all';
  4909. $option=self::checkBox($id,$checkAll,$htmlOptions);
  4910. $label=self::label($checkAllLabel,$id,$labelOptions);
  4911. $item=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4912. if($checkAllLast)
  4913. $items[]=$item;
  4914. else
  4915. array_unshift($items,$item);
  4916. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  4917. $js=<<<EOD
  4918. jQuery('#$id').click(function() {
  4919. jQuery("input[name='$name']").prop('checked', this.checked);
  4920. });
  4921. jQuery("input[name='$name']").click(function() {
  4922. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  4923. });
  4924. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  4925. EOD;
  4926. $cs=Yii::app()->getClientScript();
  4927. $cs->registerCoreScript('jquery');
  4928. $cs->registerScript($id,$js);
  4929. }
  4930. if(empty($container))
  4931. return implode($separator,$items);
  4932. else
  4933. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  4934. }
  4935. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  4936. {
  4937. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4938. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4939. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  4940. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  4941. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4942. unset($htmlOptions['labelOptions']);
  4943. $items=array();
  4944. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  4945. unset($htmlOptions['baseID']);
  4946. $id=0;
  4947. foreach($data as $value=>$label)
  4948. {
  4949. $checked=!strcmp($value,$select);
  4950. $htmlOptions['value']=$value;
  4951. $htmlOptions['id']=$baseID.'_'.$id++;
  4952. $option=self::radioButton($name,$checked,$htmlOptions);
  4953. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4954. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4955. }
  4956. if(empty($container))
  4957. return implode($separator,$items);
  4958. else
  4959. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  4960. }
  4961. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  4962. {
  4963. if(!isset($htmlOptions['href']))
  4964. $htmlOptions['href']='#';
  4965. $ajaxOptions['url']=$url;
  4966. $htmlOptions['ajax']=$ajaxOptions;
  4967. self::clientChange('click',$htmlOptions);
  4968. return self::tag('a',$htmlOptions,$text);
  4969. }
  4970. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4971. {
  4972. $ajaxOptions['url']=$url;
  4973. $htmlOptions['ajax']=$ajaxOptions;
  4974. return self::button($label,$htmlOptions);
  4975. }
  4976. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4977. {
  4978. $ajaxOptions['type']='POST';
  4979. $htmlOptions['type']='submit';
  4980. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  4981. }
  4982. public static function ajax($options)
  4983. {
  4984. Yii::app()->getClientScript()->registerCoreScript('jquery');
  4985. if(!isset($options['url']))
  4986. $options['url']=new CJavaScriptExpression('location.href');
  4987. else
  4988. $options['url']=self::normalizeUrl($options['url']);
  4989. if(!isset($options['cache']))
  4990. $options['cache']=false;
  4991. if(!isset($options['data']) && isset($options['type']))
  4992. $options['data']=new CJavaScriptExpression('jQuery(this).parents("form").serialize()');
  4993. foreach(array('beforeSend','complete','error','success') as $name)
  4994. {
  4995. if(isset($options[$name]) && !($options[$name] instanceof CJavaScriptExpression))
  4996. $options[$name]=new CJavaScriptExpression($options[$name]);
  4997. }
  4998. if(isset($options['update']))
  4999. {
  5000. if(!isset($options['success']))
  5001. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['update'].'").html(html)}');
  5002. unset($options['update']);
  5003. }
  5004. if(isset($options['replace']))
  5005. {
  5006. if(!isset($options['success']))
  5007. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['replace'].'").replaceWith(html)}');
  5008. unset($options['replace']);
  5009. }
  5010. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  5011. }
  5012. public static function asset($path,$hashByName=false)
  5013. {
  5014. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  5015. }
  5016. public static function normalizeUrl($url)
  5017. {
  5018. if(is_array($url))
  5019. {
  5020. if(isset($url[0]))
  5021. {
  5022. if(($c=Yii::app()->getController())!==null)
  5023. $url=$c->createUrl($url[0],array_splice($url,1));
  5024. else
  5025. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  5026. }
  5027. else
  5028. $url='';
  5029. }
  5030. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  5031. }
  5032. protected static function inputField($type,$name,$value,$htmlOptions)
  5033. {
  5034. $htmlOptions['type']=$type;
  5035. $htmlOptions['value']=$value;
  5036. $htmlOptions['name']=$name;
  5037. if(!isset($htmlOptions['id']))
  5038. $htmlOptions['id']=self::getIdByName($name);
  5039. elseif($htmlOptions['id']===false)
  5040. unset($htmlOptions['id']);
  5041. return self::tag('input',$htmlOptions);
  5042. }
  5043. public static function activeLabel($model,$attribute,$htmlOptions=array())
  5044. {
  5045. if(isset($htmlOptions['for']))
  5046. {
  5047. $for=$htmlOptions['for'];
  5048. unset($htmlOptions['for']);
  5049. }
  5050. else
  5051. $for=self::getIdByName(self::resolveName($model,$attribute));
  5052. if(isset($htmlOptions['label']))
  5053. {
  5054. if(($label=$htmlOptions['label'])===false)
  5055. return '';
  5056. unset($htmlOptions['label']);
  5057. }
  5058. else
  5059. $label=$model->getAttributeLabel($attribute);
  5060. if($model->hasErrors($attribute))
  5061. self::addErrorCss($htmlOptions);
  5062. return self::label($label,$for,$htmlOptions);
  5063. }
  5064. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  5065. {
  5066. $realAttribute=$attribute;
  5067. self::resolveName($model,$attribute); // strip off square brackets if any
  5068. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  5069. return self::activeLabel($model,$realAttribute,$htmlOptions);
  5070. }
  5071. public static function activeTextField($model,$attribute,$htmlOptions=array())
  5072. {
  5073. self::resolveNameID($model,$attribute,$htmlOptions);
  5074. self::clientChange('change',$htmlOptions);
  5075. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  5076. }
  5077. public static function activeUrlField($model,$attribute,$htmlOptions=array())
  5078. {
  5079. self::resolveNameID($model,$attribute,$htmlOptions);
  5080. self::clientChange('change',$htmlOptions);
  5081. return self::activeInputField('url',$model,$attribute,$htmlOptions);
  5082. }
  5083. public static function activeEmailField($model,$attribute,$htmlOptions=array())
  5084. {
  5085. self::resolveNameID($model,$attribute,$htmlOptions);
  5086. self::clientChange('change',$htmlOptions);
  5087. return self::activeInputField('email',$model,$attribute,$htmlOptions);
  5088. }
  5089. public static function activeNumberField($model,$attribute,$htmlOptions=array())
  5090. {
  5091. self::resolveNameID($model,$attribute,$htmlOptions);
  5092. self::clientChange('change',$htmlOptions);
  5093. return self::activeInputField('number',$model,$attribute,$htmlOptions);
  5094. }
  5095. public static function activeRangeField($model,$attribute,$htmlOptions=array())
  5096. {
  5097. self::resolveNameID($model,$attribute,$htmlOptions);
  5098. self::clientChange('change',$htmlOptions);
  5099. return self::activeInputField('range',$model,$attribute,$htmlOptions);
  5100. }
  5101. public static function activeDateField($model,$attribute,$htmlOptions=array())
  5102. {
  5103. self::resolveNameID($model,$attribute,$htmlOptions);
  5104. self::clientChange('change',$htmlOptions);
  5105. return self::activeInputField('date',$model,$attribute,$htmlOptions);
  5106. }
  5107. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  5108. {
  5109. self::resolveNameID($model,$attribute,$htmlOptions);
  5110. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  5111. }
  5112. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  5113. {
  5114. self::resolveNameID($model,$attribute,$htmlOptions);
  5115. self::clientChange('change',$htmlOptions);
  5116. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  5117. }
  5118. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  5119. {
  5120. self::resolveNameID($model,$attribute,$htmlOptions);
  5121. self::clientChange('change',$htmlOptions);
  5122. if($model->hasErrors($attribute))
  5123. self::addErrorCss($htmlOptions);
  5124. if(isset($htmlOptions['value']))
  5125. {
  5126. $text=$htmlOptions['value'];
  5127. unset($htmlOptions['value']);
  5128. }
  5129. else
  5130. $text=self::resolveValue($model,$attribute);
  5131. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  5132. }
  5133. public static function activeFileField($model,$attribute,$htmlOptions=array())
  5134. {
  5135. self::resolveNameID($model,$attribute,$htmlOptions);
  5136. // add a hidden field so that if a model only has a file field, we can
  5137. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  5138. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5139. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  5140. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  5141. }
  5142. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  5143. {
  5144. self::resolveNameID($model,$attribute,$htmlOptions);
  5145. if(!isset($htmlOptions['value']))
  5146. $htmlOptions['value']=1;
  5147. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5148. $htmlOptions['checked']='checked';
  5149. self::clientChange('click',$htmlOptions);
  5150. if(array_key_exists('uncheckValue',$htmlOptions))
  5151. {
  5152. $uncheck=$htmlOptions['uncheckValue'];
  5153. unset($htmlOptions['uncheckValue']);
  5154. }
  5155. else
  5156. $uncheck='0';
  5157. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5158. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5159. // add a hidden field so that if the radio button is not selected, it still submits a value
  5160. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  5161. }
  5162. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  5163. {
  5164. self::resolveNameID($model,$attribute,$htmlOptions);
  5165. if(!isset($htmlOptions['value']))
  5166. $htmlOptions['value']=1;
  5167. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5168. $htmlOptions['checked']='checked';
  5169. self::clientChange('click',$htmlOptions);
  5170. if(array_key_exists('uncheckValue',$htmlOptions))
  5171. {
  5172. $uncheck=$htmlOptions['uncheckValue'];
  5173. unset($htmlOptions['uncheckValue']);
  5174. }
  5175. else
  5176. $uncheck='0';
  5177. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5178. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5179. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  5180. }
  5181. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  5182. {
  5183. self::resolveNameID($model,$attribute,$htmlOptions);
  5184. $selection=self::resolveValue($model,$attribute);
  5185. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  5186. self::clientChange('change',$htmlOptions);
  5187. if($model->hasErrors($attribute))
  5188. self::addErrorCss($htmlOptions);
  5189. $hidden='';
  5190. if(isset($htmlOptions['multiple']))
  5191. {
  5192. if(substr($htmlOptions['name'],-2)!=='[]')
  5193. $htmlOptions['name'].='[]';
  5194. if(isset($htmlOptions['unselectValue']))
  5195. {
  5196. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5197. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  5198. unset($htmlOptions['unselectValue']);
  5199. }
  5200. }
  5201. return $hidden . self::tag('select',$htmlOptions,$options);
  5202. }
  5203. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  5204. {
  5205. if(!isset($htmlOptions['size']))
  5206. $htmlOptions['size']=4;
  5207. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  5208. }
  5209. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  5210. {
  5211. self::resolveNameID($model,$attribute,$htmlOptions);
  5212. $selection=self::resolveValue($model,$attribute);
  5213. if($model->hasErrors($attribute))
  5214. self::addErrorCss($htmlOptions);
  5215. $name=$htmlOptions['name'];
  5216. unset($htmlOptions['name']);
  5217. if(array_key_exists('uncheckValue',$htmlOptions))
  5218. {
  5219. $uncheck=$htmlOptions['uncheckValue'];
  5220. unset($htmlOptions['uncheckValue']);
  5221. }
  5222. else
  5223. $uncheck='';
  5224. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5225. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5226. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  5227. }
  5228. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  5229. {
  5230. self::resolveNameID($model,$attribute,$htmlOptions);
  5231. $selection=self::resolveValue($model,$attribute);
  5232. if($model->hasErrors($attribute))
  5233. self::addErrorCss($htmlOptions);
  5234. $name=$htmlOptions['name'];
  5235. unset($htmlOptions['name']);
  5236. if(array_key_exists('uncheckValue',$htmlOptions))
  5237. {
  5238. $uncheck=$htmlOptions['uncheckValue'];
  5239. unset($htmlOptions['uncheckValue']);
  5240. }
  5241. else
  5242. $uncheck='';
  5243. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5244. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5245. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  5246. }
  5247. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  5248. {
  5249. $content='';
  5250. if(!is_array($model))
  5251. $model=array($model);
  5252. if(isset($htmlOptions['firstError']))
  5253. {
  5254. $firstError=$htmlOptions['firstError'];
  5255. unset($htmlOptions['firstError']);
  5256. }
  5257. else
  5258. $firstError=false;
  5259. foreach($model as $m)
  5260. {
  5261. foreach($m->getErrors() as $errors)
  5262. {
  5263. foreach($errors as $error)
  5264. {
  5265. if($error!='')
  5266. $content.="<li>$error</li>\n";
  5267. if($firstError)
  5268. break;
  5269. }
  5270. }
  5271. }
  5272. if($content!=='')
  5273. {
  5274. if($header===null)
  5275. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5276. if(!isset($htmlOptions['class']))
  5277. $htmlOptions['class']=self::$errorSummaryCss;
  5278. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5279. }
  5280. else
  5281. return '';
  5282. }
  5283. public static function error($model,$attribute,$htmlOptions=array())
  5284. {
  5285. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5286. $error=$model->getError($attribute);
  5287. if($error!='')
  5288. {
  5289. if(!isset($htmlOptions['class']))
  5290. $htmlOptions['class']=self::$errorMessageCss;
  5291. return self::tag(self::$errorContainerTag,$htmlOptions,$error);
  5292. }
  5293. else
  5294. return '';
  5295. }
  5296. public static function listData($models,$valueField,$textField,$groupField='')
  5297. {
  5298. $listData=array();
  5299. if($groupField==='')
  5300. {
  5301. foreach($models as $model)
  5302. {
  5303. $value=self::value($model,$valueField);
  5304. $text=self::value($model,$textField);
  5305. $listData[$value]=$text;
  5306. }
  5307. }
  5308. else
  5309. {
  5310. foreach($models as $model)
  5311. {
  5312. $group=self::value($model,$groupField);
  5313. $value=self::value($model,$valueField);
  5314. $text=self::value($model,$textField);
  5315. if($group===null)
  5316. $listData[$value]=$text;
  5317. else
  5318. $listData[$group][$value]=$text;
  5319. }
  5320. }
  5321. return $listData;
  5322. }
  5323. public static function value($model,$attribute,$defaultValue=null)
  5324. {
  5325. if(is_scalar($attribute) || $attribute===null)
  5326. foreach(explode('.',$attribute) as $name)
  5327. {
  5328. if(is_object($model) && isset($model->$name))
  5329. $model=$model->$name;
  5330. elseif(is_array($model) && isset($model[$name]))
  5331. $model=$model[$name];
  5332. else
  5333. return $defaultValue;
  5334. }
  5335. else
  5336. return call_user_func($attribute,$model);
  5337. return $model;
  5338. }
  5339. public static function getIdByName($name)
  5340. {
  5341. return str_replace(array('[]', '][', '[', ']', ' '), array('', '_', '_', '', '_'), $name);
  5342. }
  5343. public static function activeId($model,$attribute)
  5344. {
  5345. return self::getIdByName(self::activeName($model,$attribute));
  5346. }
  5347. public static function activeName($model,$attribute)
  5348. {
  5349. $a=$attribute; // because the attribute name may be changed by resolveName
  5350. return self::resolveName($model,$a);
  5351. }
  5352. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5353. {
  5354. $htmlOptions['type']=$type;
  5355. if($type==='text' || $type==='password')
  5356. {
  5357. if(!isset($htmlOptions['maxlength']))
  5358. {
  5359. foreach($model->getValidators($attribute) as $validator)
  5360. {
  5361. if($validator instanceof CStringValidator && $validator->max!==null)
  5362. {
  5363. $htmlOptions['maxlength']=$validator->max;
  5364. break;
  5365. }
  5366. }
  5367. }
  5368. elseif($htmlOptions['maxlength']===false)
  5369. unset($htmlOptions['maxlength']);
  5370. }
  5371. if($type==='file')
  5372. unset($htmlOptions['value']);
  5373. elseif(!isset($htmlOptions['value']))
  5374. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5375. if($model->hasErrors($attribute))
  5376. self::addErrorCss($htmlOptions);
  5377. return self::tag('input',$htmlOptions);
  5378. }
  5379. public static function listOptions($selection,$listData,&$htmlOptions)
  5380. {
  5381. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5382. $content='';
  5383. if(isset($htmlOptions['prompt']))
  5384. {
  5385. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5386. unset($htmlOptions['prompt']);
  5387. }
  5388. if(isset($htmlOptions['empty']))
  5389. {
  5390. if(!is_array($htmlOptions['empty']))
  5391. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5392. foreach($htmlOptions['empty'] as $value=>$label)
  5393. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5394. unset($htmlOptions['empty']);
  5395. }
  5396. if(isset($htmlOptions['options']))
  5397. {
  5398. $options=$htmlOptions['options'];
  5399. unset($htmlOptions['options']);
  5400. }
  5401. else
  5402. $options=array();
  5403. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  5404. if(is_array($selection))
  5405. {
  5406. foreach($selection as $i=>$item)
  5407. {
  5408. if(is_object($item))
  5409. $selection[$i]=$item->$key;
  5410. }
  5411. }
  5412. elseif(is_object($selection))
  5413. $selection=$selection->$key;
  5414. foreach($listData as $key=>$value)
  5415. {
  5416. if(is_array($value))
  5417. {
  5418. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  5419. $dummy=array('options'=>$options);
  5420. if(isset($htmlOptions['encode']))
  5421. $dummy['encode']=$htmlOptions['encode'];
  5422. $content.=self::listOptions($selection,$value,$dummy);
  5423. $content.='</optgroup>'."\n";
  5424. }
  5425. else
  5426. {
  5427. $attributes=array('value'=>(string)$key, 'encode'=>!$raw);
  5428. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  5429. $attributes['selected']='selected';
  5430. if(isset($options[$key]))
  5431. $attributes=array_merge($attributes,$options[$key]);
  5432. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  5433. }
  5434. }
  5435. unset($htmlOptions['key']);
  5436. return $content;
  5437. }
  5438. protected static function clientChange($event,&$htmlOptions)
  5439. {
  5440. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  5441. return;
  5442. if(isset($htmlOptions['live']))
  5443. {
  5444. $live=$htmlOptions['live'];
  5445. unset($htmlOptions['live']);
  5446. }
  5447. else
  5448. $live = self::$liveEvents;
  5449. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  5450. $return='return true';
  5451. else
  5452. $return='return false';
  5453. if(isset($htmlOptions['on'.$event]))
  5454. {
  5455. $handler=trim($htmlOptions['on'.$event],';').';';
  5456. unset($htmlOptions['on'.$event]);
  5457. }
  5458. else
  5459. $handler='';
  5460. if(isset($htmlOptions['id']))
  5461. $id=$htmlOptions['id'];
  5462. else
  5463. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  5464. $cs=Yii::app()->getClientScript();
  5465. $cs->registerCoreScript('jquery');
  5466. if(isset($htmlOptions['submit']))
  5467. {
  5468. $cs->registerCoreScript('yii');
  5469. $request=Yii::app()->getRequest();
  5470. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  5471. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  5472. if(isset($htmlOptions['params']))
  5473. $params=CJavaScript::encode($htmlOptions['params']);
  5474. else
  5475. $params='{}';
  5476. if($htmlOptions['submit']!=='')
  5477. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  5478. else
  5479. $url='';
  5480. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  5481. }
  5482. if(isset($htmlOptions['ajax']))
  5483. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  5484. if(isset($htmlOptions['confirm']))
  5485. {
  5486. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  5487. if($handler!=='')
  5488. $handler="if($confirm) {".$handler."} else return false;";
  5489. else
  5490. $handler="return $confirm;";
  5491. }
  5492. if($live)
  5493. $cs->registerScript('Yii.CHtml.#' . $id, "jQuery('body').on('$event','#$id',function(){{$handler}});");
  5494. else
  5495. $cs->registerScript('Yii.CHtml.#' . $id, "jQuery('#$id').on('$event', function(){{$handler}});");
  5496. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  5497. }
  5498. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  5499. {
  5500. if(!isset($htmlOptions['name']))
  5501. $htmlOptions['name']=self::resolveName($model,$attribute);
  5502. if(!isset($htmlOptions['id']))
  5503. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  5504. elseif($htmlOptions['id']===false)
  5505. unset($htmlOptions['id']);
  5506. }
  5507. public static function resolveName($model,&$attribute)
  5508. {
  5509. if(($pos=strpos($attribute,'['))!==false)
  5510. {
  5511. if($pos!==0) // e.g. name[a][b]
  5512. return get_class($model).'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5513. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5514. {
  5515. $sub=substr($attribute,0,$pos+1);
  5516. $attribute=substr($attribute,$pos+1);
  5517. return get_class($model).$sub.'['.$attribute.']';
  5518. }
  5519. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5520. {
  5521. $name=get_class($model).'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5522. $attribute=$matches[1];
  5523. return $name;
  5524. }
  5525. }
  5526. return get_class($model).'['.$attribute.']';
  5527. }
  5528. public static function resolveValue($model,$attribute)
  5529. {
  5530. if(($pos=strpos($attribute,'['))!==false)
  5531. {
  5532. if($pos===0) // [a]name[b][c], should ignore [a]
  5533. {
  5534. if(preg_match('/\](\w+(\[.+)?)/',$attribute,$matches))
  5535. $attribute=$matches[1]; // we get: name[b][c]
  5536. if(($pos=strpos($attribute,'['))===false)
  5537. return $model->$attribute;
  5538. }
  5539. $name=substr($attribute,0,$pos);
  5540. $value=$model->$name;
  5541. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5542. {
  5543. if((is_array($value) || $value instanceof ArrayAccess) && isset($value[$id]))
  5544. $value=$value[$id];
  5545. else
  5546. return null;
  5547. }
  5548. return $value;
  5549. }
  5550. else
  5551. return $model->$attribute;
  5552. }
  5553. protected static function addErrorCss(&$htmlOptions)
  5554. {
  5555. if(empty(self::$errorCss))
  5556. return;
  5557. if(isset($htmlOptions['class']))
  5558. $htmlOptions['class'].=' '.self::$errorCss;
  5559. else
  5560. $htmlOptions['class']=self::$errorCss;
  5561. }
  5562. public static function renderAttributes($htmlOptions)
  5563. {
  5564. static $specialAttributes=array(
  5565. 'async'=>1,
  5566. 'autofocus'=>1,
  5567. 'autoplay'=>1,
  5568. 'checked'=>1,
  5569. 'controls'=>1,
  5570. 'declare'=>1,
  5571. 'default'=>1,
  5572. 'defer'=>1,
  5573. 'disabled'=>1,
  5574. 'formnovalidate'=>1,
  5575. 'hidden'=>1,
  5576. 'ismap'=>1,
  5577. 'loop'=>1,
  5578. 'multiple'=>1,
  5579. 'muted'=>1,
  5580. 'nohref'=>1,
  5581. 'noresize'=>1,
  5582. 'novalidate'=>1,
  5583. 'open'=>1,
  5584. 'readonly'=>1,
  5585. 'required'=>1,
  5586. 'reversed'=>1,
  5587. 'scoped'=>1,
  5588. 'seamless'=>1,
  5589. 'selected'=>1,
  5590. 'typemustmatch'=>1,
  5591. );
  5592. if($htmlOptions===array())
  5593. return '';
  5594. $html='';
  5595. if(isset($htmlOptions['encode']))
  5596. {
  5597. $raw=!$htmlOptions['encode'];
  5598. unset($htmlOptions['encode']);
  5599. }
  5600. else
  5601. $raw=false;
  5602. foreach($htmlOptions as $name=>$value)
  5603. {
  5604. if(isset($specialAttributes[$name]))
  5605. {
  5606. if($value)
  5607. {
  5608. $html .= ' ' . $name;
  5609. if(self::$renderSpecialAttributesValue)
  5610. $html .= '="' . $name . '"';
  5611. }
  5612. }
  5613. elseif($value!==null)
  5614. $html .= ' ' . $name . '="' . ($raw ? $value : self::encode($value)) . '"';
  5615. }
  5616. return $html;
  5617. }
  5618. }
  5619. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  5620. {
  5621. public $enableSkin=false;
  5622. public $widgets=array();
  5623. public $skinnableWidgets;
  5624. public $skinPath;
  5625. private $_skins=array(); // class name, skin name, property name => value
  5626. public function init()
  5627. {
  5628. parent::init();
  5629. if($this->enableSkin && $this->skinPath===null)
  5630. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  5631. }
  5632. public function createWidget($owner,$className,$properties=array())
  5633. {
  5634. $className=Yii::import($className,true);
  5635. $widget=new $className($owner);
  5636. if(isset($this->widgets[$className]))
  5637. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  5638. if($this->enableSkin)
  5639. {
  5640. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  5641. {
  5642. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  5643. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  5644. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  5645. }
  5646. }
  5647. foreach($properties as $name=>$value)
  5648. $widget->$name=$value;
  5649. return $widget;
  5650. }
  5651. protected function getSkin($className,$skinName)
  5652. {
  5653. if(!isset($this->_skins[$className][$skinName]))
  5654. {
  5655. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  5656. if(is_file($skinFile))
  5657. $this->_skins[$className]=require($skinFile);
  5658. else
  5659. $this->_skins[$className]=array();
  5660. if(($theme=Yii::app()->getTheme())!==null)
  5661. {
  5662. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  5663. if(is_file($skinFile))
  5664. {
  5665. $skins=require($skinFile);
  5666. foreach($skins as $name=>$skin)
  5667. $this->_skins[$className][$name]=$skin;
  5668. }
  5669. }
  5670. if(!isset($this->_skins[$className][$skinName]))
  5671. $this->_skins[$className][$skinName]=array();
  5672. }
  5673. return $this->_skins[$className][$skinName];
  5674. }
  5675. }
  5676. class CWidget extends CBaseController
  5677. {
  5678. public $actionPrefix;
  5679. public $skin='default';
  5680. private static $_viewPaths;
  5681. private static $_counter=0;
  5682. private $_id;
  5683. private $_owner;
  5684. public static function actions()
  5685. {
  5686. return array();
  5687. }
  5688. public function __construct($owner=null)
  5689. {
  5690. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  5691. }
  5692. public function getOwner()
  5693. {
  5694. return $this->_owner;
  5695. }
  5696. public function getId($autoGenerate=true)
  5697. {
  5698. if($this->_id!==null)
  5699. return $this->_id;
  5700. elseif($autoGenerate)
  5701. return $this->_id='yw'.self::$_counter++;
  5702. }
  5703. public function setId($value)
  5704. {
  5705. $this->_id=$value;
  5706. }
  5707. public function getController()
  5708. {
  5709. if($this->_owner instanceof CController)
  5710. return $this->_owner;
  5711. else
  5712. return Yii::app()->getController();
  5713. }
  5714. public function init()
  5715. {
  5716. }
  5717. public function run()
  5718. {
  5719. }
  5720. public function getViewPath($checkTheme=false)
  5721. {
  5722. $className=get_class($this);
  5723. if(isset(self::$_viewPaths[$className]))
  5724. return self::$_viewPaths[$className];
  5725. else
  5726. {
  5727. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  5728. {
  5729. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  5730. if(strpos($className,'\\')!==false) // namespaced class
  5731. $path.=str_replace('\\','_',ltrim($className,'\\'));
  5732. else
  5733. $path.=$className;
  5734. if(is_dir($path))
  5735. return self::$_viewPaths[$className]=$path;
  5736. }
  5737. $class=new ReflectionClass($className);
  5738. return self::$_viewPaths[$className]=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  5739. }
  5740. }
  5741. public function getViewFile($viewName)
  5742. {
  5743. if(($renderer=Yii::app()->getViewRenderer())!==null)
  5744. $extension=$renderer->fileExtension;
  5745. else
  5746. $extension='.php';
  5747. if(strpos($viewName,'.')) // a path alias
  5748. $viewFile=Yii::getPathOfAlias($viewName);
  5749. else
  5750. {
  5751. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  5752. if(is_file($viewFile.$extension))
  5753. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5754. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  5755. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5756. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  5757. }
  5758. if(is_file($viewFile.$extension))
  5759. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5760. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  5761. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5762. else
  5763. return false;
  5764. }
  5765. public function render($view,$data=null,$return=false)
  5766. {
  5767. if(($viewFile=$this->getViewFile($view))!==false)
  5768. return $this->renderFile($viewFile,$data,$return);
  5769. else
  5770. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  5771. array('{widget}'=>get_class($this), '{view}'=>$view)));
  5772. }
  5773. }
  5774. class CClientScript extends CApplicationComponent
  5775. {
  5776. const POS_HEAD=0;
  5777. const POS_BEGIN=1;
  5778. const POS_END=2;
  5779. const POS_LOAD=3;
  5780. const POS_READY=4;
  5781. public $enableJavaScript=true;
  5782. public $scriptMap=array();
  5783. public $packages=array();
  5784. public $corePackages;
  5785. public $scripts=array();
  5786. protected $cssFiles=array();
  5787. protected $scriptFiles=array();
  5788. protected $metaTags=array();
  5789. protected $linkTags=array();
  5790. protected $css=array();
  5791. protected $hasScripts=false;
  5792. protected $coreScripts=array();
  5793. public $coreScriptPosition=self::POS_HEAD;
  5794. public $defaultScriptFilePosition=self::POS_HEAD;
  5795. public $defaultScriptPosition=self::POS_READY;
  5796. private $_baseUrl;
  5797. public function reset()
  5798. {
  5799. $this->hasScripts=false;
  5800. $this->coreScripts=array();
  5801. $this->cssFiles=array();
  5802. $this->css=array();
  5803. $this->scriptFiles=array();
  5804. $this->scripts=array();
  5805. $this->metaTags=array();
  5806. $this->linkTags=array();
  5807. $this->recordCachingAction('clientScript','reset',array());
  5808. }
  5809. public function render(&$output)
  5810. {
  5811. if(!$this->hasScripts)
  5812. return;
  5813. $this->renderCoreScripts();
  5814. if(!empty($this->scriptMap))
  5815. $this->remapScripts();
  5816. $this->unifyScripts();
  5817. $this->renderHead($output);
  5818. if($this->enableJavaScript)
  5819. {
  5820. $this->renderBodyBegin($output);
  5821. $this->renderBodyEnd($output);
  5822. }
  5823. }
  5824. protected function unifyScripts()
  5825. {
  5826. if(!$this->enableJavaScript)
  5827. return;
  5828. $map=array();
  5829. if(isset($this->scriptFiles[self::POS_HEAD]))
  5830. $map=$this->scriptFiles[self::POS_HEAD];
  5831. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5832. {
  5833. foreach($this->scriptFiles[self::POS_BEGIN] as $key=>$scriptFile)
  5834. {
  5835. if(isset($map[$scriptFile]))
  5836. unset($this->scriptFiles[self::POS_BEGIN][$key]);
  5837. else
  5838. $map[$scriptFile]=true;
  5839. }
  5840. }
  5841. if(isset($this->scriptFiles[self::POS_END]))
  5842. {
  5843. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  5844. {
  5845. if(isset($map[$scriptFile]))
  5846. unset($this->scriptFiles[self::POS_END][$key]);
  5847. }
  5848. }
  5849. }
  5850. protected function remapScripts()
  5851. {
  5852. $cssFiles=array();
  5853. foreach($this->cssFiles as $url=>$media)
  5854. {
  5855. $name=basename($url);
  5856. if(isset($this->scriptMap[$name]))
  5857. {
  5858. if($this->scriptMap[$name]!==false)
  5859. $cssFiles[$this->scriptMap[$name]]=$media;
  5860. }
  5861. elseif(isset($this->scriptMap['*.css']))
  5862. {
  5863. if($this->scriptMap['*.css']!==false)
  5864. $cssFiles[$this->scriptMap['*.css']]=$media;
  5865. }
  5866. else
  5867. $cssFiles[$url]=$media;
  5868. }
  5869. $this->cssFiles=$cssFiles;
  5870. $jsFiles=array();
  5871. foreach($this->scriptFiles as $position=>$scripts)
  5872. {
  5873. $jsFiles[$position]=array();
  5874. foreach($scripts as $key=>$script)
  5875. {
  5876. $name=basename($script);
  5877. if(isset($this->scriptMap[$name]))
  5878. {
  5879. if($this->scriptMap[$name]!==false)
  5880. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  5881. }
  5882. elseif(isset($this->scriptMap['*.js']))
  5883. {
  5884. if($this->scriptMap['*.js']!==false)
  5885. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  5886. }
  5887. else
  5888. $jsFiles[$position][$key]=$script;
  5889. }
  5890. }
  5891. $this->scriptFiles=$jsFiles;
  5892. }
  5893. public function renderCoreScripts()
  5894. {
  5895. if($this->coreScripts===null)
  5896. return;
  5897. $cssFiles=array();
  5898. $jsFiles=array();
  5899. foreach($this->coreScripts as $name=>$package)
  5900. {
  5901. $baseUrl=$this->getPackageBaseUrl($name);
  5902. if(!empty($package['js']))
  5903. {
  5904. foreach($package['js'] as $js)
  5905. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  5906. }
  5907. if(!empty($package['css']))
  5908. {
  5909. foreach($package['css'] as $css)
  5910. $cssFiles[$baseUrl.'/'.$css]='';
  5911. }
  5912. }
  5913. // merge in place
  5914. if($cssFiles!==array())
  5915. {
  5916. foreach($this->cssFiles as $cssFile=>$media)
  5917. $cssFiles[$cssFile]=$media;
  5918. $this->cssFiles=$cssFiles;
  5919. }
  5920. if($jsFiles!==array())
  5921. {
  5922. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  5923. {
  5924. foreach($this->scriptFiles[$this->coreScriptPosition] as $url)
  5925. $jsFiles[$url]=$url;
  5926. }
  5927. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  5928. }
  5929. }
  5930. public function renderHead(&$output)
  5931. {
  5932. $html='';
  5933. foreach($this->metaTags as $meta)
  5934. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  5935. foreach($this->linkTags as $link)
  5936. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  5937. foreach($this->cssFiles as $url=>$media)
  5938. $html.=CHtml::cssFile($url,$media)."\n";
  5939. foreach($this->css as $css)
  5940. $html.=CHtml::css($css[0],$css[1])."\n";
  5941. if($this->enableJavaScript)
  5942. {
  5943. if(isset($this->scriptFiles[self::POS_HEAD]))
  5944. {
  5945. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFile)
  5946. $html.=CHtml::scriptFile($scriptFile)."\n";
  5947. }
  5948. if(isset($this->scripts[self::POS_HEAD]))
  5949. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_HEAD]))."\n";
  5950. }
  5951. if($html!=='')
  5952. {
  5953. $count=0;
  5954. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  5955. if($count)
  5956. $output=str_replace('<###head###>',$html,$output);
  5957. else
  5958. $output=$html.$output;
  5959. }
  5960. }
  5961. public function renderBodyBegin(&$output)
  5962. {
  5963. $html='';
  5964. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5965. {
  5966. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile)
  5967. $html.=CHtml::scriptFile($scriptFile)."\n";
  5968. }
  5969. if(isset($this->scripts[self::POS_BEGIN]))
  5970. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_BEGIN]))."\n";
  5971. if($html!=='')
  5972. {
  5973. $count=0;
  5974. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  5975. if($count)
  5976. $output=str_replace('<###begin###>',$html,$output);
  5977. else
  5978. $output=$html.$output;
  5979. }
  5980. }
  5981. public function renderBodyEnd(&$output)
  5982. {
  5983. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  5984. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  5985. return;
  5986. $fullPage=0;
  5987. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  5988. $html='';
  5989. if(isset($this->scriptFiles[self::POS_END]))
  5990. {
  5991. foreach($this->scriptFiles[self::POS_END] as $scriptFile)
  5992. $html.=CHtml::scriptFile($scriptFile)."\n";
  5993. }
  5994. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  5995. if(isset($this->scripts[self::POS_READY]))
  5996. {
  5997. if($fullPage)
  5998. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  5999. else
  6000. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  6001. }
  6002. if(isset($this->scripts[self::POS_LOAD]))
  6003. {
  6004. if($fullPage)
  6005. $scripts[]="jQuery(window).on('load',function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  6006. else
  6007. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  6008. }
  6009. if(!empty($scripts))
  6010. $html.=CHtml::script(implode("\n",$scripts))."\n";
  6011. if($fullPage)
  6012. $output=str_replace('<###end###>',$html,$output);
  6013. else
  6014. $output=$output.$html;
  6015. }
  6016. public function getCoreScriptUrl()
  6017. {
  6018. if($this->_baseUrl!==null)
  6019. return $this->_baseUrl;
  6020. else
  6021. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  6022. }
  6023. public function setCoreScriptUrl($value)
  6024. {
  6025. $this->_baseUrl=$value;
  6026. }
  6027. public function getPackageBaseUrl($name)
  6028. {
  6029. if(!isset($this->coreScripts[$name]))
  6030. return false;
  6031. $package=$this->coreScripts[$name];
  6032. if(isset($package['baseUrl']))
  6033. {
  6034. $baseUrl=$package['baseUrl'];
  6035. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  6036. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  6037. $baseUrl=rtrim($baseUrl,'/');
  6038. }
  6039. elseif(isset($package['basePath']))
  6040. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  6041. else
  6042. $baseUrl=$this->getCoreScriptUrl();
  6043. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  6044. }
  6045. public function registerPackage($name)
  6046. {
  6047. return $this->registerCoreScript($name);
  6048. }
  6049. public function registerCoreScript($name)
  6050. {
  6051. if(isset($this->coreScripts[$name]))
  6052. return $this;
  6053. if(isset($this->packages[$name]))
  6054. $package=$this->packages[$name];
  6055. else
  6056. {
  6057. if($this->corePackages===null)
  6058. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  6059. if(isset($this->corePackages[$name]))
  6060. $package=$this->corePackages[$name];
  6061. }
  6062. if(isset($package))
  6063. {
  6064. if(!empty($package['depends']))
  6065. {
  6066. foreach($package['depends'] as $p)
  6067. $this->registerCoreScript($p);
  6068. }
  6069. $this->coreScripts[$name]=$package;
  6070. $this->hasScripts=true;
  6071. $params=func_get_args();
  6072. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  6073. }
  6074. return $this;
  6075. }
  6076. public function registerCssFile($url,$media='')
  6077. {
  6078. $this->hasScripts=true;
  6079. $this->cssFiles[$url]=$media;
  6080. $params=func_get_args();
  6081. $this->recordCachingAction('clientScript','registerCssFile',$params);
  6082. return $this;
  6083. }
  6084. public function registerCss($id,$css,$media='')
  6085. {
  6086. $this->hasScripts=true;
  6087. $this->css[$id]=array($css,$media);
  6088. $params=func_get_args();
  6089. $this->recordCachingAction('clientScript','registerCss',$params);
  6090. return $this;
  6091. }
  6092. public function registerScriptFile($url,$position=null)
  6093. {
  6094. if($position===null)
  6095. $position=$this->defaultScriptFilePosition;
  6096. $this->hasScripts=true;
  6097. $this->scriptFiles[$position][$url]=$url;
  6098. $params=func_get_args();
  6099. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  6100. return $this;
  6101. }
  6102. public function registerScript($id,$script,$position=null)
  6103. {
  6104. if($position===null)
  6105. $position=$this->defaultScriptPosition;
  6106. $this->hasScripts=true;
  6107. $this->scripts[$position][$id]=$script;
  6108. if($position===self::POS_READY || $position===self::POS_LOAD)
  6109. $this->registerCoreScript('jquery');
  6110. $params=func_get_args();
  6111. $this->recordCachingAction('clientScript','registerScript',$params);
  6112. return $this;
  6113. }
  6114. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array(),$id=null)
  6115. {
  6116. $this->hasScripts=true;
  6117. if($name!==null)
  6118. $options['name']=$name;
  6119. if($httpEquiv!==null)
  6120. $options['http-equiv']=$httpEquiv;
  6121. $options['content']=$content;
  6122. $this->metaTags[null===$id?count($this->metaTags):$id]=$options;
  6123. $params=func_get_args();
  6124. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  6125. return $this;
  6126. }
  6127. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  6128. {
  6129. $this->hasScripts=true;
  6130. if($relation!==null)
  6131. $options['rel']=$relation;
  6132. if($type!==null)
  6133. $options['type']=$type;
  6134. if($href!==null)
  6135. $options['href']=$href;
  6136. if($media!==null)
  6137. $options['media']=$media;
  6138. $this->linkTags[serialize($options)]=$options;
  6139. $params=func_get_args();
  6140. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  6141. return $this;
  6142. }
  6143. public function isCssFileRegistered($url)
  6144. {
  6145. return isset($this->cssFiles[$url]);
  6146. }
  6147. public function isCssRegistered($id)
  6148. {
  6149. return isset($this->css[$id]);
  6150. }
  6151. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  6152. {
  6153. return isset($this->scriptFiles[$position][$url]);
  6154. }
  6155. public function isScriptRegistered($id,$position=self::POS_READY)
  6156. {
  6157. return isset($this->scripts[$position][$id]);
  6158. }
  6159. protected function recordCachingAction($context,$method,$params)
  6160. {
  6161. if(($controller=Yii::app()->getController())!==null)
  6162. $controller->recordCachingAction($context,$method,$params);
  6163. }
  6164. public function addPackage($name,$definition)
  6165. {
  6166. $this->packages[$name]=$definition;
  6167. return $this;
  6168. }
  6169. }
  6170. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  6171. {
  6172. private $_d=array();
  6173. private $_c=0;
  6174. private $_r=false;
  6175. public function __construct($data=null,$readOnly=false)
  6176. {
  6177. if($data!==null)
  6178. $this->copyFrom($data);
  6179. $this->setReadOnly($readOnly);
  6180. }
  6181. public function getReadOnly()
  6182. {
  6183. return $this->_r;
  6184. }
  6185. protected function setReadOnly($value)
  6186. {
  6187. $this->_r=$value;
  6188. }
  6189. public function getIterator()
  6190. {
  6191. return new CListIterator($this->_d);
  6192. }
  6193. public function count()
  6194. {
  6195. return $this->getCount();
  6196. }
  6197. public function getCount()
  6198. {
  6199. return $this->_c;
  6200. }
  6201. public function itemAt($index)
  6202. {
  6203. if(isset($this->_d[$index]))
  6204. return $this->_d[$index];
  6205. elseif($index>=0 && $index<$this->_c) // in case the value is null
  6206. return $this->_d[$index];
  6207. else
  6208. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6209. array('{index}'=>$index)));
  6210. }
  6211. public function add($item)
  6212. {
  6213. $this->insertAt($this->_c,$item);
  6214. return $this->_c-1;
  6215. }
  6216. public function insertAt($index,$item)
  6217. {
  6218. if(!$this->_r)
  6219. {
  6220. if($index===$this->_c)
  6221. $this->_d[$this->_c++]=$item;
  6222. elseif($index>=0 && $index<$this->_c)
  6223. {
  6224. array_splice($this->_d,$index,0,array($item));
  6225. $this->_c++;
  6226. }
  6227. else
  6228. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6229. array('{index}'=>$index)));
  6230. }
  6231. else
  6232. throw new CException(Yii::t('yii','The list is read only.'));
  6233. }
  6234. public function remove($item)
  6235. {
  6236. if(($index=$this->indexOf($item))>=0)
  6237. {
  6238. $this->removeAt($index);
  6239. return $index;
  6240. }
  6241. else
  6242. return false;
  6243. }
  6244. public function removeAt($index)
  6245. {
  6246. if(!$this->_r)
  6247. {
  6248. if($index>=0 && $index<$this->_c)
  6249. {
  6250. $this->_c--;
  6251. if($index===$this->_c)
  6252. return array_pop($this->_d);
  6253. else
  6254. {
  6255. $item=$this->_d[$index];
  6256. array_splice($this->_d,$index,1);
  6257. return $item;
  6258. }
  6259. }
  6260. else
  6261. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6262. array('{index}'=>$index)));
  6263. }
  6264. else
  6265. throw new CException(Yii::t('yii','The list is read only.'));
  6266. }
  6267. public function clear()
  6268. {
  6269. for($i=$this->_c-1;$i>=0;--$i)
  6270. $this->removeAt($i);
  6271. }
  6272. public function contains($item)
  6273. {
  6274. return $this->indexOf($item)>=0;
  6275. }
  6276. public function indexOf($item)
  6277. {
  6278. if(($index=array_search($item,$this->_d,true))!==false)
  6279. return $index;
  6280. else
  6281. return -1;
  6282. }
  6283. public function toArray()
  6284. {
  6285. return $this->_d;
  6286. }
  6287. public function copyFrom($data)
  6288. {
  6289. if(is_array($data) || ($data instanceof Traversable))
  6290. {
  6291. if($this->_c>0)
  6292. $this->clear();
  6293. if($data instanceof CList)
  6294. $data=$data->_d;
  6295. foreach($data as $item)
  6296. $this->add($item);
  6297. }
  6298. elseif($data!==null)
  6299. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6300. }
  6301. public function mergeWith($data)
  6302. {
  6303. if(is_array($data) || ($data instanceof Traversable))
  6304. {
  6305. if($data instanceof CList)
  6306. $data=$data->_d;
  6307. foreach($data as $item)
  6308. $this->add($item);
  6309. }
  6310. elseif($data!==null)
  6311. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6312. }
  6313. public function offsetExists($offset)
  6314. {
  6315. return ($offset>=0 && $offset<$this->_c);
  6316. }
  6317. public function offsetGet($offset)
  6318. {
  6319. return $this->itemAt($offset);
  6320. }
  6321. public function offsetSet($offset,$item)
  6322. {
  6323. if($offset===null || $offset===$this->_c)
  6324. $this->insertAt($this->_c,$item);
  6325. else
  6326. {
  6327. $this->removeAt($offset);
  6328. $this->insertAt($offset,$item);
  6329. }
  6330. }
  6331. public function offsetUnset($offset)
  6332. {
  6333. $this->removeAt($offset);
  6334. }
  6335. }
  6336. class CFilterChain extends CList
  6337. {
  6338. public $controller;
  6339. public $action;
  6340. public $filterIndex=0;
  6341. public function __construct($controller,$action)
  6342. {
  6343. $this->controller=$controller;
  6344. $this->action=$action;
  6345. }
  6346. public static function create($controller,$action,$filters)
  6347. {
  6348. $chain=new CFilterChain($controller,$action);
  6349. $actionID=$action->getId();
  6350. foreach($filters as $filter)
  6351. {
  6352. if(is_string($filter)) // filterName [+|- action1 action2]
  6353. {
  6354. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  6355. {
  6356. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  6357. if(($filter[$pos]==='+')===$matched)
  6358. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  6359. }
  6360. else
  6361. $filter=CInlineFilter::create($controller,$filter);
  6362. }
  6363. elseif(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  6364. {
  6365. if(!isset($filter[0]))
  6366. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  6367. $filterClass=$filter[0];
  6368. unset($filter[0]);
  6369. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  6370. {
  6371. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  6372. if(($filterClass[$pos]==='+')===$matched)
  6373. $filterClass=trim(substr($filterClass,0,$pos));
  6374. else
  6375. continue;
  6376. }
  6377. $filter['class']=$filterClass;
  6378. $filter=Yii::createComponent($filter);
  6379. }
  6380. if(is_object($filter))
  6381. {
  6382. $filter->init();
  6383. $chain->add($filter);
  6384. }
  6385. }
  6386. return $chain;
  6387. }
  6388. public function insertAt($index,$item)
  6389. {
  6390. if($item instanceof IFilter)
  6391. parent::insertAt($index,$item);
  6392. else
  6393. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  6394. }
  6395. public function run()
  6396. {
  6397. if($this->offsetExists($this->filterIndex))
  6398. {
  6399. $filter=$this->itemAt($this->filterIndex++);
  6400. $filter->filter($this);
  6401. }
  6402. else
  6403. $this->controller->runAction($this->action);
  6404. }
  6405. }
  6406. class CFilter extends CComponent implements IFilter
  6407. {
  6408. public function filter($filterChain)
  6409. {
  6410. if($this->preFilter($filterChain))
  6411. {
  6412. $filterChain->run();
  6413. $this->postFilter($filterChain);
  6414. }
  6415. }
  6416. public function init()
  6417. {
  6418. }
  6419. protected function preFilter($filterChain)
  6420. {
  6421. return true;
  6422. }
  6423. protected function postFilter($filterChain)
  6424. {
  6425. }
  6426. }
  6427. class CInlineFilter extends CFilter
  6428. {
  6429. public $name;
  6430. public static function create($controller,$filterName)
  6431. {
  6432. if(method_exists($controller,'filter'.$filterName))
  6433. {
  6434. $filter=new CInlineFilter;
  6435. $filter->name=$filterName;
  6436. return $filter;
  6437. }
  6438. else
  6439. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  6440. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  6441. }
  6442. public function filter($filterChain)
  6443. {
  6444. $method='filter'.$this->name;
  6445. $filterChain->controller->$method($filterChain);
  6446. }
  6447. }
  6448. class CAccessControlFilter extends CFilter
  6449. {
  6450. public $message;
  6451. private $_rules=array();
  6452. public function getRules()
  6453. {
  6454. return $this->_rules;
  6455. }
  6456. public function setRules($rules)
  6457. {
  6458. foreach($rules as $rule)
  6459. {
  6460. if(is_array($rule) && isset($rule[0]))
  6461. {
  6462. $r=new CAccessRule;
  6463. $r->allow=$rule[0]==='allow';
  6464. foreach(array_slice($rule,1) as $name=>$value)
  6465. {
  6466. if($name==='expression' || $name==='roles' || $name==='message' || $name==='deniedCallback')
  6467. $r->$name=$value;
  6468. else
  6469. $r->$name=array_map('strtolower',$value);
  6470. }
  6471. $this->_rules[]=$r;
  6472. }
  6473. }
  6474. }
  6475. protected function preFilter($filterChain)
  6476. {
  6477. $app=Yii::app();
  6478. $request=$app->getRequest();
  6479. $user=$app->getUser();
  6480. $verb=$request->getRequestType();
  6481. $ip=$request->getUserHostAddress();
  6482. foreach($this->getRules() as $rule)
  6483. {
  6484. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  6485. break;
  6486. elseif($allow<0) // denied
  6487. {
  6488. if(isset($rule->deniedCallback))
  6489. call_user_func($rule->deniedCallback, $rule);
  6490. else
  6491. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  6492. return false;
  6493. }
  6494. }
  6495. return true;
  6496. }
  6497. protected function resolveErrorMessage($rule)
  6498. {
  6499. if($rule->message!==null)
  6500. return $rule->message;
  6501. elseif($this->message!==null)
  6502. return $this->message;
  6503. else
  6504. return Yii::t('yii','You are not authorized to perform this action.');
  6505. }
  6506. protected function accessDenied($user,$message)
  6507. {
  6508. if($user->getIsGuest())
  6509. $user->loginRequired();
  6510. else
  6511. throw new CHttpException(403,$message);
  6512. }
  6513. }
  6514. class CAccessRule extends CComponent
  6515. {
  6516. public $allow;
  6517. public $actions;
  6518. public $controllers;
  6519. public $users;
  6520. public $roles;
  6521. public $ips;
  6522. public $verbs;
  6523. public $expression;
  6524. public $message;
  6525. public $deniedCallback;
  6526. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  6527. {
  6528. if($this->isActionMatched($action)
  6529. && $this->isUserMatched($user)
  6530. && $this->isRoleMatched($user)
  6531. && $this->isIpMatched($ip)
  6532. && $this->isVerbMatched($verb)
  6533. && $this->isControllerMatched($controller)
  6534. && $this->isExpressionMatched($user))
  6535. return $this->allow ? 1 : -1;
  6536. else
  6537. return 0;
  6538. }
  6539. protected function isActionMatched($action)
  6540. {
  6541. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  6542. }
  6543. protected function isControllerMatched($controller)
  6544. {
  6545. return empty($this->controllers) || in_array(strtolower($controller->getId()),$this->controllers);
  6546. }
  6547. protected function isUserMatched($user)
  6548. {
  6549. if(empty($this->users))
  6550. return true;
  6551. foreach($this->users as $u)
  6552. {
  6553. if($u==='*')
  6554. return true;
  6555. elseif($u==='?' && $user->getIsGuest())
  6556. return true;
  6557. elseif($u==='@' && !$user->getIsGuest())
  6558. return true;
  6559. elseif(!strcasecmp($u,$user->getName()))
  6560. return true;
  6561. }
  6562. return false;
  6563. }
  6564. protected function isRoleMatched($user)
  6565. {
  6566. if(empty($this->roles))
  6567. return true;
  6568. foreach($this->roles as $key=>$role)
  6569. {
  6570. if(is_numeric($key))
  6571. {
  6572. if($user->checkAccess($role))
  6573. return true;
  6574. }
  6575. else
  6576. {
  6577. if($user->checkAccess($key,$role))
  6578. return true;
  6579. }
  6580. }
  6581. return false;
  6582. }
  6583. protected function isIpMatched($ip)
  6584. {
  6585. if(empty($this->ips))
  6586. return true;
  6587. foreach($this->ips as $rule)
  6588. {
  6589. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  6590. return true;
  6591. }
  6592. return false;
  6593. }
  6594. protected function isVerbMatched($verb)
  6595. {
  6596. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  6597. }
  6598. protected function isExpressionMatched($user)
  6599. {
  6600. if($this->expression===null)
  6601. return true;
  6602. else
  6603. return $this->evaluateExpression($this->expression, array('user'=>$user));
  6604. }
  6605. }
  6606. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  6607. {
  6608. private $_errors=array(); // attribute name => array of errors
  6609. private $_validators; // validators
  6610. private $_scenario=''; // scenario
  6611. abstract public function attributeNames();
  6612. public function rules()
  6613. {
  6614. return array();
  6615. }
  6616. public function behaviors()
  6617. {
  6618. return array();
  6619. }
  6620. public function attributeLabels()
  6621. {
  6622. return array();
  6623. }
  6624. public function validate($attributes=null, $clearErrors=true)
  6625. {
  6626. if($clearErrors)
  6627. $this->clearErrors();
  6628. if($this->beforeValidate())
  6629. {
  6630. foreach($this->getValidators() as $validator)
  6631. $validator->validate($this,$attributes);
  6632. $this->afterValidate();
  6633. return !$this->hasErrors();
  6634. }
  6635. else
  6636. return false;
  6637. }
  6638. protected function afterConstruct()
  6639. {
  6640. if($this->hasEventHandler('onAfterConstruct'))
  6641. $this->onAfterConstruct(new CEvent($this));
  6642. }
  6643. protected function beforeValidate()
  6644. {
  6645. $event=new CModelEvent($this);
  6646. $this->onBeforeValidate($event);
  6647. return $event->isValid;
  6648. }
  6649. protected function afterValidate()
  6650. {
  6651. $this->onAfterValidate(new CEvent($this));
  6652. }
  6653. public function onAfterConstruct($event)
  6654. {
  6655. $this->raiseEvent('onAfterConstruct',$event);
  6656. }
  6657. public function onBeforeValidate($event)
  6658. {
  6659. $this->raiseEvent('onBeforeValidate',$event);
  6660. }
  6661. public function onAfterValidate($event)
  6662. {
  6663. $this->raiseEvent('onAfterValidate',$event);
  6664. }
  6665. public function getValidatorList()
  6666. {
  6667. if($this->_validators===null)
  6668. $this->_validators=$this->createValidators();
  6669. return $this->_validators;
  6670. }
  6671. public function getValidators($attribute=null)
  6672. {
  6673. if($this->_validators===null)
  6674. $this->_validators=$this->createValidators();
  6675. $validators=array();
  6676. $scenario=$this->getScenario();
  6677. foreach($this->_validators as $validator)
  6678. {
  6679. if($validator->applyTo($scenario))
  6680. {
  6681. if($attribute===null || in_array($attribute,$validator->attributes,true))
  6682. $validators[]=$validator;
  6683. }
  6684. }
  6685. return $validators;
  6686. }
  6687. public function createValidators()
  6688. {
  6689. $validators=new CList;
  6690. foreach($this->rules() as $rule)
  6691. {
  6692. if(isset($rule[0],$rule[1])) // attributes, validator name
  6693. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  6694. else
  6695. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  6696. array('{class}'=>get_class($this))));
  6697. }
  6698. return $validators;
  6699. }
  6700. public function isAttributeRequired($attribute)
  6701. {
  6702. foreach($this->getValidators($attribute) as $validator)
  6703. {
  6704. if($validator instanceof CRequiredValidator)
  6705. return true;
  6706. }
  6707. return false;
  6708. }
  6709. public function isAttributeSafe($attribute)
  6710. {
  6711. $attributes=$this->getSafeAttributeNames();
  6712. return in_array($attribute,$attributes);
  6713. }
  6714. public function getAttributeLabel($attribute)
  6715. {
  6716. $labels=$this->attributeLabels();
  6717. if(isset($labels[$attribute]))
  6718. return $labels[$attribute];
  6719. else
  6720. return $this->generateAttributeLabel($attribute);
  6721. }
  6722. public function hasErrors($attribute=null)
  6723. {
  6724. if($attribute===null)
  6725. return $this->_errors!==array();
  6726. else
  6727. return isset($this->_errors[$attribute]);
  6728. }
  6729. public function getErrors($attribute=null)
  6730. {
  6731. if($attribute===null)
  6732. return $this->_errors;
  6733. else
  6734. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  6735. }
  6736. public function getError($attribute)
  6737. {
  6738. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  6739. }
  6740. public function addError($attribute,$error)
  6741. {
  6742. $this->_errors[$attribute][]=$error;
  6743. }
  6744. public function addErrors($errors)
  6745. {
  6746. foreach($errors as $attribute=>$error)
  6747. {
  6748. if(is_array($error))
  6749. {
  6750. foreach($error as $e)
  6751. $this->addError($attribute, $e);
  6752. }
  6753. else
  6754. $this->addError($attribute, $error);
  6755. }
  6756. }
  6757. public function clearErrors($attribute=null)
  6758. {
  6759. if($attribute===null)
  6760. $this->_errors=array();
  6761. else
  6762. unset($this->_errors[$attribute]);
  6763. }
  6764. public function generateAttributeLabel($name)
  6765. {
  6766. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  6767. }
  6768. public function getAttributes($names=null)
  6769. {
  6770. $values=array();
  6771. foreach($this->attributeNames() as $name)
  6772. $values[$name]=$this->$name;
  6773. if(is_array($names))
  6774. {
  6775. $values2=array();
  6776. foreach($names as $name)
  6777. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  6778. return $values2;
  6779. }
  6780. else
  6781. return $values;
  6782. }
  6783. public function setAttributes($values,$safeOnly=true)
  6784. {
  6785. if(!is_array($values))
  6786. return;
  6787. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  6788. foreach($values as $name=>$value)
  6789. {
  6790. if(isset($attributes[$name]))
  6791. $this->$name=$value;
  6792. elseif($safeOnly)
  6793. $this->onUnsafeAttribute($name,$value);
  6794. }
  6795. }
  6796. public function unsetAttributes($names=null)
  6797. {
  6798. if($names===null)
  6799. $names=$this->attributeNames();
  6800. foreach($names as $name)
  6801. $this->$name=null;
  6802. }
  6803. public function onUnsafeAttribute($name,$value)
  6804. {
  6805. if(YII_DEBUG)
  6806. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  6807. }
  6808. public function getScenario()
  6809. {
  6810. return $this->_scenario;
  6811. }
  6812. public function setScenario($value)
  6813. {
  6814. $this->_scenario=$value;
  6815. }
  6816. public function getSafeAttributeNames()
  6817. {
  6818. $attributes=array();
  6819. $unsafe=array();
  6820. foreach($this->getValidators() as $validator)
  6821. {
  6822. if(!$validator->safe)
  6823. {
  6824. foreach($validator->attributes as $name)
  6825. $unsafe[]=$name;
  6826. }
  6827. else
  6828. {
  6829. foreach($validator->attributes as $name)
  6830. $attributes[$name]=true;
  6831. }
  6832. }
  6833. foreach($unsafe as $name)
  6834. unset($attributes[$name]);
  6835. return array_keys($attributes);
  6836. }
  6837. public function getIterator()
  6838. {
  6839. $attributes=$this->getAttributes();
  6840. return new CMapIterator($attributes);
  6841. }
  6842. public function offsetExists($offset)
  6843. {
  6844. return property_exists($this,$offset);
  6845. }
  6846. public function offsetGet($offset)
  6847. {
  6848. return $this->$offset;
  6849. }
  6850. public function offsetSet($offset,$item)
  6851. {
  6852. $this->$offset=$item;
  6853. }
  6854. public function offsetUnset($offset)
  6855. {
  6856. unset($this->$offset);
  6857. }
  6858. }
  6859. abstract class CActiveRecord extends CModel
  6860. {
  6861. const BELONGS_TO='CBelongsToRelation';
  6862. const HAS_ONE='CHasOneRelation';
  6863. const HAS_MANY='CHasManyRelation';
  6864. const MANY_MANY='CManyManyRelation';
  6865. const STAT='CStatRelation';
  6866. public static $db;
  6867. private static $_models=array(); // class name => model
  6868. private $_md; // meta data
  6869. private $_new=false; // whether this instance is new or not
  6870. private $_attributes=array(); // attribute name => attribute value
  6871. private $_related=array(); // attribute name => related objects
  6872. private $_c; // query criteria (used by finder only)
  6873. private $_pk; // old primary key value
  6874. private $_alias='t'; // the table alias being used for query
  6875. public function __construct($scenario='insert')
  6876. {
  6877. if($scenario===null) // internally used by populateRecord() and model()
  6878. return;
  6879. $this->setScenario($scenario);
  6880. $this->setIsNewRecord(true);
  6881. $this->_attributes=$this->getMetaData()->attributeDefaults;
  6882. $this->init();
  6883. $this->attachBehaviors($this->behaviors());
  6884. $this->afterConstruct();
  6885. }
  6886. public function init()
  6887. {
  6888. }
  6889. public function cache($duration, $dependency=null, $queryCount=1)
  6890. {
  6891. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  6892. return $this;
  6893. }
  6894. public function __sleep()
  6895. {
  6896. $this->_md=null;
  6897. return array_keys((array)$this);
  6898. }
  6899. public function __get($name)
  6900. {
  6901. if(isset($this->_attributes[$name]))
  6902. return $this->_attributes[$name];
  6903. elseif(isset($this->getMetaData()->columns[$name]))
  6904. return null;
  6905. elseif(isset($this->_related[$name]))
  6906. return $this->_related[$name];
  6907. elseif(isset($this->getMetaData()->relations[$name]))
  6908. return $this->getRelated($name);
  6909. else
  6910. return parent::__get($name);
  6911. }
  6912. public function __set($name,$value)
  6913. {
  6914. if($this->setAttribute($name,$value)===false)
  6915. {
  6916. if(isset($this->getMetaData()->relations[$name]))
  6917. $this->_related[$name]=$value;
  6918. else
  6919. parent::__set($name,$value);
  6920. }
  6921. }
  6922. public function __isset($name)
  6923. {
  6924. if(isset($this->_attributes[$name]))
  6925. return true;
  6926. elseif(isset($this->getMetaData()->columns[$name]))
  6927. return false;
  6928. elseif(isset($this->_related[$name]))
  6929. return true;
  6930. elseif(isset($this->getMetaData()->relations[$name]))
  6931. return $this->getRelated($name)!==null;
  6932. else
  6933. return parent::__isset($name);
  6934. }
  6935. public function __unset($name)
  6936. {
  6937. if(isset($this->getMetaData()->columns[$name]))
  6938. unset($this->_attributes[$name]);
  6939. elseif(isset($this->getMetaData()->relations[$name]))
  6940. unset($this->_related[$name]);
  6941. else
  6942. parent::__unset($name);
  6943. }
  6944. public function __call($name,$parameters)
  6945. {
  6946. if(isset($this->getMetaData()->relations[$name]))
  6947. {
  6948. if(empty($parameters))
  6949. return $this->getRelated($name,false);
  6950. else
  6951. return $this->getRelated($name,false,$parameters[0]);
  6952. }
  6953. $scopes=$this->scopes();
  6954. if(isset($scopes[$name]))
  6955. {
  6956. $this->getDbCriteria()->mergeWith($scopes[$name]);
  6957. return $this;
  6958. }
  6959. return parent::__call($name,$parameters);
  6960. }
  6961. public function getRelated($name,$refresh=false,$params=array())
  6962. {
  6963. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  6964. return $this->_related[$name];
  6965. $md=$this->getMetaData();
  6966. if(!isset($md->relations[$name]))
  6967. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  6968. array('{class}'=>get_class($this), '{name}'=>$name)));
  6969. $relation=$md->relations[$name];
  6970. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  6971. return $relation instanceof CHasOneRelation ? null : array();
  6972. if($params!==array()) // dynamic query
  6973. {
  6974. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6975. if($exists)
  6976. $save=$this->_related[$name];
  6977. if($params instanceof CDbCriteria)
  6978. $params = $params->toArray();
  6979. $r=array($name=>$params);
  6980. }
  6981. else
  6982. $r=$name;
  6983. unset($this->_related[$name]);
  6984. $finder=new CActiveFinder($this,$r);
  6985. $finder->lazyFind($this);
  6986. if(!isset($this->_related[$name]))
  6987. {
  6988. if($relation instanceof CHasManyRelation)
  6989. $this->_related[$name]=array();
  6990. elseif($relation instanceof CStatRelation)
  6991. $this->_related[$name]=$relation->defaultValue;
  6992. else
  6993. $this->_related[$name]=null;
  6994. }
  6995. if($params!==array())
  6996. {
  6997. $results=$this->_related[$name];
  6998. if($exists)
  6999. $this->_related[$name]=$save;
  7000. else
  7001. unset($this->_related[$name]);
  7002. return $results;
  7003. }
  7004. else
  7005. return $this->_related[$name];
  7006. }
  7007. public function hasRelated($name)
  7008. {
  7009. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7010. }
  7011. public function getDbCriteria($createIfNull=true)
  7012. {
  7013. if($this->_c===null)
  7014. {
  7015. if(($c=$this->defaultScope())!==array() || $createIfNull)
  7016. $this->_c=new CDbCriteria($c);
  7017. }
  7018. return $this->_c;
  7019. }
  7020. public function setDbCriteria($criteria)
  7021. {
  7022. $this->_c=$criteria;
  7023. }
  7024. public function defaultScope()
  7025. {
  7026. return array();
  7027. }
  7028. public function resetScope($resetDefault=true)
  7029. {
  7030. if($resetDefault)
  7031. $this->_c=new CDbCriteria();
  7032. else
  7033. $this->_c=null;
  7034. return $this;
  7035. }
  7036. public static function model($className=__CLASS__)
  7037. {
  7038. if(isset(self::$_models[$className]))
  7039. return self::$_models[$className];
  7040. else
  7041. {
  7042. $model=self::$_models[$className]=new $className(null);
  7043. $model->_md=new CActiveRecordMetaData($model);
  7044. $model->attachBehaviors($model->behaviors());
  7045. return $model;
  7046. }
  7047. }
  7048. public function getMetaData()
  7049. {
  7050. if($this->_md!==null)
  7051. return $this->_md;
  7052. else
  7053. return $this->_md=self::model(get_class($this))->_md;
  7054. }
  7055. public function refreshMetaData()
  7056. {
  7057. $finder=self::model(get_class($this));
  7058. $finder->_md=new CActiveRecordMetaData($finder);
  7059. if($this!==$finder)
  7060. $this->_md=$finder->_md;
  7061. }
  7062. public function tableName()
  7063. {
  7064. return get_class($this);
  7065. }
  7066. public function primaryKey()
  7067. {
  7068. }
  7069. public function relations()
  7070. {
  7071. return array();
  7072. }
  7073. public function scopes()
  7074. {
  7075. return array();
  7076. }
  7077. public function attributeNames()
  7078. {
  7079. return array_keys($this->getMetaData()->columns);
  7080. }
  7081. public function getAttributeLabel($attribute)
  7082. {
  7083. $labels=$this->attributeLabels();
  7084. if(isset($labels[$attribute]))
  7085. return $labels[$attribute];
  7086. elseif(strpos($attribute,'.')!==false)
  7087. {
  7088. $segs=explode('.',$attribute);
  7089. $name=array_pop($segs);
  7090. $model=$this;
  7091. foreach($segs as $seg)
  7092. {
  7093. $relations=$model->getMetaData()->relations;
  7094. if(isset($relations[$seg]))
  7095. $model=CActiveRecord::model($relations[$seg]->className);
  7096. else
  7097. break;
  7098. }
  7099. return $model->getAttributeLabel($name);
  7100. }
  7101. else
  7102. return $this->generateAttributeLabel($attribute);
  7103. }
  7104. public function getDbConnection()
  7105. {
  7106. if(self::$db!==null)
  7107. return self::$db;
  7108. else
  7109. {
  7110. self::$db=Yii::app()->getDb();
  7111. if(self::$db instanceof CDbConnection)
  7112. return self::$db;
  7113. else
  7114. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  7115. }
  7116. }
  7117. public function getActiveRelation($name)
  7118. {
  7119. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  7120. }
  7121. public function getTableSchema()
  7122. {
  7123. return $this->getMetaData()->tableSchema;
  7124. }
  7125. public function getCommandBuilder()
  7126. {
  7127. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  7128. }
  7129. public function hasAttribute($name)
  7130. {
  7131. return isset($this->getMetaData()->columns[$name]);
  7132. }
  7133. public function getAttribute($name)
  7134. {
  7135. if(property_exists($this,$name))
  7136. return $this->$name;
  7137. elseif(isset($this->_attributes[$name]))
  7138. return $this->_attributes[$name];
  7139. }
  7140. public function setAttribute($name,$value)
  7141. {
  7142. if(property_exists($this,$name))
  7143. $this->$name=$value;
  7144. elseif(isset($this->getMetaData()->columns[$name]))
  7145. $this->_attributes[$name]=$value;
  7146. else
  7147. return false;
  7148. return true;
  7149. }
  7150. public function addRelatedRecord($name,$record,$index)
  7151. {
  7152. if($index!==false)
  7153. {
  7154. if(!isset($this->_related[$name]))
  7155. $this->_related[$name]=array();
  7156. if($record instanceof CActiveRecord)
  7157. {
  7158. if($index===true)
  7159. $this->_related[$name][]=$record;
  7160. else
  7161. $this->_related[$name][$index]=$record;
  7162. }
  7163. }
  7164. elseif(!isset($this->_related[$name]))
  7165. $this->_related[$name]=$record;
  7166. }
  7167. public function getAttributes($names=true)
  7168. {
  7169. $attributes=$this->_attributes;
  7170. foreach($this->getMetaData()->columns as $name=>$column)
  7171. {
  7172. if(property_exists($this,$name))
  7173. $attributes[$name]=$this->$name;
  7174. elseif($names===true && !isset($attributes[$name]))
  7175. $attributes[$name]=null;
  7176. }
  7177. if(is_array($names))
  7178. {
  7179. $attrs=array();
  7180. foreach($names as $name)
  7181. {
  7182. if(property_exists($this,$name))
  7183. $attrs[$name]=$this->$name;
  7184. else
  7185. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  7186. }
  7187. return $attrs;
  7188. }
  7189. else
  7190. return $attributes;
  7191. }
  7192. public function save($runValidation=true,$attributes=null)
  7193. {
  7194. if(!$runValidation || $this->validate($attributes))
  7195. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  7196. else
  7197. return false;
  7198. }
  7199. public function getIsNewRecord()
  7200. {
  7201. return $this->_new;
  7202. }
  7203. public function setIsNewRecord($value)
  7204. {
  7205. $this->_new=$value;
  7206. }
  7207. public function onBeforeSave($event)
  7208. {
  7209. $this->raiseEvent('onBeforeSave',$event);
  7210. }
  7211. public function onAfterSave($event)
  7212. {
  7213. $this->raiseEvent('onAfterSave',$event);
  7214. }
  7215. public function onBeforeDelete($event)
  7216. {
  7217. $this->raiseEvent('onBeforeDelete',$event);
  7218. }
  7219. public function onAfterDelete($event)
  7220. {
  7221. $this->raiseEvent('onAfterDelete',$event);
  7222. }
  7223. public function onBeforeFind($event)
  7224. {
  7225. $this->raiseEvent('onBeforeFind',$event);
  7226. }
  7227. public function onAfterFind($event)
  7228. {
  7229. $this->raiseEvent('onAfterFind',$event);
  7230. }
  7231. protected function beforeSave()
  7232. {
  7233. if($this->hasEventHandler('onBeforeSave'))
  7234. {
  7235. $event=new CModelEvent($this);
  7236. $this->onBeforeSave($event);
  7237. return $event->isValid;
  7238. }
  7239. else
  7240. return true;
  7241. }
  7242. protected function afterSave()
  7243. {
  7244. if($this->hasEventHandler('onAfterSave'))
  7245. $this->onAfterSave(new CEvent($this));
  7246. }
  7247. protected function beforeDelete()
  7248. {
  7249. if($this->hasEventHandler('onBeforeDelete'))
  7250. {
  7251. $event=new CModelEvent($this);
  7252. $this->onBeforeDelete($event);
  7253. return $event->isValid;
  7254. }
  7255. else
  7256. return true;
  7257. }
  7258. protected function afterDelete()
  7259. {
  7260. if($this->hasEventHandler('onAfterDelete'))
  7261. $this->onAfterDelete(new CEvent($this));
  7262. }
  7263. protected function beforeFind()
  7264. {
  7265. if($this->hasEventHandler('onBeforeFind'))
  7266. {
  7267. $event=new CModelEvent($this);
  7268. $this->onBeforeFind($event);
  7269. }
  7270. }
  7271. protected function afterFind()
  7272. {
  7273. if($this->hasEventHandler('onAfterFind'))
  7274. $this->onAfterFind(new CEvent($this));
  7275. }
  7276. public function beforeFindInternal()
  7277. {
  7278. $this->beforeFind();
  7279. }
  7280. public function afterFindInternal()
  7281. {
  7282. $this->afterFind();
  7283. }
  7284. public function insert($attributes=null)
  7285. {
  7286. if(!$this->getIsNewRecord())
  7287. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  7288. if($this->beforeSave())
  7289. {
  7290. $builder=$this->getCommandBuilder();
  7291. $table=$this->getMetaData()->tableSchema;
  7292. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  7293. if($command->execute())
  7294. {
  7295. $primaryKey=$table->primaryKey;
  7296. if($table->sequenceName!==null)
  7297. {
  7298. if(is_string($primaryKey) && $this->$primaryKey===null)
  7299. $this->$primaryKey=$builder->getLastInsertID($table);
  7300. elseif(is_array($primaryKey))
  7301. {
  7302. foreach($primaryKey as $pk)
  7303. {
  7304. if($this->$pk===null)
  7305. {
  7306. $this->$pk=$builder->getLastInsertID($table);
  7307. break;
  7308. }
  7309. }
  7310. }
  7311. }
  7312. $this->_pk=$this->getPrimaryKey();
  7313. $this->afterSave();
  7314. $this->setIsNewRecord(false);
  7315. $this->setScenario('update');
  7316. return true;
  7317. }
  7318. }
  7319. return false;
  7320. }
  7321. public function update($attributes=null)
  7322. {
  7323. if($this->getIsNewRecord())
  7324. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7325. if($this->beforeSave())
  7326. {
  7327. if($this->_pk===null)
  7328. $this->_pk=$this->getPrimaryKey();
  7329. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  7330. $this->_pk=$this->getPrimaryKey();
  7331. $this->afterSave();
  7332. return true;
  7333. }
  7334. else
  7335. return false;
  7336. }
  7337. public function saveAttributes($attributes)
  7338. {
  7339. if(!$this->getIsNewRecord())
  7340. {
  7341. $values=array();
  7342. foreach($attributes as $name=>$value)
  7343. {
  7344. if(is_integer($name))
  7345. $values[$value]=$this->$value;
  7346. else
  7347. $values[$name]=$this->$name=$value;
  7348. }
  7349. if($this->_pk===null)
  7350. $this->_pk=$this->getPrimaryKey();
  7351. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  7352. {
  7353. $this->_pk=$this->getPrimaryKey();
  7354. return true;
  7355. }
  7356. else
  7357. return false;
  7358. }
  7359. else
  7360. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7361. }
  7362. public function saveCounters($counters)
  7363. {
  7364. $builder=$this->getCommandBuilder();
  7365. $table=$this->getTableSchema();
  7366. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  7367. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7368. if($command->execute())
  7369. {
  7370. foreach($counters as $name=>$value)
  7371. $this->$name=$this->$name+$value;
  7372. return true;
  7373. }
  7374. else
  7375. return false;
  7376. }
  7377. public function delete()
  7378. {
  7379. if(!$this->getIsNewRecord())
  7380. {
  7381. if($this->beforeDelete())
  7382. {
  7383. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  7384. $this->afterDelete();
  7385. return $result;
  7386. }
  7387. else
  7388. return false;
  7389. }
  7390. else
  7391. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  7392. }
  7393. public function refresh()
  7394. {
  7395. if(($record=$this->findByPk($this->getPrimaryKey()))!==null)
  7396. {
  7397. $this->_attributes=array();
  7398. $this->_related=array();
  7399. foreach($this->getMetaData()->columns as $name=>$column)
  7400. {
  7401. if(property_exists($this,$name))
  7402. $this->$name=$record->$name;
  7403. else
  7404. $this->_attributes[$name]=$record->$name;
  7405. }
  7406. return true;
  7407. }
  7408. else
  7409. return false;
  7410. }
  7411. public function equals($record)
  7412. {
  7413. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  7414. }
  7415. public function getPrimaryKey()
  7416. {
  7417. $table=$this->getMetaData()->tableSchema;
  7418. if(is_string($table->primaryKey))
  7419. return $this->{$table->primaryKey};
  7420. elseif(is_array($table->primaryKey))
  7421. {
  7422. $values=array();
  7423. foreach($table->primaryKey as $name)
  7424. $values[$name]=$this->$name;
  7425. return $values;
  7426. }
  7427. else
  7428. return null;
  7429. }
  7430. public function setPrimaryKey($value)
  7431. {
  7432. $this->_pk=$this->getPrimaryKey();
  7433. $table=$this->getMetaData()->tableSchema;
  7434. if(is_string($table->primaryKey))
  7435. $this->{$table->primaryKey}=$value;
  7436. elseif(is_array($table->primaryKey))
  7437. {
  7438. foreach($table->primaryKey as $name)
  7439. $this->$name=$value[$name];
  7440. }
  7441. }
  7442. public function getOldPrimaryKey()
  7443. {
  7444. return $this->_pk;
  7445. }
  7446. public function setOldPrimaryKey($value)
  7447. {
  7448. $this->_pk=$value;
  7449. }
  7450. protected function query($criteria,$all=false)
  7451. {
  7452. $this->beforeFind();
  7453. $this->applyScopes($criteria);
  7454. if(empty($criteria->with))
  7455. {
  7456. if(!$all)
  7457. $criteria->limit=1;
  7458. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  7459. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  7460. }
  7461. else
  7462. {
  7463. $finder=new CActiveFinder($this,$criteria->with);
  7464. return $finder->query($criteria,$all);
  7465. }
  7466. }
  7467. public function applyScopes(&$criteria)
  7468. {
  7469. if(!empty($criteria->scopes))
  7470. {
  7471. $scs=$this->scopes();
  7472. $c=$this->getDbCriteria();
  7473. foreach((array)$criteria->scopes as $k=>$v)
  7474. {
  7475. if(is_integer($k))
  7476. {
  7477. if(is_string($v))
  7478. {
  7479. if(isset($scs[$v]))
  7480. {
  7481. $c->mergeWith($scs[$v],true);
  7482. continue;
  7483. }
  7484. $scope=$v;
  7485. $params=array();
  7486. }
  7487. elseif(is_array($v))
  7488. {
  7489. $scope=key($v);
  7490. $params=current($v);
  7491. }
  7492. }
  7493. elseif(is_string($k))
  7494. {
  7495. $scope=$k;
  7496. $params=$v;
  7497. }
  7498. call_user_func_array(array($this,$scope),(array)$params);
  7499. }
  7500. }
  7501. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  7502. {
  7503. $c->mergeWith($criteria);
  7504. $criteria=$c;
  7505. $this->resetScope(false);
  7506. }
  7507. }
  7508. public function getTableAlias($quote=false, $checkScopes=true)
  7509. {
  7510. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  7511. $alias=$criteria->alias;
  7512. else
  7513. $alias=$this->_alias;
  7514. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  7515. }
  7516. public function setTableAlias($alias)
  7517. {
  7518. $this->_alias=$alias;
  7519. }
  7520. public function find($condition='',$params=array())
  7521. {
  7522. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7523. return $this->query($criteria);
  7524. }
  7525. public function findAll($condition='',$params=array())
  7526. {
  7527. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7528. return $this->query($criteria,true);
  7529. }
  7530. public function findByPk($pk,$condition='',$params=array())
  7531. {
  7532. $prefix=$this->getTableAlias(true).'.';
  7533. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7534. return $this->query($criteria);
  7535. }
  7536. public function findAllByPk($pk,$condition='',$params=array())
  7537. {
  7538. $prefix=$this->getTableAlias(true).'.';
  7539. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7540. return $this->query($criteria,true);
  7541. }
  7542. public function findByAttributes($attributes,$condition='',$params=array())
  7543. {
  7544. $prefix=$this->getTableAlias(true).'.';
  7545. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7546. return $this->query($criteria);
  7547. }
  7548. public function findAllByAttributes($attributes,$condition='',$params=array())
  7549. {
  7550. $prefix=$this->getTableAlias(true).'.';
  7551. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7552. return $this->query($criteria,true);
  7553. }
  7554. public function findBySql($sql,$params=array())
  7555. {
  7556. $this->beforeFind();
  7557. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7558. {
  7559. $this->resetScope(false);
  7560. $finder=new CActiveFinder($this,$criteria->with);
  7561. return $finder->findBySql($sql,$params);
  7562. }
  7563. else
  7564. {
  7565. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7566. return $this->populateRecord($command->queryRow());
  7567. }
  7568. }
  7569. public function findAllBySql($sql,$params=array())
  7570. {
  7571. $this->beforeFind();
  7572. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7573. {
  7574. $this->resetScope(false);
  7575. $finder=new CActiveFinder($this,$criteria->with);
  7576. return $finder->findAllBySql($sql,$params);
  7577. }
  7578. else
  7579. {
  7580. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7581. return $this->populateRecords($command->queryAll());
  7582. }
  7583. }
  7584. public function count($condition='',$params=array())
  7585. {
  7586. $builder=$this->getCommandBuilder();
  7587. $criteria=$builder->createCriteria($condition,$params);
  7588. $this->applyScopes($criteria);
  7589. if(empty($criteria->with))
  7590. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7591. else
  7592. {
  7593. $finder=new CActiveFinder($this,$criteria->with);
  7594. return $finder->count($criteria);
  7595. }
  7596. }
  7597. public function countByAttributes($attributes,$condition='',$params=array())
  7598. {
  7599. $prefix=$this->getTableAlias(true).'.';
  7600. $builder=$this->getCommandBuilder();
  7601. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7602. $this->applyScopes($criteria);
  7603. if(empty($criteria->with))
  7604. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7605. else
  7606. {
  7607. $finder=new CActiveFinder($this,$criteria->with);
  7608. return $finder->count($criteria);
  7609. }
  7610. }
  7611. public function countBySql($sql,$params=array())
  7612. {
  7613. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  7614. }
  7615. public function exists($condition='',$params=array())
  7616. {
  7617. $builder=$this->getCommandBuilder();
  7618. $criteria=$builder->createCriteria($condition,$params);
  7619. $table=$this->getTableSchema();
  7620. $criteria->select='1';
  7621. $criteria->limit=1;
  7622. $this->applyScopes($criteria);
  7623. if(empty($criteria->with))
  7624. return $builder->createFindCommand($table,$criteria)->queryRow()!==false;
  7625. else
  7626. {
  7627. $criteria->select='*';
  7628. $finder=new CActiveFinder($this,$criteria->with);
  7629. return $finder->count($criteria)>0;
  7630. }
  7631. }
  7632. public function with()
  7633. {
  7634. if(func_num_args()>0)
  7635. {
  7636. $with=func_get_args();
  7637. if(is_array($with[0])) // the parameter is given as an array
  7638. $with=$with[0];
  7639. if(!empty($with))
  7640. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  7641. }
  7642. return $this;
  7643. }
  7644. public function together()
  7645. {
  7646. $this->getDbCriteria()->together=true;
  7647. return $this;
  7648. }
  7649. public function updateByPk($pk,$attributes,$condition='',$params=array())
  7650. {
  7651. $builder=$this->getCommandBuilder();
  7652. $table=$this->getTableSchema();
  7653. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  7654. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  7655. return $command->execute();
  7656. }
  7657. public function updateAll($attributes,$condition='',$params=array())
  7658. {
  7659. $builder=$this->getCommandBuilder();
  7660. $criteria=$builder->createCriteria($condition,$params);
  7661. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  7662. return $command->execute();
  7663. }
  7664. public function updateCounters($counters,$condition='',$params=array())
  7665. {
  7666. $builder=$this->getCommandBuilder();
  7667. $criteria=$builder->createCriteria($condition,$params);
  7668. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7669. return $command->execute();
  7670. }
  7671. public function deleteByPk($pk,$condition='',$params=array())
  7672. {
  7673. $builder=$this->getCommandBuilder();
  7674. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  7675. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7676. return $command->execute();
  7677. }
  7678. public function deleteAll($condition='',$params=array())
  7679. {
  7680. $builder=$this->getCommandBuilder();
  7681. $criteria=$builder->createCriteria($condition,$params);
  7682. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7683. return $command->execute();
  7684. }
  7685. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  7686. {
  7687. $builder=$this->getCommandBuilder();
  7688. $table=$this->getTableSchema();
  7689. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  7690. $command=$builder->createDeleteCommand($table,$criteria);
  7691. return $command->execute();
  7692. }
  7693. public function populateRecord($attributes,$callAfterFind=true)
  7694. {
  7695. if($attributes!==false)
  7696. {
  7697. $record=$this->instantiate($attributes);
  7698. $record->setScenario('update');
  7699. $record->init();
  7700. $md=$record->getMetaData();
  7701. foreach($attributes as $name=>$value)
  7702. {
  7703. if(property_exists($record,$name))
  7704. $record->$name=$value;
  7705. elseif(isset($md->columns[$name]))
  7706. $record->_attributes[$name]=$value;
  7707. }
  7708. $record->_pk=$record->getPrimaryKey();
  7709. $record->attachBehaviors($record->behaviors());
  7710. if($callAfterFind)
  7711. $record->afterFind();
  7712. return $record;
  7713. }
  7714. else
  7715. return null;
  7716. }
  7717. public function populateRecords($data,$callAfterFind=true,$index=null)
  7718. {
  7719. $records=array();
  7720. foreach($data as $attributes)
  7721. {
  7722. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  7723. {
  7724. if($index===null)
  7725. $records[]=$record;
  7726. else
  7727. $records[$record->$index]=$record;
  7728. }
  7729. }
  7730. return $records;
  7731. }
  7732. protected function instantiate($attributes)
  7733. {
  7734. $class=get_class($this);
  7735. $model=new $class(null);
  7736. return $model;
  7737. }
  7738. public function offsetExists($offset)
  7739. {
  7740. return $this->__isset($offset);
  7741. }
  7742. }
  7743. class CBaseActiveRelation extends CComponent
  7744. {
  7745. public $name;
  7746. public $className;
  7747. public $foreignKey;
  7748. public $select='*';
  7749. public $condition='';
  7750. public $params=array();
  7751. public $group='';
  7752. public $join='';
  7753. public $having='';
  7754. public $order='';
  7755. public function __construct($name,$className,$foreignKey,$options=array())
  7756. {
  7757. $this->name=$name;
  7758. $this->className=$className;
  7759. $this->foreignKey=$foreignKey;
  7760. foreach($options as $name=>$value)
  7761. $this->$name=$value;
  7762. }
  7763. public function mergeWith($criteria,$fromScope=false)
  7764. {
  7765. if($criteria instanceof CDbCriteria)
  7766. $criteria=$criteria->toArray();
  7767. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  7768. {
  7769. if($this->select==='*')
  7770. $this->select=$criteria['select'];
  7771. elseif($criteria['select']!=='*')
  7772. {
  7773. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  7774. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  7775. $this->select=array_merge($select1,array_diff($select2,$select1));
  7776. }
  7777. }
  7778. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  7779. {
  7780. if($this->condition==='')
  7781. $this->condition=$criteria['condition'];
  7782. elseif($criteria['condition']!=='')
  7783. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  7784. }
  7785. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  7786. $this->params=array_merge($this->params,$criteria['params']);
  7787. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  7788. {
  7789. if($this->order==='')
  7790. $this->order=$criteria['order'];
  7791. elseif($criteria['order']!=='')
  7792. $this->order=$criteria['order'].', '.$this->order;
  7793. }
  7794. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  7795. {
  7796. if($this->group==='')
  7797. $this->group=$criteria['group'];
  7798. elseif($criteria['group']!=='')
  7799. $this->group.=', '.$criteria['group'];
  7800. }
  7801. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  7802. {
  7803. if($this->join==='')
  7804. $this->join=$criteria['join'];
  7805. elseif($criteria['join']!=='')
  7806. $this->join.=' '.$criteria['join'];
  7807. }
  7808. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  7809. {
  7810. if($this->having==='')
  7811. $this->having=$criteria['having'];
  7812. elseif($criteria['having']!=='')
  7813. $this->having="({$this->having}) AND ({$criteria['having']})";
  7814. }
  7815. }
  7816. }
  7817. class CStatRelation extends CBaseActiveRelation
  7818. {
  7819. public $select='COUNT(*)';
  7820. public $defaultValue=0;
  7821. public function mergeWith($criteria,$fromScope=false)
  7822. {
  7823. if($criteria instanceof CDbCriteria)
  7824. $criteria=$criteria->toArray();
  7825. parent::mergeWith($criteria,$fromScope);
  7826. if(isset($criteria['defaultValue']))
  7827. $this->defaultValue=$criteria['defaultValue'];
  7828. }
  7829. }
  7830. class CActiveRelation extends CBaseActiveRelation
  7831. {
  7832. public $joinType='LEFT OUTER JOIN';
  7833. public $on='';
  7834. public $alias;
  7835. public $with=array();
  7836. public $together;
  7837. public $scopes;
  7838. public function mergeWith($criteria,$fromScope=false)
  7839. {
  7840. if($criteria instanceof CDbCriteria)
  7841. $criteria=$criteria->toArray();
  7842. if($fromScope)
  7843. {
  7844. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  7845. {
  7846. if($this->on==='')
  7847. $this->on=$criteria['condition'];
  7848. elseif($criteria['condition']!=='')
  7849. $this->on="({$this->on}) AND ({$criteria['condition']})";
  7850. }
  7851. unset($criteria['condition']);
  7852. }
  7853. parent::mergeWith($criteria);
  7854. if(isset($criteria['joinType']))
  7855. $this->joinType=$criteria['joinType'];
  7856. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  7857. {
  7858. if($this->on==='')
  7859. $this->on=$criteria['on'];
  7860. elseif($criteria['on']!=='')
  7861. $this->on="({$this->on}) AND ({$criteria['on']})";
  7862. }
  7863. if(isset($criteria['with']))
  7864. $this->with=$criteria['with'];
  7865. if(isset($criteria['alias']))
  7866. $this->alias=$criteria['alias'];
  7867. if(isset($criteria['together']))
  7868. $this->together=$criteria['together'];
  7869. }
  7870. }
  7871. class CBelongsToRelation extends CActiveRelation
  7872. {
  7873. }
  7874. class CHasOneRelation extends CActiveRelation
  7875. {
  7876. public $through;
  7877. }
  7878. class CHasManyRelation extends CActiveRelation
  7879. {
  7880. public $limit=-1;
  7881. public $offset=-1;
  7882. public $index;
  7883. public $through;
  7884. public function mergeWith($criteria,$fromScope=false)
  7885. {
  7886. if($criteria instanceof CDbCriteria)
  7887. $criteria=$criteria->toArray();
  7888. parent::mergeWith($criteria,$fromScope);
  7889. if(isset($criteria['limit']) && $criteria['limit']>0)
  7890. $this->limit=$criteria['limit'];
  7891. if(isset($criteria['offset']) && $criteria['offset']>=0)
  7892. $this->offset=$criteria['offset'];
  7893. if(isset($criteria['index']))
  7894. $this->index=$criteria['index'];
  7895. }
  7896. }
  7897. class CManyManyRelation extends CHasManyRelation
  7898. {
  7899. private $_junctionTableName=null;
  7900. private $_junctionForeignKeys=null;
  7901. public function getJunctionTableName()
  7902. {
  7903. if ($this->_junctionTableName===null)
  7904. $this->initJunctionData();
  7905. return $this->_junctionTableName;
  7906. }
  7907. public function getJunctionForeignKeys()
  7908. {
  7909. if ($this->_junctionForeignKeys===null)
  7910. $this->initJunctionData();
  7911. return $this->_junctionForeignKeys;
  7912. }
  7913. private function initJunctionData()
  7914. {
  7915. if(!preg_match('/^\s*(.*?)\((.*)\)\s*$/',$this->foreignKey,$matches))
  7916. 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,...)".',
  7917. array('{class}'=>$this->className,'{relation}'=>$this->name)));
  7918. $this->_junctionTableName=$matches[1];
  7919. $this->_junctionForeignKeys=preg_split('/\s*,\s*/',$matches[2],-1,PREG_SPLIT_NO_EMPTY);
  7920. }
  7921. }
  7922. class CActiveRecordMetaData
  7923. {
  7924. public $tableSchema;
  7925. public $columns;
  7926. public $relations=array();
  7927. public $attributeDefaults=array();
  7928. private $_model;
  7929. public function __construct($model)
  7930. {
  7931. $this->_model=$model;
  7932. $tableName=$model->tableName();
  7933. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  7934. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  7935. array('{class}'=>get_class($model),'{table}'=>$tableName)));
  7936. if($table->primaryKey===null)
  7937. {
  7938. $table->primaryKey=$model->primaryKey();
  7939. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  7940. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  7941. elseif(is_array($table->primaryKey))
  7942. {
  7943. foreach($table->primaryKey as $name)
  7944. {
  7945. if(isset($table->columns[$name]))
  7946. $table->columns[$name]->isPrimaryKey=true;
  7947. }
  7948. }
  7949. }
  7950. $this->tableSchema=$table;
  7951. $this->columns=$table->columns;
  7952. foreach($table->columns as $name=>$column)
  7953. {
  7954. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  7955. $this->attributeDefaults[$name]=$column->defaultValue;
  7956. }
  7957. foreach($model->relations() as $name=>$config)
  7958. {
  7959. $this->addRelation($name,$config);
  7960. }
  7961. }
  7962. public function addRelation($name,$config)
  7963. {
  7964. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  7965. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  7966. else
  7967. throw new CDbException(Yii::t('yii','Active record "{class}" has an invalid configuration for relation "{relation}". It must specify the relation type, the related active record class and the foreign key.', array('{class}'=>get_class($this->_model),'{relation}'=>$name)));
  7968. }
  7969. public function hasRelation($name)
  7970. {
  7971. return isset($this->relations[$name]);
  7972. }
  7973. public function removeRelation($name)
  7974. {
  7975. unset($this->relations[$name]);
  7976. }
  7977. }
  7978. class CDbConnection extends CApplicationComponent
  7979. {
  7980. public $connectionString;
  7981. public $username='';
  7982. public $password='';
  7983. public $schemaCachingDuration=0;
  7984. public $schemaCachingExclude=array();
  7985. public $schemaCacheID='cache';
  7986. public $queryCachingDuration=0;
  7987. public $queryCachingDependency;
  7988. public $queryCachingCount=0;
  7989. public $queryCacheID='cache';
  7990. public $autoConnect=true;
  7991. public $charset;
  7992. public $emulatePrepare;
  7993. public $enableParamLogging=false;
  7994. public $enableProfiling=false;
  7995. public $tablePrefix;
  7996. public $initSQLs;
  7997. public $driverMap=array(
  7998. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  7999. 'mysqli'=>'CMysqlSchema', // MySQL
  8000. 'mysql'=>'CMysqlSchema', // MySQL
  8001. 'sqlite'=>'CSqliteSchema', // sqlite 3
  8002. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  8003. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  8004. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  8005. 'sqlsrv'=>'CMssqlSchema', // Mssql
  8006. 'oci'=>'COciSchema', // Oracle driver
  8007. );
  8008. public $pdoClass = 'PDO';
  8009. private $_attributes=array();
  8010. private $_active=false;
  8011. private $_pdo;
  8012. private $_transaction;
  8013. private $_schema;
  8014. public function __construct($dsn='',$username='',$password='')
  8015. {
  8016. $this->connectionString=$dsn;
  8017. $this->username=$username;
  8018. $this->password=$password;
  8019. }
  8020. public function __sleep()
  8021. {
  8022. $this->close();
  8023. return array_keys(get_object_vars($this));
  8024. }
  8025. public static function getAvailableDrivers()
  8026. {
  8027. return PDO::getAvailableDrivers();
  8028. }
  8029. public function init()
  8030. {
  8031. parent::init();
  8032. if($this->autoConnect)
  8033. $this->setActive(true);
  8034. }
  8035. public function getActive()
  8036. {
  8037. return $this->_active;
  8038. }
  8039. public function setActive($value)
  8040. {
  8041. if($value!=$this->_active)
  8042. {
  8043. if($value)
  8044. $this->open();
  8045. else
  8046. $this->close();
  8047. }
  8048. }
  8049. public function cache($duration, $dependency=null, $queryCount=1)
  8050. {
  8051. $this->queryCachingDuration=$duration;
  8052. $this->queryCachingDependency=$dependency;
  8053. $this->queryCachingCount=$queryCount;
  8054. return $this;
  8055. }
  8056. protected function open()
  8057. {
  8058. if($this->_pdo===null)
  8059. {
  8060. if(empty($this->connectionString))
  8061. throw new CDbException('CDbConnection.connectionString cannot be empty.');
  8062. try
  8063. {
  8064. $this->_pdo=$this->createPdoInstance();
  8065. $this->initConnection($this->_pdo);
  8066. $this->_active=true;
  8067. }
  8068. catch(PDOException $e)
  8069. {
  8070. if(YII_DEBUG)
  8071. {
  8072. throw new CDbException('CDbConnection failed to open the DB connection: '.
  8073. $e->getMessage(),(int)$e->getCode(),$e->errorInfo);
  8074. }
  8075. else
  8076. {
  8077. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  8078. throw new CDbException('CDbConnection failed to open the DB connection.',(int)$e->getCode(),$e->errorInfo);
  8079. }
  8080. }
  8081. }
  8082. }
  8083. protected function close()
  8084. {
  8085. $this->_pdo=null;
  8086. $this->_active=false;
  8087. $this->_schema=null;
  8088. }
  8089. protected function createPdoInstance()
  8090. {
  8091. $pdoClass=$this->pdoClass;
  8092. if(($pos=strpos($this->connectionString,':'))!==false)
  8093. {
  8094. $driver=strtolower(substr($this->connectionString,0,$pos));
  8095. if($driver==='mssql' || $driver==='dblib')
  8096. $pdoClass='CMssqlPdoAdapter';
  8097. elseif($driver==='sqlsrv')
  8098. $pdoClass='CMssqlSqlsrvPdoAdapter';
  8099. }
  8100. return new $pdoClass($this->connectionString,$this->username,
  8101. $this->password,$this->_attributes);
  8102. }
  8103. protected function initConnection($pdo)
  8104. {
  8105. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  8106. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  8107. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  8108. if($this->charset!==null)
  8109. {
  8110. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  8111. if(in_array($driver,array('pgsql','mysql','mysqli')))
  8112. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  8113. }
  8114. if($this->initSQLs!==null)
  8115. {
  8116. foreach($this->initSQLs as $sql)
  8117. $pdo->exec($sql);
  8118. }
  8119. }
  8120. public function getPdoInstance()
  8121. {
  8122. return $this->_pdo;
  8123. }
  8124. public function createCommand($query=null)
  8125. {
  8126. $this->setActive(true);
  8127. return new CDbCommand($this,$query);
  8128. }
  8129. public function getCurrentTransaction()
  8130. {
  8131. if($this->_transaction!==null)
  8132. {
  8133. if($this->_transaction->getActive())
  8134. return $this->_transaction;
  8135. }
  8136. return null;
  8137. }
  8138. public function beginTransaction()
  8139. {
  8140. $this->setActive(true);
  8141. $this->_pdo->beginTransaction();
  8142. return $this->_transaction=new CDbTransaction($this);
  8143. }
  8144. public function getSchema()
  8145. {
  8146. if($this->_schema!==null)
  8147. return $this->_schema;
  8148. else
  8149. {
  8150. $driver=$this->getDriverName();
  8151. if(isset($this->driverMap[$driver]))
  8152. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  8153. else
  8154. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  8155. array('{driver}'=>$driver)));
  8156. }
  8157. }
  8158. public function getCommandBuilder()
  8159. {
  8160. return $this->getSchema()->getCommandBuilder();
  8161. }
  8162. public function getLastInsertID($sequenceName='')
  8163. {
  8164. $this->setActive(true);
  8165. return $this->_pdo->lastInsertId($sequenceName);
  8166. }
  8167. public function quoteValue($str)
  8168. {
  8169. if(is_int($str) || is_float($str))
  8170. return $str;
  8171. $this->setActive(true);
  8172. if(($value=$this->_pdo->quote($str))!==false)
  8173. return $value;
  8174. else // the driver doesn't support quote (e.g. oci)
  8175. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  8176. }
  8177. public function quoteTableName($name)
  8178. {
  8179. return $this->getSchema()->quoteTableName($name);
  8180. }
  8181. public function quoteColumnName($name)
  8182. {
  8183. return $this->getSchema()->quoteColumnName($name);
  8184. }
  8185. public function getPdoType($type)
  8186. {
  8187. static $map=array
  8188. (
  8189. 'boolean'=>PDO::PARAM_BOOL,
  8190. 'integer'=>PDO::PARAM_INT,
  8191. 'string'=>PDO::PARAM_STR,
  8192. 'resource'=>PDO::PARAM_LOB,
  8193. 'NULL'=>PDO::PARAM_NULL,
  8194. );
  8195. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  8196. }
  8197. public function getColumnCase()
  8198. {
  8199. return $this->getAttribute(PDO::ATTR_CASE);
  8200. }
  8201. public function setColumnCase($value)
  8202. {
  8203. $this->setAttribute(PDO::ATTR_CASE,$value);
  8204. }
  8205. public function getNullConversion()
  8206. {
  8207. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  8208. }
  8209. public function setNullConversion($value)
  8210. {
  8211. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  8212. }
  8213. public function getAutoCommit()
  8214. {
  8215. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  8216. }
  8217. public function setAutoCommit($value)
  8218. {
  8219. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  8220. }
  8221. public function getPersistent()
  8222. {
  8223. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  8224. }
  8225. public function setPersistent($value)
  8226. {
  8227. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  8228. }
  8229. public function getDriverName()
  8230. {
  8231. if(($pos=strpos($this->connectionString, ':'))!==false)
  8232. return strtolower(substr($this->connectionString, 0, $pos));
  8233. // return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  8234. }
  8235. public function getClientVersion()
  8236. {
  8237. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  8238. }
  8239. public function getConnectionStatus()
  8240. {
  8241. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  8242. }
  8243. public function getPrefetch()
  8244. {
  8245. return $this->getAttribute(PDO::ATTR_PREFETCH);
  8246. }
  8247. public function getServerInfo()
  8248. {
  8249. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  8250. }
  8251. public function getServerVersion()
  8252. {
  8253. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  8254. }
  8255. public function getTimeout()
  8256. {
  8257. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  8258. }
  8259. public function getAttribute($name)
  8260. {
  8261. $this->setActive(true);
  8262. return $this->_pdo->getAttribute($name);
  8263. }
  8264. public function setAttribute($name,$value)
  8265. {
  8266. if($this->_pdo instanceof PDO)
  8267. $this->_pdo->setAttribute($name,$value);
  8268. else
  8269. $this->_attributes[$name]=$value;
  8270. }
  8271. public function getAttributes()
  8272. {
  8273. return $this->_attributes;
  8274. }
  8275. public function setAttributes($values)
  8276. {
  8277. foreach($values as $name=>$value)
  8278. $this->_attributes[$name]=$value;
  8279. }
  8280. public function getStats()
  8281. {
  8282. $logger=Yii::getLogger();
  8283. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  8284. $count=count($timings);
  8285. $time=array_sum($timings);
  8286. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  8287. $count+=count($timings);
  8288. $time+=array_sum($timings);
  8289. return array($count,$time);
  8290. }
  8291. }
  8292. abstract class CDbSchema extends CComponent
  8293. {
  8294. public $columnTypes=array();
  8295. private $_tableNames=array();
  8296. private $_tables=array();
  8297. private $_connection;
  8298. private $_builder;
  8299. private $_cacheExclude=array();
  8300. abstract protected function loadTable($name);
  8301. public function __construct($conn)
  8302. {
  8303. $this->_connection=$conn;
  8304. foreach($conn->schemaCachingExclude as $name)
  8305. $this->_cacheExclude[$name]=true;
  8306. }
  8307. public function getDbConnection()
  8308. {
  8309. return $this->_connection;
  8310. }
  8311. public function getTable($name,$refresh=false)
  8312. {
  8313. if($refresh===false && isset($this->_tables[$name]))
  8314. return $this->_tables[$name];
  8315. else
  8316. {
  8317. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  8318. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  8319. else
  8320. $realName=$name;
  8321. // temporarily disable query caching
  8322. if($this->_connection->queryCachingDuration>0)
  8323. {
  8324. $qcDuration=$this->_connection->queryCachingDuration;
  8325. $this->_connection->queryCachingDuration=0;
  8326. }
  8327. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8328. {
  8329. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8330. $table=$cache->get($key);
  8331. if($refresh===true || $table===false)
  8332. {
  8333. $table=$this->loadTable($realName);
  8334. if($table!==null)
  8335. $cache->set($key,$table,$duration);
  8336. }
  8337. $this->_tables[$name]=$table;
  8338. }
  8339. else
  8340. $this->_tables[$name]=$table=$this->loadTable($realName);
  8341. if(isset($qcDuration)) // re-enable query caching
  8342. $this->_connection->queryCachingDuration=$qcDuration;
  8343. return $table;
  8344. }
  8345. }
  8346. public function getTables($schema='')
  8347. {
  8348. $tables=array();
  8349. foreach($this->getTableNames($schema) as $name)
  8350. {
  8351. if(($table=$this->getTable($name))!==null)
  8352. $tables[$name]=$table;
  8353. }
  8354. return $tables;
  8355. }
  8356. public function getTableNames($schema='')
  8357. {
  8358. if(!isset($this->_tableNames[$schema]))
  8359. $this->_tableNames[$schema]=$this->findTableNames($schema);
  8360. return $this->_tableNames[$schema];
  8361. }
  8362. public function getCommandBuilder()
  8363. {
  8364. if($this->_builder!==null)
  8365. return $this->_builder;
  8366. else
  8367. return $this->_builder=$this->createCommandBuilder();
  8368. }
  8369. public function refresh()
  8370. {
  8371. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8372. {
  8373. foreach(array_keys($this->_tables) as $name)
  8374. {
  8375. if(!isset($this->_cacheExclude[$name]))
  8376. {
  8377. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8378. $cache->delete($key);
  8379. }
  8380. }
  8381. }
  8382. $this->_tables=array();
  8383. $this->_tableNames=array();
  8384. $this->_builder=null;
  8385. }
  8386. public function quoteTableName($name)
  8387. {
  8388. if(strpos($name,'.')===false)
  8389. return $this->quoteSimpleTableName($name);
  8390. $parts=explode('.',$name);
  8391. foreach($parts as $i=>$part)
  8392. $parts[$i]=$this->quoteSimpleTableName($part);
  8393. return implode('.',$parts);
  8394. }
  8395. public function quoteSimpleTableName($name)
  8396. {
  8397. return "'".$name."'";
  8398. }
  8399. public function quoteColumnName($name)
  8400. {
  8401. if(($pos=strrpos($name,'.'))!==false)
  8402. {
  8403. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  8404. $name=substr($name,$pos+1);
  8405. }
  8406. else
  8407. $prefix='';
  8408. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  8409. }
  8410. public function quoteSimpleColumnName($name)
  8411. {
  8412. return '"'.$name.'"';
  8413. }
  8414. public function compareTableNames($name1,$name2)
  8415. {
  8416. $name1=str_replace(array('"','`',"'"),'',$name1);
  8417. $name2=str_replace(array('"','`',"'"),'',$name2);
  8418. if(($pos=strrpos($name1,'.'))!==false)
  8419. $name1=substr($name1,$pos+1);
  8420. if(($pos=strrpos($name2,'.'))!==false)
  8421. $name2=substr($name2,$pos+1);
  8422. if($this->_connection->tablePrefix!==null)
  8423. {
  8424. if(strpos($name1,'{')!==false)
  8425. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  8426. if(strpos($name2,'{')!==false)
  8427. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  8428. }
  8429. return $name1===$name2;
  8430. }
  8431. public function resetSequence($table,$value=null)
  8432. {
  8433. }
  8434. public function checkIntegrity($check=true,$schema='')
  8435. {
  8436. }
  8437. protected function createCommandBuilder()
  8438. {
  8439. return new CDbCommandBuilder($this);
  8440. }
  8441. protected function findTableNames($schema='')
  8442. {
  8443. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  8444. array('{class}'=>get_class($this))));
  8445. }
  8446. public function getColumnType($type)
  8447. {
  8448. if(isset($this->columnTypes[$type]))
  8449. return $this->columnTypes[$type];
  8450. elseif(($pos=strpos($type,' '))!==false)
  8451. {
  8452. $t=substr($type,0,$pos);
  8453. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  8454. }
  8455. else
  8456. return $type;
  8457. }
  8458. public function createTable($table, $columns, $options=null)
  8459. {
  8460. $cols=array();
  8461. foreach($columns as $name=>$type)
  8462. {
  8463. if(is_string($name))
  8464. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  8465. else
  8466. $cols[]="\t".$type;
  8467. }
  8468. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  8469. return $options===null ? $sql : $sql.' '.$options;
  8470. }
  8471. public function renameTable($table, $newName)
  8472. {
  8473. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  8474. }
  8475. public function dropTable($table)
  8476. {
  8477. return "DROP TABLE ".$this->quoteTableName($table);
  8478. }
  8479. public function truncateTable($table)
  8480. {
  8481. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  8482. }
  8483. public function addColumn($table, $column, $type)
  8484. {
  8485. return 'ALTER TABLE ' . $this->quoteTableName($table)
  8486. . ' ADD ' . $this->quoteColumnName($column) . ' '
  8487. . $this->getColumnType($type);
  8488. }
  8489. public function dropColumn($table, $column)
  8490. {
  8491. return "ALTER TABLE ".$this->quoteTableName($table)
  8492. ." DROP COLUMN ".$this->quoteColumnName($column);
  8493. }
  8494. public function renameColumn($table, $name, $newName)
  8495. {
  8496. return "ALTER TABLE ".$this->quoteTableName($table)
  8497. . " RENAME COLUMN ".$this->quoteColumnName($name)
  8498. . " TO ".$this->quoteColumnName($newName);
  8499. }
  8500. public function alterColumn($table, $column, $type)
  8501. {
  8502. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  8503. . $this->quoteColumnName($column) . ' '
  8504. . $this->quoteColumnName($column) . ' '
  8505. . $this->getColumnType($type);
  8506. }
  8507. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8508. {
  8509. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  8510. foreach($columns as $i=>$col)
  8511. $columns[$i]=$this->quoteColumnName($col);
  8512. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  8513. foreach($refColumns as $i=>$col)
  8514. $refColumns[$i]=$this->quoteColumnName($col);
  8515. $sql='ALTER TABLE '.$this->quoteTableName($table)
  8516. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  8517. .' FOREIGN KEY ('.implode(', ', $columns).')'
  8518. .' REFERENCES '.$this->quoteTableName($refTable)
  8519. .' ('.implode(', ', $refColumns).')';
  8520. if($delete!==null)
  8521. $sql.=' ON DELETE '.$delete;
  8522. if($update!==null)
  8523. $sql.=' ON UPDATE '.$update;
  8524. return $sql;
  8525. }
  8526. public function dropForeignKey($name, $table)
  8527. {
  8528. return 'ALTER TABLE '.$this->quoteTableName($table)
  8529. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  8530. }
  8531. public function createIndex($name, $table, $column, $unique=false)
  8532. {
  8533. $cols=array();
  8534. $columns=preg_split('/\s*,\s*/',$column,-1,PREG_SPLIT_NO_EMPTY);
  8535. foreach($columns as $col)
  8536. {
  8537. if(strpos($col,'(')!==false)
  8538. $cols[]=$col;
  8539. else
  8540. $cols[]=$this->quoteColumnName($col);
  8541. }
  8542. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  8543. . $this->quoteTableName($name).' ON '
  8544. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  8545. }
  8546. public function dropIndex($name, $table)
  8547. {
  8548. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  8549. }
  8550. public function addPrimaryKey($name,$table,$columns)
  8551. {
  8552. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  8553. foreach($columns as $i=>$col)
  8554. $columns[$i]=$this->quoteColumnName($col);
  8555. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' ADD CONSTRAINT '
  8556. . $this->quoteColumnName($name) . ' PRIMARY KEY ('
  8557. . implode(', ', $columns). ' )';
  8558. }
  8559. public function dropPrimaryKey($name,$table)
  8560. {
  8561. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' DROP CONSTRAINT '
  8562. . $this->quoteColumnName($name);
  8563. }
  8564. }
  8565. class CSqliteSchema extends CDbSchema
  8566. {
  8567. public $columnTypes=array(
  8568. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  8569. 'string' => 'varchar(255)',
  8570. 'text' => 'text',
  8571. 'integer' => 'integer',
  8572. 'float' => 'float',
  8573. 'decimal' => 'decimal',
  8574. 'datetime' => 'datetime',
  8575. 'timestamp' => 'timestamp',
  8576. 'time' => 'time',
  8577. 'date' => 'date',
  8578. 'binary' => 'blob',
  8579. 'boolean' => 'tinyint(1)',
  8580. 'money' => 'decimal(19,4)',
  8581. );
  8582. public function resetSequence($table,$value=null)
  8583. {
  8584. if($table->sequenceName!==null)
  8585. {
  8586. if($value===null)
  8587. $value=$this->getDbConnection()->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")->queryScalar();
  8588. else
  8589. $value=(int)$value-1;
  8590. try
  8591. {
  8592. // it's possible sqlite_sequence does not exist
  8593. $this->getDbConnection()->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")->execute();
  8594. }
  8595. catch(Exception $e)
  8596. {
  8597. }
  8598. }
  8599. }
  8600. public function checkIntegrity($check=true,$schema='')
  8601. {
  8602. // SQLite doesn't enforce integrity
  8603. return;
  8604. }
  8605. protected function findTableNames($schema='')
  8606. {
  8607. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  8608. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  8609. }
  8610. protected function createCommandBuilder()
  8611. {
  8612. return new CSqliteCommandBuilder($this);
  8613. }
  8614. protected function loadTable($name)
  8615. {
  8616. $table=new CDbTableSchema;
  8617. $table->name=$name;
  8618. $table->rawName=$this->quoteTableName($name);
  8619. if($this->findColumns($table))
  8620. {
  8621. $this->findConstraints($table);
  8622. return $table;
  8623. }
  8624. else
  8625. return null;
  8626. }
  8627. protected function findColumns($table)
  8628. {
  8629. $sql="PRAGMA table_info({$table->rawName})";
  8630. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  8631. if(empty($columns))
  8632. return false;
  8633. foreach($columns as $column)
  8634. {
  8635. $c=$this->createColumn($column);
  8636. $table->columns[$c->name]=$c;
  8637. if($c->isPrimaryKey)
  8638. {
  8639. if($table->primaryKey===null)
  8640. $table->primaryKey=$c->name;
  8641. elseif(is_string($table->primaryKey))
  8642. $table->primaryKey=array($table->primaryKey,$c->name);
  8643. else
  8644. $table->primaryKey[]=$c->name;
  8645. }
  8646. }
  8647. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  8648. {
  8649. $table->sequenceName='';
  8650. $table->columns[$table->primaryKey]->autoIncrement=true;
  8651. }
  8652. return true;
  8653. }
  8654. protected function findConstraints($table)
  8655. {
  8656. $foreignKeys=array();
  8657. $sql="PRAGMA foreign_key_list({$table->rawName})";
  8658. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  8659. foreach($keys as $key)
  8660. {
  8661. $column=$table->columns[$key['from']];
  8662. $column->isForeignKey=true;
  8663. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  8664. }
  8665. $table->foreignKeys=$foreignKeys;
  8666. }
  8667. protected function createColumn($column)
  8668. {
  8669. $c=new CSqliteColumnSchema;
  8670. $c->name=$column['name'];
  8671. $c->rawName=$this->quoteColumnName($c->name);
  8672. $c->allowNull=!$column['notnull'];
  8673. $c->isPrimaryKey=$column['pk']!=0;
  8674. $c->isForeignKey=false;
  8675. $c->comment=null; // SQLite does not support column comments at all
  8676. $c->init(strtolower($column['type']),$column['dflt_value']);
  8677. return $c;
  8678. }
  8679. public function renameTable($table, $newName)
  8680. {
  8681. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' RENAME TO ' . $this->quoteTableName($newName);
  8682. }
  8683. public function truncateTable($table)
  8684. {
  8685. return "DELETE FROM ".$this->quoteTableName($table);
  8686. }
  8687. public function dropColumn($table, $column)
  8688. {
  8689. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  8690. }
  8691. public function renameColumn($table, $name, $newName)
  8692. {
  8693. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  8694. }
  8695. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8696. {
  8697. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  8698. }
  8699. public function dropForeignKey($name, $table)
  8700. {
  8701. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  8702. }
  8703. public function alterColumn($table, $column, $type)
  8704. {
  8705. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  8706. }
  8707. public function dropIndex($name, $table)
  8708. {
  8709. return 'DROP INDEX '.$this->quoteTableName($name);
  8710. }
  8711. public function addPrimaryKey($name,$table,$columns)
  8712. {
  8713. throw new CDbException(Yii::t('yii', 'Adding a primary key after table has been created is not supported by SQLite.'));
  8714. }
  8715. public function dropPrimaryKey($name,$table)
  8716. {
  8717. throw new CDbException(Yii::t('yii', 'Removing a primary key after table has been created is not supported by SQLite.'));
  8718. }
  8719. }
  8720. class CDbTableSchema extends CComponent
  8721. {
  8722. public $name;
  8723. public $rawName;
  8724. public $primaryKey;
  8725. public $sequenceName;
  8726. public $foreignKeys=array();
  8727. public $columns=array();
  8728. public function getColumn($name)
  8729. {
  8730. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  8731. }
  8732. public function getColumnNames()
  8733. {
  8734. return array_keys($this->columns);
  8735. }
  8736. }
  8737. class CDbCommand extends CComponent
  8738. {
  8739. public $params=array();
  8740. private $_connection;
  8741. private $_text;
  8742. private $_statement;
  8743. private $_paramLog=array();
  8744. private $_query;
  8745. private $_fetchMode = array(PDO::FETCH_ASSOC);
  8746. public function __construct(CDbConnection $connection,$query=null)
  8747. {
  8748. $this->_connection=$connection;
  8749. if(is_array($query))
  8750. {
  8751. foreach($query as $name=>$value)
  8752. $this->$name=$value;
  8753. }
  8754. else
  8755. $this->setText($query);
  8756. }
  8757. public function __sleep()
  8758. {
  8759. $this->_statement=null;
  8760. return array_keys(get_object_vars($this));
  8761. }
  8762. public function setFetchMode($mode)
  8763. {
  8764. $params=func_get_args();
  8765. $this->_fetchMode = $params;
  8766. return $this;
  8767. }
  8768. public function reset()
  8769. {
  8770. $this->_text=null;
  8771. $this->_query=null;
  8772. $this->_statement=null;
  8773. $this->_paramLog=array();
  8774. $this->params=array();
  8775. return $this;
  8776. }
  8777. public function getText()
  8778. {
  8779. if($this->_text=='' && !empty($this->_query))
  8780. $this->setText($this->buildQuery($this->_query));
  8781. return $this->_text;
  8782. }
  8783. public function setText($value)
  8784. {
  8785. if($this->_connection->tablePrefix!==null && $value!='')
  8786. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  8787. else
  8788. $this->_text=$value;
  8789. $this->cancel();
  8790. return $this;
  8791. }
  8792. public function getConnection()
  8793. {
  8794. return $this->_connection;
  8795. }
  8796. public function getPdoStatement()
  8797. {
  8798. return $this->_statement;
  8799. }
  8800. public function prepare()
  8801. {
  8802. if($this->_statement==null)
  8803. {
  8804. try
  8805. {
  8806. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  8807. $this->_paramLog=array();
  8808. }
  8809. catch(Exception $e)
  8810. {
  8811. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8812. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  8813. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  8814. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  8815. }
  8816. }
  8817. }
  8818. public function cancel()
  8819. {
  8820. $this->_statement=null;
  8821. }
  8822. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  8823. {
  8824. $this->prepare();
  8825. if($dataType===null)
  8826. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  8827. elseif($length===null)
  8828. $this->_statement->bindParam($name,$value,$dataType);
  8829. elseif($driverOptions===null)
  8830. $this->_statement->bindParam($name,$value,$dataType,$length);
  8831. else
  8832. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  8833. $this->_paramLog[$name]=&$value;
  8834. return $this;
  8835. }
  8836. public function bindValue($name, $value, $dataType=null)
  8837. {
  8838. $this->prepare();
  8839. if($dataType===null)
  8840. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8841. else
  8842. $this->_statement->bindValue($name,$value,$dataType);
  8843. $this->_paramLog[$name]=$value;
  8844. return $this;
  8845. }
  8846. public function bindValues($values)
  8847. {
  8848. $this->prepare();
  8849. foreach($values as $name=>$value)
  8850. {
  8851. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8852. $this->_paramLog[$name]=$value;
  8853. }
  8854. return $this;
  8855. }
  8856. public function execute($params=array())
  8857. {
  8858. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8859. {
  8860. $p=array();
  8861. foreach($pars as $name=>$value)
  8862. $p[$name]=$name.'='.var_export($value,true);
  8863. $par='. Bound with ' .implode(', ',$p);
  8864. }
  8865. else
  8866. $par='';
  8867. try
  8868. {
  8869. if($this->_connection->enableProfiling)
  8870. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  8871. $this->prepare();
  8872. if($params===array())
  8873. $this->_statement->execute();
  8874. else
  8875. $this->_statement->execute($params);
  8876. $n=$this->_statement->rowCount();
  8877. if($this->_connection->enableProfiling)
  8878. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  8879. return $n;
  8880. }
  8881. catch(Exception $e)
  8882. {
  8883. if($this->_connection->enableProfiling)
  8884. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  8885. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  8886. $message=$e->getMessage();
  8887. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  8888. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8889. if(YII_DEBUG)
  8890. $message.='. The SQL statement executed was: '.$this->getText().$par;
  8891. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8892. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8893. }
  8894. }
  8895. public function query($params=array())
  8896. {
  8897. return $this->queryInternal('',0,$params);
  8898. }
  8899. public function queryAll($fetchAssociative=true,$params=array())
  8900. {
  8901. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8902. }
  8903. public function queryRow($fetchAssociative=true,$params=array())
  8904. {
  8905. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8906. }
  8907. public function queryScalar($params=array())
  8908. {
  8909. $result=$this->queryInternal('fetchColumn',0,$params);
  8910. if(is_resource($result) && get_resource_type($result)==='stream')
  8911. return stream_get_contents($result);
  8912. else
  8913. return $result;
  8914. }
  8915. public function queryColumn($params=array())
  8916. {
  8917. return $this->queryInternal('fetchAll',array(PDO::FETCH_COLUMN, 0),$params);
  8918. }
  8919. private function queryInternal($method,$mode,$params=array())
  8920. {
  8921. $params=array_merge($this->params,$params);
  8922. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8923. {
  8924. $p=array();
  8925. foreach($pars as $name=>$value)
  8926. $p[$name]=$name.'='.var_export($value,true);
  8927. $par='. Bound with '.implode(', ',$p);
  8928. }
  8929. else
  8930. $par='';
  8931. if($this->_connection->queryCachingCount>0 && $method!==''
  8932. && $this->_connection->queryCachingDuration>0
  8933. && $this->_connection->queryCacheID!==false
  8934. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  8935. {
  8936. $this->_connection->queryCachingCount--;
  8937. $cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
  8938. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  8939. if(($result=$cache->get($cacheKey))!==false)
  8940. {
  8941. return $result[0];
  8942. }
  8943. }
  8944. try
  8945. {
  8946. if($this->_connection->enableProfiling)
  8947. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8948. $this->prepare();
  8949. if($params===array())
  8950. $this->_statement->execute();
  8951. else
  8952. $this->_statement->execute($params);
  8953. if($method==='')
  8954. $result=new CDbDataReader($this);
  8955. else
  8956. {
  8957. $mode=(array)$mode;
  8958. call_user_func_array(array($this->_statement, 'setFetchMode'), $mode);
  8959. $result=$this->_statement->$method();
  8960. $this->_statement->closeCursor();
  8961. }
  8962. if($this->_connection->enableProfiling)
  8963. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8964. if(isset($cache,$cacheKey))
  8965. $cache->set($cacheKey, array($result), $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  8966. return $result;
  8967. }
  8968. catch(Exception $e)
  8969. {
  8970. if($this->_connection->enableProfiling)
  8971. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8972. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  8973. $message=$e->getMessage();
  8974. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  8975. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8976. if(YII_DEBUG)
  8977. $message.='. The SQL statement executed was: '.$this->getText().$par;
  8978. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8979. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8980. }
  8981. }
  8982. public function buildQuery($query)
  8983. {
  8984. $sql=!empty($query['distinct']) ? 'SELECT DISTINCT' : 'SELECT';
  8985. $sql.=' '.(!empty($query['select']) ? $query['select'] : '*');
  8986. if(!empty($query['from']))
  8987. $sql.="\nFROM ".$query['from'];
  8988. else
  8989. throw new CDbException(Yii::t('yii','The DB query must contain the "from" portion.'));
  8990. if(!empty($query['join']))
  8991. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  8992. if(!empty($query['where']))
  8993. $sql.="\nWHERE ".$query['where'];
  8994. if(!empty($query['group']))
  8995. $sql.="\nGROUP BY ".$query['group'];
  8996. if(!empty($query['having']))
  8997. $sql.="\nHAVING ".$query['having'];
  8998. if(!empty($query['union']))
  8999. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  9000. if(!empty($query['order']))
  9001. $sql.="\nORDER BY ".$query['order'];
  9002. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  9003. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  9004. if($limit>=0 || $offset>0)
  9005. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  9006. return $sql;
  9007. }
  9008. public function select($columns='*', $option='')
  9009. {
  9010. if(is_string($columns) && strpos($columns,'(')!==false)
  9011. $this->_query['select']=$columns;
  9012. else
  9013. {
  9014. if(!is_array($columns))
  9015. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9016. foreach($columns as $i=>$column)
  9017. {
  9018. if(is_object($column))
  9019. $columns[$i]=(string)$column;
  9020. elseif(strpos($column,'(')===false)
  9021. {
  9022. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  9023. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  9024. else
  9025. $columns[$i]=$this->_connection->quoteColumnName($column);
  9026. }
  9027. }
  9028. $this->_query['select']=implode(', ',$columns);
  9029. }
  9030. if($option!='')
  9031. $this->_query['select']=$option.' '.$this->_query['select'];
  9032. return $this;
  9033. }
  9034. public function getSelect()
  9035. {
  9036. return isset($this->_query['select']) ? $this->_query['select'] : '';
  9037. }
  9038. public function setSelect($value)
  9039. {
  9040. $this->select($value);
  9041. }
  9042. public function selectDistinct($columns='*')
  9043. {
  9044. $this->_query['distinct']=true;
  9045. return $this->select($columns);
  9046. }
  9047. public function getDistinct()
  9048. {
  9049. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  9050. }
  9051. public function setDistinct($value)
  9052. {
  9053. $this->_query['distinct']=$value;
  9054. }
  9055. public function from($tables)
  9056. {
  9057. if(is_string($tables) && strpos($tables,'(')!==false)
  9058. $this->_query['from']=$tables;
  9059. else
  9060. {
  9061. if(!is_array($tables))
  9062. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  9063. foreach($tables as $i=>$table)
  9064. {
  9065. if(strpos($table,'(')===false)
  9066. {
  9067. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9068. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9069. else
  9070. $tables[$i]=$this->_connection->quoteTableName($table);
  9071. }
  9072. }
  9073. $this->_query['from']=implode(', ',$tables);
  9074. }
  9075. return $this;
  9076. }
  9077. public function getFrom()
  9078. {
  9079. return isset($this->_query['from']) ? $this->_query['from'] : '';
  9080. }
  9081. public function setFrom($value)
  9082. {
  9083. $this->from($value);
  9084. }
  9085. public function where($conditions, $params=array())
  9086. {
  9087. $this->_query['where']=$this->processConditions($conditions);
  9088. foreach($params as $name=>$value)
  9089. $this->params[$name]=$value;
  9090. return $this;
  9091. }
  9092. public function andWhere($conditions,$params=array())
  9093. {
  9094. if(isset($this->_query['where']))
  9095. $this->_query['where']=$this->processConditions(array('AND',$this->_query['where'],$conditions));
  9096. else
  9097. $this->_query['where']=$this->processConditions($conditions);
  9098. foreach($params as $name=>$value)
  9099. $this->params[$name]=$value;
  9100. return $this;
  9101. }
  9102. public function orWhere($conditions,$params=array())
  9103. {
  9104. if(isset($this->_query['where']))
  9105. $this->_query['where']=$this->processConditions(array('OR',$this->_query['where'],$conditions));
  9106. else
  9107. $this->_query['where']=$this->processConditions($conditions);
  9108. foreach($params as $name=>$value)
  9109. $this->params[$name]=$value;
  9110. return $this;
  9111. }
  9112. public function getWhere()
  9113. {
  9114. return isset($this->_query['where']) ? $this->_query['where'] : '';
  9115. }
  9116. public function setWhere($value)
  9117. {
  9118. $this->where($value);
  9119. }
  9120. public function join($table, $conditions, $params=array())
  9121. {
  9122. return $this->joinInternal('join', $table, $conditions, $params);
  9123. }
  9124. public function getJoin()
  9125. {
  9126. return isset($this->_query['join']) ? $this->_query['join'] : '';
  9127. }
  9128. public function setJoin($value)
  9129. {
  9130. $this->_query['join']=$value;
  9131. }
  9132. public function leftJoin($table, $conditions, $params=array())
  9133. {
  9134. return $this->joinInternal('left join', $table, $conditions, $params);
  9135. }
  9136. public function rightJoin($table, $conditions, $params=array())
  9137. {
  9138. return $this->joinInternal('right join', $table, $conditions, $params);
  9139. }
  9140. public function crossJoin($table)
  9141. {
  9142. return $this->joinInternal('cross join', $table);
  9143. }
  9144. public function naturalJoin($table)
  9145. {
  9146. return $this->joinInternal('natural join', $table);
  9147. }
  9148. public function group($columns)
  9149. {
  9150. if(is_string($columns) && strpos($columns,'(')!==false)
  9151. $this->_query['group']=$columns;
  9152. else
  9153. {
  9154. if(!is_array($columns))
  9155. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9156. foreach($columns as $i=>$column)
  9157. {
  9158. if(is_object($column))
  9159. $columns[$i]=(string)$column;
  9160. elseif(strpos($column,'(')===false)
  9161. $columns[$i]=$this->_connection->quoteColumnName($column);
  9162. }
  9163. $this->_query['group']=implode(', ',$columns);
  9164. }
  9165. return $this;
  9166. }
  9167. public function getGroup()
  9168. {
  9169. return isset($this->_query['group']) ? $this->_query['group'] : '';
  9170. }
  9171. public function setGroup($value)
  9172. {
  9173. $this->group($value);
  9174. }
  9175. public function having($conditions, $params=array())
  9176. {
  9177. $this->_query['having']=$this->processConditions($conditions);
  9178. foreach($params as $name=>$value)
  9179. $this->params[$name]=$value;
  9180. return $this;
  9181. }
  9182. public function getHaving()
  9183. {
  9184. return isset($this->_query['having']) ? $this->_query['having'] : '';
  9185. }
  9186. public function setHaving($value)
  9187. {
  9188. $this->having($value);
  9189. }
  9190. public function order($columns)
  9191. {
  9192. if(is_string($columns) && strpos($columns,'(')!==false)
  9193. $this->_query['order']=$columns;
  9194. else
  9195. {
  9196. if(!is_array($columns))
  9197. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9198. foreach($columns as $i=>$column)
  9199. {
  9200. if(is_object($column))
  9201. $columns[$i]=(string)$column;
  9202. elseif(strpos($column,'(')===false)
  9203. {
  9204. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  9205. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  9206. else
  9207. $columns[$i]=$this->_connection->quoteColumnName($column);
  9208. }
  9209. }
  9210. $this->_query['order']=implode(', ',$columns);
  9211. }
  9212. return $this;
  9213. }
  9214. public function getOrder()
  9215. {
  9216. return isset($this->_query['order']) ? $this->_query['order'] : '';
  9217. }
  9218. public function setOrder($value)
  9219. {
  9220. $this->order($value);
  9221. }
  9222. public function limit($limit, $offset=null)
  9223. {
  9224. $this->_query['limit']=(int)$limit;
  9225. if($offset!==null)
  9226. $this->offset($offset);
  9227. return $this;
  9228. }
  9229. public function getLimit()
  9230. {
  9231. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  9232. }
  9233. public function setLimit($value)
  9234. {
  9235. $this->limit($value);
  9236. }
  9237. public function offset($offset)
  9238. {
  9239. $this->_query['offset']=(int)$offset;
  9240. return $this;
  9241. }
  9242. public function getOffset()
  9243. {
  9244. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  9245. }
  9246. public function setOffset($value)
  9247. {
  9248. $this->offset($value);
  9249. }
  9250. public function union($sql)
  9251. {
  9252. if(isset($this->_query['union']) && is_string($this->_query['union']))
  9253. $this->_query['union']=array($this->_query['union']);
  9254. $this->_query['union'][]=$sql;
  9255. return $this;
  9256. }
  9257. public function getUnion()
  9258. {
  9259. return isset($this->_query['union']) ? $this->_query['union'] : '';
  9260. }
  9261. public function setUnion($value)
  9262. {
  9263. $this->_query['union']=$value;
  9264. }
  9265. public function insert($table, $columns)
  9266. {
  9267. $params=array();
  9268. $names=array();
  9269. $placeholders=array();
  9270. foreach($columns as $name=>$value)
  9271. {
  9272. $names[]=$this->_connection->quoteColumnName($name);
  9273. if($value instanceof CDbExpression)
  9274. {
  9275. $placeholders[] = $value->expression;
  9276. foreach($value->params as $n => $v)
  9277. $params[$n] = $v;
  9278. }
  9279. else
  9280. {
  9281. $placeholders[] = ':' . $name;
  9282. $params[':' . $name] = $value;
  9283. }
  9284. }
  9285. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  9286. . ' (' . implode(', ',$names) . ') VALUES ('
  9287. . implode(', ', $placeholders) . ')';
  9288. return $this->setText($sql)->execute($params);
  9289. }
  9290. public function update($table, $columns, $conditions='', $params=array())
  9291. {
  9292. $lines=array();
  9293. foreach($columns as $name=>$value)
  9294. {
  9295. if($value instanceof CDbExpression)
  9296. {
  9297. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  9298. foreach($value->params as $n => $v)
  9299. $params[$n] = $v;
  9300. }
  9301. else
  9302. {
  9303. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  9304. $params[':' . $name]=$value;
  9305. }
  9306. }
  9307. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  9308. if(($where=$this->processConditions($conditions))!='')
  9309. $sql.=' WHERE '.$where;
  9310. return $this->setText($sql)->execute($params);
  9311. }
  9312. public function delete($table, $conditions='', $params=array())
  9313. {
  9314. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  9315. if(($where=$this->processConditions($conditions))!='')
  9316. $sql.=' WHERE '.$where;
  9317. return $this->setText($sql)->execute($params);
  9318. }
  9319. public function createTable($table, $columns, $options=null)
  9320. {
  9321. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  9322. }
  9323. public function renameTable($table, $newName)
  9324. {
  9325. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  9326. }
  9327. public function dropTable($table)
  9328. {
  9329. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  9330. }
  9331. public function truncateTable($table)
  9332. {
  9333. $schema=$this->getConnection()->getSchema();
  9334. $n=$this->setText($schema->truncateTable($table))->execute();
  9335. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  9336. $schema->resetSequence($schema->getTable($table));
  9337. return $n;
  9338. }
  9339. public function addColumn($table, $column, $type)
  9340. {
  9341. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  9342. }
  9343. public function dropColumn($table, $column)
  9344. {
  9345. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  9346. }
  9347. public function renameColumn($table, $name, $newName)
  9348. {
  9349. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  9350. }
  9351. public function alterColumn($table, $column, $type)
  9352. {
  9353. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  9354. }
  9355. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9356. {
  9357. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  9358. }
  9359. public function dropForeignKey($name, $table)
  9360. {
  9361. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  9362. }
  9363. public function createIndex($name, $table, $column, $unique=false)
  9364. {
  9365. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $column, $unique))->execute();
  9366. }
  9367. public function dropIndex($name, $table)
  9368. {
  9369. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  9370. }
  9371. private function processConditions($conditions)
  9372. {
  9373. if(!is_array($conditions))
  9374. return $conditions;
  9375. elseif($conditions===array())
  9376. return '';
  9377. $n=count($conditions);
  9378. $operator=strtoupper($conditions[0]);
  9379. if($operator==='OR' || $operator==='AND')
  9380. {
  9381. $parts=array();
  9382. for($i=1;$i<$n;++$i)
  9383. {
  9384. $condition=$this->processConditions($conditions[$i]);
  9385. if($condition!=='')
  9386. $parts[]='('.$condition.')';
  9387. }
  9388. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  9389. }
  9390. if(!isset($conditions[1],$conditions[2]))
  9391. return '';
  9392. $column=$conditions[1];
  9393. if(strpos($column,'(')===false)
  9394. $column=$this->_connection->quoteColumnName($column);
  9395. $values=$conditions[2];
  9396. if(!is_array($values))
  9397. $values=array($values);
  9398. if($operator==='IN' || $operator==='NOT IN')
  9399. {
  9400. if($values===array())
  9401. return $operator==='IN' ? '0=1' : '';
  9402. foreach($values as $i=>$value)
  9403. {
  9404. if(is_string($value))
  9405. $values[$i]=$this->_connection->quoteValue($value);
  9406. else
  9407. $values[$i]=(string)$value;
  9408. }
  9409. return $column.' '.$operator.' ('.implode(', ',$values).')';
  9410. }
  9411. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  9412. {
  9413. if($values===array())
  9414. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  9415. if($operator==='LIKE' || $operator==='NOT LIKE')
  9416. $andor=' AND ';
  9417. else
  9418. {
  9419. $andor=' OR ';
  9420. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  9421. }
  9422. $expressions=array();
  9423. foreach($values as $value)
  9424. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  9425. return implode($andor,$expressions);
  9426. }
  9427. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  9428. }
  9429. private function joinInternal($type, $table, $conditions='', $params=array())
  9430. {
  9431. if(strpos($table,'(')===false)
  9432. {
  9433. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9434. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9435. else
  9436. $table=$this->_connection->quoteTableName($table);
  9437. }
  9438. $conditions=$this->processConditions($conditions);
  9439. if($conditions!='')
  9440. $conditions=' ON '.$conditions;
  9441. if(isset($this->_query['join']) && is_string($this->_query['join']))
  9442. $this->_query['join']=array($this->_query['join']);
  9443. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  9444. foreach($params as $name=>$value)
  9445. $this->params[$name]=$value;
  9446. return $this;
  9447. }
  9448. public function addPrimaryKey($name,$table,$columns)
  9449. {
  9450. return $this->setText($this->getConnection()->getSchema()->addPrimaryKey($name,$table,$columns))->execute();
  9451. }
  9452. public function dropPrimaryKey($name,$table)
  9453. {
  9454. return $this->setText($this->getConnection()->getSchema()->dropPrimaryKey($name,$table))->execute();
  9455. }
  9456. }
  9457. class CDbColumnSchema extends CComponent
  9458. {
  9459. public $name;
  9460. public $rawName;
  9461. public $allowNull;
  9462. public $dbType;
  9463. public $type;
  9464. public $defaultValue;
  9465. public $size;
  9466. public $precision;
  9467. public $scale;
  9468. public $isPrimaryKey;
  9469. public $isForeignKey;
  9470. public $autoIncrement=false;
  9471. public $comment='';
  9472. public function init($dbType, $defaultValue)
  9473. {
  9474. $this->dbType=$dbType;
  9475. $this->extractType($dbType);
  9476. $this->extractLimit($dbType);
  9477. if($defaultValue!==null)
  9478. $this->extractDefault($defaultValue);
  9479. }
  9480. protected function extractType($dbType)
  9481. {
  9482. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  9483. $this->type='integer';
  9484. elseif(stripos($dbType,'bool')!==false)
  9485. $this->type='boolean';
  9486. elseif(preg_match('/(real|floa|doub)/i',$dbType))
  9487. $this->type='double';
  9488. else
  9489. $this->type='string';
  9490. }
  9491. protected function extractLimit($dbType)
  9492. {
  9493. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  9494. {
  9495. $values=explode(',',$matches[1]);
  9496. $this->size=$this->precision=(int)$values[0];
  9497. if(isset($values[1]))
  9498. $this->scale=(int)$values[1];
  9499. }
  9500. }
  9501. protected function extractDefault($defaultValue)
  9502. {
  9503. $this->defaultValue=$this->typecast($defaultValue);
  9504. }
  9505. public function typecast($value)
  9506. {
  9507. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  9508. return $value;
  9509. if($value==='' && $this->allowNull)
  9510. return $this->type==='string' ? '' : null;
  9511. switch($this->type)
  9512. {
  9513. case 'string': return (string)$value;
  9514. case 'integer': return (integer)$value;
  9515. case 'boolean': return (boolean)$value;
  9516. case 'double':
  9517. default: return $value;
  9518. }
  9519. }
  9520. }
  9521. class CSqliteColumnSchema extends CDbColumnSchema
  9522. {
  9523. protected function extractDefault($defaultValue)
  9524. {
  9525. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  9526. if($this->type==='string' && $this->defaultValue!==null) // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  9527. $this->defaultValue=trim($this->defaultValue,"'\"");
  9528. }
  9529. }
  9530. abstract class CValidator extends CComponent
  9531. {
  9532. public static $builtInValidators=array(
  9533. 'required'=>'CRequiredValidator',
  9534. 'filter'=>'CFilterValidator',
  9535. 'match'=>'CRegularExpressionValidator',
  9536. 'email'=>'CEmailValidator',
  9537. 'url'=>'CUrlValidator',
  9538. 'unique'=>'CUniqueValidator',
  9539. 'compare'=>'CCompareValidator',
  9540. 'length'=>'CStringValidator',
  9541. 'in'=>'CRangeValidator',
  9542. 'numerical'=>'CNumberValidator',
  9543. 'captcha'=>'CCaptchaValidator',
  9544. 'type'=>'CTypeValidator',
  9545. 'file'=>'CFileValidator',
  9546. 'default'=>'CDefaultValueValidator',
  9547. 'exist'=>'CExistValidator',
  9548. 'boolean'=>'CBooleanValidator',
  9549. 'safe'=>'CSafeValidator',
  9550. 'unsafe'=>'CUnsafeValidator',
  9551. 'date'=>'CDateValidator',
  9552. );
  9553. public $attributes;
  9554. public $message;
  9555. public $skipOnError=false;
  9556. public $on;
  9557. public $except;
  9558. public $safe=true;
  9559. public $enableClientValidation=true;
  9560. abstract protected function validateAttribute($object,$attribute);
  9561. public static function createValidator($name,$object,$attributes,$params=array())
  9562. {
  9563. if(is_string($attributes))
  9564. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  9565. if(isset($params['on']))
  9566. {
  9567. if(is_array($params['on']))
  9568. $on=$params['on'];
  9569. else
  9570. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  9571. }
  9572. else
  9573. $on=array();
  9574. if(isset($params['except']))
  9575. {
  9576. if(is_array($params['except']))
  9577. $except=$params['except'];
  9578. else
  9579. $except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
  9580. }
  9581. else
  9582. $except=array();
  9583. if(method_exists($object,$name))
  9584. {
  9585. $validator=new CInlineValidator;
  9586. $validator->attributes=$attributes;
  9587. $validator->method=$name;
  9588. if(isset($params['clientValidate']))
  9589. {
  9590. $validator->clientValidate=$params['clientValidate'];
  9591. unset($params['clientValidate']);
  9592. }
  9593. $validator->params=$params;
  9594. if(isset($params['skipOnError']))
  9595. $validator->skipOnError=$params['skipOnError'];
  9596. }
  9597. else
  9598. {
  9599. $params['attributes']=$attributes;
  9600. if(isset(self::$builtInValidators[$name]))
  9601. $className=Yii::import(self::$builtInValidators[$name],true);
  9602. else
  9603. $className=Yii::import($name,true);
  9604. $validator=new $className;
  9605. foreach($params as $name=>$value)
  9606. $validator->$name=$value;
  9607. }
  9608. $validator->on=empty($on) ? array() : array_combine($on,$on);
  9609. $validator->except=empty($except) ? array() : array_combine($except,$except);
  9610. return $validator;
  9611. }
  9612. public function validate($object,$attributes=null)
  9613. {
  9614. if(is_array($attributes))
  9615. $attributes=array_intersect($this->attributes,$attributes);
  9616. else
  9617. $attributes=$this->attributes;
  9618. foreach($attributes as $attribute)
  9619. {
  9620. if(!$this->skipOnError || !$object->hasErrors($attribute))
  9621. $this->validateAttribute($object,$attribute);
  9622. }
  9623. }
  9624. public function clientValidateAttribute($object,$attribute)
  9625. {
  9626. }
  9627. public function applyTo($scenario)
  9628. {
  9629. if(isset($this->except[$scenario]))
  9630. return false;
  9631. return empty($this->on) || isset($this->on[$scenario]);
  9632. }
  9633. protected function addError($object,$attribute,$message,$params=array())
  9634. {
  9635. $params['{attribute}']=$object->getAttributeLabel($attribute);
  9636. $object->addError($attribute,strtr($message,$params));
  9637. }
  9638. protected function isEmpty($value,$trim=false)
  9639. {
  9640. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  9641. }
  9642. }
  9643. class CStringValidator extends CValidator
  9644. {
  9645. public $max;
  9646. public $min;
  9647. public $is;
  9648. public $tooShort;
  9649. public $tooLong;
  9650. public $allowEmpty=true;
  9651. public $encoding;
  9652. protected function validateAttribute($object,$attribute)
  9653. {
  9654. $value=$object->$attribute;
  9655. if($this->allowEmpty && $this->isEmpty($value))
  9656. return;
  9657. if(function_exists('mb_strlen') && $this->encoding!==false)
  9658. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  9659. else
  9660. $length=strlen($value);
  9661. if($this->min!==null && $length<$this->min)
  9662. {
  9663. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9664. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9665. }
  9666. if($this->max!==null && $length>$this->max)
  9667. {
  9668. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9669. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9670. }
  9671. if($this->is!==null && $length!==$this->is)
  9672. {
  9673. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9674. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  9675. }
  9676. }
  9677. public function clientValidateAttribute($object,$attribute)
  9678. {
  9679. $label=$object->getAttributeLabel($attribute);
  9680. if(($message=$this->message)===null)
  9681. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9682. $message=strtr($message, array(
  9683. '{attribute}'=>$label,
  9684. '{length}'=>$this->is,
  9685. ));
  9686. if(($tooShort=$this->tooShort)===null)
  9687. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9688. $tooShort=strtr($tooShort, array(
  9689. '{attribute}'=>$label,
  9690. '{min}'=>$this->min,
  9691. ));
  9692. if(($tooLong=$this->tooLong)===null)
  9693. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9694. $tooLong=strtr($tooLong, array(
  9695. '{attribute}'=>$label,
  9696. '{max}'=>$this->max,
  9697. ));
  9698. $js='';
  9699. if($this->min!==null)
  9700. {
  9701. $js.="
  9702. if(value.length<{$this->min}) {
  9703. messages.push(".CJSON::encode($tooShort).");
  9704. }
  9705. ";
  9706. }
  9707. if($this->max!==null)
  9708. {
  9709. $js.="
  9710. if(value.length>{$this->max}) {
  9711. messages.push(".CJSON::encode($tooLong).");
  9712. }
  9713. ";
  9714. }
  9715. if($this->is!==null)
  9716. {
  9717. $js.="
  9718. if(value.length!={$this->is}) {
  9719. messages.push(".CJSON::encode($message).");
  9720. }
  9721. ";
  9722. }
  9723. if($this->allowEmpty)
  9724. {
  9725. $js="
  9726. if(jQuery.trim(value)!='') {
  9727. $js
  9728. }
  9729. ";
  9730. }
  9731. return $js;
  9732. }
  9733. }
  9734. class CRequiredValidator extends CValidator
  9735. {
  9736. public $requiredValue;
  9737. public $strict=false;
  9738. protected function validateAttribute($object,$attribute)
  9739. {
  9740. $value=$object->$attribute;
  9741. if($this->requiredValue!==null)
  9742. {
  9743. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  9744. {
  9745. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  9746. array('{value}'=>$this->requiredValue));
  9747. $this->addError($object,$attribute,$message);
  9748. }
  9749. }
  9750. elseif($this->isEmpty($value,true))
  9751. {
  9752. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  9753. $this->addError($object,$attribute,$message);
  9754. }
  9755. }
  9756. public function clientValidateAttribute($object,$attribute)
  9757. {
  9758. $message=$this->message;
  9759. if($this->requiredValue!==null)
  9760. {
  9761. if($message===null)
  9762. $message=Yii::t('yii','{attribute} must be {value}.');
  9763. $message=strtr($message, array(
  9764. '{value}'=>$this->requiredValue,
  9765. '{attribute}'=>$object->getAttributeLabel($attribute),
  9766. ));
  9767. return "
  9768. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  9769. messages.push(".CJSON::encode($message).");
  9770. }
  9771. ";
  9772. }
  9773. else
  9774. {
  9775. if($message===null)
  9776. $message=Yii::t('yii','{attribute} cannot be blank.');
  9777. $message=strtr($message, array(
  9778. '{attribute}'=>$object->getAttributeLabel($attribute),
  9779. ));
  9780. return "
  9781. if(jQuery.trim(value)=='') {
  9782. messages.push(".CJSON::encode($message).");
  9783. }
  9784. ";
  9785. }
  9786. }
  9787. }
  9788. class CNumberValidator extends CValidator
  9789. {
  9790. public $integerOnly=false;
  9791. public $allowEmpty=true;
  9792. public $max;
  9793. public $min;
  9794. public $tooBig;
  9795. public $tooSmall;
  9796. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  9797. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  9798. protected function validateAttribute($object,$attribute)
  9799. {
  9800. $value=$object->$attribute;
  9801. if($this->allowEmpty && $this->isEmpty($value))
  9802. return;
  9803. if($this->integerOnly)
  9804. {
  9805. if(!preg_match($this->integerPattern,"$value"))
  9806. {
  9807. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  9808. $this->addError($object,$attribute,$message);
  9809. }
  9810. }
  9811. else
  9812. {
  9813. if(!preg_match($this->numberPattern,"$value"))
  9814. {
  9815. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  9816. $this->addError($object,$attribute,$message);
  9817. }
  9818. }
  9819. if($this->min!==null && $value<$this->min)
  9820. {
  9821. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9822. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9823. }
  9824. if($this->max!==null && $value>$this->max)
  9825. {
  9826. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9827. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9828. }
  9829. }
  9830. public function clientValidateAttribute($object,$attribute)
  9831. {
  9832. $label=$object->getAttributeLabel($attribute);
  9833. if(($message=$this->message)===null)
  9834. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  9835. $message=strtr($message, array(
  9836. '{attribute}'=>$label,
  9837. ));
  9838. if(($tooBig=$this->tooBig)===null)
  9839. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9840. $tooBig=strtr($tooBig, array(
  9841. '{attribute}'=>$label,
  9842. '{max}'=>$this->max,
  9843. ));
  9844. if(($tooSmall=$this->tooSmall)===null)
  9845. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9846. $tooSmall=strtr($tooSmall, array(
  9847. '{attribute}'=>$label,
  9848. '{min}'=>$this->min,
  9849. ));
  9850. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  9851. $js="
  9852. if(!value.match($pattern)) {
  9853. messages.push(".CJSON::encode($message).");
  9854. }
  9855. ";
  9856. if($this->min!==null)
  9857. {
  9858. $js.="
  9859. if(value<{$this->min}) {
  9860. messages.push(".CJSON::encode($tooSmall).");
  9861. }
  9862. ";
  9863. }
  9864. if($this->max!==null)
  9865. {
  9866. $js.="
  9867. if(value>{$this->max}) {
  9868. messages.push(".CJSON::encode($tooBig).");
  9869. }
  9870. ";
  9871. }
  9872. if($this->allowEmpty)
  9873. {
  9874. $js="
  9875. if(jQuery.trim(value)!='') {
  9876. $js
  9877. }
  9878. ";
  9879. }
  9880. return $js;
  9881. }
  9882. }
  9883. class CListIterator implements Iterator
  9884. {
  9885. private $_d;
  9886. private $_i;
  9887. private $_c;
  9888. public function __construct(&$data)
  9889. {
  9890. $this->_d=&$data;
  9891. $this->_i=0;
  9892. $this->_c=count($this->_d);
  9893. }
  9894. public function rewind()
  9895. {
  9896. $this->_i=0;
  9897. }
  9898. public function key()
  9899. {
  9900. return $this->_i;
  9901. }
  9902. public function current()
  9903. {
  9904. return $this->_d[$this->_i];
  9905. }
  9906. public function next()
  9907. {
  9908. $this->_i++;
  9909. }
  9910. public function valid()
  9911. {
  9912. return $this->_i<$this->_c;
  9913. }
  9914. }
  9915. interface IApplicationComponent
  9916. {
  9917. public function init();
  9918. public function getIsInitialized();
  9919. }
  9920. interface ICache
  9921. {
  9922. public function get($id);
  9923. public function mget($ids);
  9924. public function set($id,$value,$expire=0,$dependency=null);
  9925. public function add($id,$value,$expire=0,$dependency=null);
  9926. public function delete($id);
  9927. public function flush();
  9928. }
  9929. interface ICacheDependency
  9930. {
  9931. public function evaluateDependency();
  9932. public function getHasChanged();
  9933. }
  9934. interface IStatePersister
  9935. {
  9936. public function load();
  9937. public function save($state);
  9938. }
  9939. interface IFilter
  9940. {
  9941. public function filter($filterChain);
  9942. }
  9943. interface IAction
  9944. {
  9945. public function getId();
  9946. public function getController();
  9947. }
  9948. interface IWebServiceProvider
  9949. {
  9950. public function beforeWebMethod($service);
  9951. public function afterWebMethod($service);
  9952. }
  9953. interface IViewRenderer
  9954. {
  9955. public function renderFile($context,$file,$data,$return);
  9956. }
  9957. interface IUserIdentity
  9958. {
  9959. public function authenticate();
  9960. public function getIsAuthenticated();
  9961. public function getId();
  9962. public function getName();
  9963. public function getPersistentStates();
  9964. }
  9965. interface IWebUser
  9966. {
  9967. public function getId();
  9968. public function getName();
  9969. public function getIsGuest();
  9970. public function checkAccess($operation,$params=array());
  9971. public function loginRequired();
  9972. }
  9973. interface IAuthManager
  9974. {
  9975. public function checkAccess($itemName,$userId,$params=array());
  9976. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  9977. public function removeAuthItem($name);
  9978. public function getAuthItems($type=null,$userId=null);
  9979. public function getAuthItem($name);
  9980. public function saveAuthItem($item,$oldName=null);
  9981. public function addItemChild($itemName,$childName);
  9982. public function removeItemChild($itemName,$childName);
  9983. public function hasItemChild($itemName,$childName);
  9984. public function getItemChildren($itemName);
  9985. public function assign($itemName,$userId,$bizRule=null,$data=null);
  9986. public function revoke($itemName,$userId);
  9987. public function isAssigned($itemName,$userId);
  9988. public function getAuthAssignment($itemName,$userId);
  9989. public function getAuthAssignments($userId);
  9990. public function saveAuthAssignment($assignment);
  9991. public function clearAll();
  9992. public function clearAuthAssignments();
  9993. public function save();
  9994. public function executeBizRule($bizRule,$params,$data);
  9995. }
  9996. interface IBehavior
  9997. {
  9998. public function attach($component);
  9999. public function detach($component);
  10000. public function getEnabled();
  10001. public function setEnabled($value);
  10002. }
  10003. interface IWidgetFactory
  10004. {
  10005. public function createWidget($owner,$className,$properties=array());
  10006. }
  10007. interface IDataProvider
  10008. {
  10009. public function getId();
  10010. public function getItemCount($refresh=false);
  10011. public function getTotalItemCount($refresh=false);
  10012. public function getData($refresh=false);
  10013. public function getKeys($refresh=false);
  10014. public function getSort();
  10015. public function getPagination();
  10016. }
  10017. interface ILogFilter
  10018. {
  10019. public function filter(&$logs);
  10020. }
  10021. ?>