PageRenderTime 129ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 2ms

/yii/framework/yiilite.php

https://bitbucket.org/zurmo/zurmo/
PHP | 10608 lines | 10527 code | 2 blank | 79 comment | 1094 complexity | 745d6fb1c194841250da2105edc9ef84 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, GPL-2.0, LGPL-3.0, LGPL-2.1, BSD-2-Clause
  1. <?php
  2. /**
  3. * Yii bootstrap file.
  4. *
  5. * This file is automatically generated using 'build lite' command.
  6. * It is the result of merging commonly used Yii class files with
  7. * comments and trace statements removed away.
  8. *
  9. * By using this file instead of yii.php, an Yii application may
  10. * improve performance due to the reduction of PHP parsing time.
  11. * The performance improvement is especially obvious when PHP APC extension
  12. * is enabled.
  13. *
  14. * DO NOT modify this file manually.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @link http://www.yiiframework.com/
  18. * @copyright 2008-2013 Yii Software LLC
  19. * @license http://www.yiiframework.com/license/
  20. * @version $Id: $
  21. * @since 1.0
  22. */
  23. defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME',microtime(true));
  24. defined('YII_DEBUG') or define('YII_DEBUG',false);
  25. defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',0);
  26. defined('YII_ENABLE_EXCEPTION_HANDLER') or define('YII_ENABLE_EXCEPTION_HANDLER',true);
  27. defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER',true);
  28. defined('YII_PATH') or define('YII_PATH',dirname(__FILE__));
  29. defined('YII_ZII_PATH') or define('YII_ZII_PATH',YII_PATH.DIRECTORY_SEPARATOR.'zii');
  30. class YiiBase
  31. {
  32. public static $classMap=array();
  33. public static $enableIncludePath=true;
  34. private static $_aliases=array('system'=>YII_PATH,'zii'=>YII_ZII_PATH); // alias => path
  35. private static $_imports=array(); // alias => class name or directory
  36. private static $_includePaths; // list of include paths
  37. private static $_app;
  38. private static $_logger;
  39. public static function getVersion()
  40. {
  41. return '1.1.17';
  42. }
  43. public static function createWebApplication($config=null)
  44. {
  45. return self::createApplication('CWebApplication',$config);
  46. }
  47. public static function createConsoleApplication($config=null)
  48. {
  49. return self::createApplication('CConsoleApplication',$config);
  50. }
  51. public static function createApplication($class,$config=null)
  52. {
  53. return new $class($config);
  54. }
  55. public static function app()
  56. {
  57. return self::$_app;
  58. }
  59. public static function setApplication($app)
  60. {
  61. if(self::$_app===null || $app===null)
  62. self::$_app=$app;
  63. else
  64. throw new CException(Yii::t('yii','Yii application can only be created once.'));
  65. }
  66. public static function getFrameworkPath()
  67. {
  68. return YII_PATH;
  69. }
  70. public static function createComponent($config)
  71. {
  72. if(is_string($config))
  73. {
  74. $type=$config;
  75. $config=array();
  76. }
  77. elseif(isset($config['class']))
  78. {
  79. $type=$config['class'];
  80. unset($config['class']);
  81. }
  82. else
  83. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  84. if(!class_exists($type,false))
  85. $type=Yii::import($type,true);
  86. if(($n=func_num_args())>1)
  87. {
  88. $args=func_get_args();
  89. if($n===2)
  90. $object=new $type($args[1]);
  91. elseif($n===3)
  92. $object=new $type($args[1],$args[2]);
  93. elseif($n===4)
  94. $object=new $type($args[1],$args[2],$args[3]);
  95. else
  96. {
  97. unset($args[0]);
  98. $class=new ReflectionClass($type);
  99. // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
  100. // $object=$class->newInstanceArgs($args);
  101. $object=call_user_func_array(array($class,'newInstance'),$args);
  102. }
  103. }
  104. else
  105. $object=new $type;
  106. foreach($config as $key=>$value)
  107. $object->$key=$value;
  108. return $object;
  109. }
  110. public static function import($alias,$forceInclude=false)
  111. {
  112. if(isset(self::$_imports[$alias])) // previously imported
  113. return self::$_imports[$alias];
  114. if(class_exists($alias,false) || interface_exists($alias,false))
  115. return self::$_imports[$alias]=$alias;
  116. if(($pos=strrpos($alias,'\\'))!==false) // a class name in PHP 5.3 namespace format
  117. {
  118. $namespace=str_replace('\\','.',ltrim(substr($alias,0,$pos),'\\'));
  119. if(($path=self::getPathOfAlias($namespace))!==false)
  120. {
  121. $classFile=$path.DIRECTORY_SEPARATOR.substr($alias,$pos+1).'.php';
  122. if($forceInclude)
  123. {
  124. if(is_file($classFile))
  125. require($classFile);
  126. else
  127. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
  128. self::$_imports[$alias]=$alias;
  129. }
  130. else
  131. self::$classMap[$alias]=$classFile;
  132. return $alias;
  133. }
  134. else
  135. {
  136. // try to autoload the class with an autoloader
  137. if (class_exists($alias,true))
  138. return self::$_imports[$alias]=$alias;
  139. else
  140. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  141. array('{alias}'=>$namespace)));
  142. }
  143. }
  144. if(($pos=strrpos($alias,'.'))===false) // a simple class name
  145. {
  146. // try to autoload the class with an autoloader if $forceInclude is true
  147. if($forceInclude && (Yii::autoload($alias,true) || class_exists($alias,true)))
  148. self::$_imports[$alias]=$alias;
  149. return $alias;
  150. }
  151. $className=(string)substr($alias,$pos+1);
  152. $isClass=$className!=='*';
  153. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  154. return self::$_imports[$alias]=$className;
  155. if(($path=self::getPathOfAlias($alias))!==false)
  156. {
  157. if($isClass)
  158. {
  159. if($forceInclude)
  160. {
  161. if(is_file($path.'.php'))
  162. require($path.'.php');
  163. else
  164. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
  165. self::$_imports[$alias]=$className;
  166. }
  167. else
  168. self::$classMap[$className]=$path.'.php';
  169. return $className;
  170. }
  171. else // a directory
  172. {
  173. if(self::$_includePaths===null)
  174. {
  175. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  176. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  177. unset(self::$_includePaths[$pos]);
  178. }
  179. array_unshift(self::$_includePaths,$path);
  180. if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  181. self::$enableIncludePath=false;
  182. return self::$_imports[$alias]=$path;
  183. }
  184. }
  185. else
  186. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  187. array('{alias}'=>$alias)));
  188. }
  189. public static function getPathOfAlias($alias)
  190. {
  191. if(isset(self::$_aliases[$alias]))
  192. return self::$_aliases[$alias];
  193. elseif(($pos=strpos($alias,'.'))!==false)
  194. {
  195. $rootAlias=substr($alias,0,$pos);
  196. if(isset(self::$_aliases[$rootAlias]))
  197. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  198. elseif(self::$_app instanceof CWebApplication)
  199. {
  200. if(self::$_app->findModule($rootAlias)!==null)
  201. return self::getPathOfAlias($alias);
  202. }
  203. }
  204. return false;
  205. }
  206. public static function setPathOfAlias($alias,$path)
  207. {
  208. if(empty($path))
  209. unset(self::$_aliases[$alias]);
  210. else
  211. self::$_aliases[$alias]=rtrim($path,'\\/');
  212. }
  213. public static function autoload($className,$classMapOnly=false)
  214. {
  215. // use include so that the error PHP file may appear
  216. if(isset(self::$classMap[$className]))
  217. include(self::$classMap[$className]);
  218. elseif(isset(self::$_coreClasses[$className]))
  219. include(YII_PATH.self::$_coreClasses[$className]);
  220. elseif($classMapOnly)
  221. return false;
  222. else
  223. {
  224. // include class file relying on include_path
  225. if(strpos($className,'\\')===false) // class without namespace
  226. {
  227. if(self::$enableIncludePath===false)
  228. {
  229. foreach(self::$_includePaths as $path)
  230. {
  231. $classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
  232. if(is_file($classFile))
  233. {
  234. include($classFile);
  235. if(YII_DEBUG && basename(realpath($classFile))!==$className.'.php')
  236. throw new CException(Yii::t('yii','Class name "{class}" does not match class file "{file}".', array(
  237. '{class}'=>$className,
  238. '{file}'=>$classFile,
  239. )));
  240. break;
  241. }
  242. }
  243. }
  244. else
  245. include($className.'.php');
  246. }
  247. else // class name with namespace in PHP 5.3
  248. {
  249. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  250. if(($path=self::getPathOfAlias($namespace))!==false && is_file($path.'.php'))
  251. include($path.'.php');
  252. else
  253. return false;
  254. }
  255. return class_exists($className,false) || interface_exists($className,false);
  256. }
  257. return true;
  258. }
  259. public static function trace($msg,$category='application')
  260. {
  261. if(YII_DEBUG)
  262. self::log($msg,CLogger::LEVEL_TRACE,$category);
  263. }
  264. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  265. {
  266. if(self::$_logger===null)
  267. self::$_logger=new CLogger;
  268. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  269. {
  270. $traces=debug_backtrace();
  271. $count=0;
  272. foreach($traces as $trace)
  273. {
  274. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  275. {
  276. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  277. if(++$count>=YII_TRACE_LEVEL)
  278. break;
  279. }
  280. }
  281. }
  282. self::$_logger->log($msg,$level,$category);
  283. }
  284. public static function beginProfile($token,$category='application')
  285. {
  286. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  287. }
  288. public static function endProfile($token,$category='application')
  289. {
  290. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  291. }
  292. public static function getLogger()
  293. {
  294. if(self::$_logger!==null)
  295. return self::$_logger;
  296. else
  297. return self::$_logger=new CLogger;
  298. }
  299. public static function setLogger($logger)
  300. {
  301. self::$_logger=$logger;
  302. }
  303. public static function powered()
  304. {
  305. return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
  306. }
  307. public static function t($category,$message,$params=array(),$source=null,$language=null)
  308. {
  309. if(self::$_app!==null)
  310. {
  311. if($source===null)
  312. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  313. if(($source=self::$_app->getComponent($source))!==null)
  314. $message=$source->translate($category,$message,$language);
  315. }
  316. if($params===array())
  317. return $message;
  318. if(!is_array($params))
  319. $params=array($params);
  320. if(isset($params[0])) // number choice
  321. {
  322. if(strpos($message,'|')!==false)
  323. {
  324. if(strpos($message,'#')===false)
  325. {
  326. $chunks=explode('|',$message);
  327. $expressions=self::$_app->getLocale($language)->getPluralRules();
  328. if($n=min(count($chunks),count($expressions)))
  329. {
  330. for($i=0;$i<$n;$i++)
  331. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  332. $message=implode('|',$chunks);
  333. }
  334. }
  335. $message=CChoiceFormat::format($message,$params[0]);
  336. }
  337. if(!isset($params['{n}']))
  338. $params['{n}']=$params[0];
  339. unset($params[0]);
  340. }
  341. return $params!==array() ? strtr($message,$params) : $message;
  342. }
  343. public static function registerAutoloader($callback, $append=false)
  344. {
  345. if($append)
  346. {
  347. self::$enableIncludePath=false;
  348. spl_autoload_register($callback);
  349. }
  350. else
  351. {
  352. spl_autoload_unregister(array('YiiBase','autoload'));
  353. spl_autoload_register($callback);
  354. spl_autoload_register(array('YiiBase','autoload'));
  355. }
  356. }
  357. private static $_coreClasses=array(
  358. 'CApplication' => '/base/CApplication.php',
  359. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  360. 'CBehavior' => '/base/CBehavior.php',
  361. 'CComponent' => '/base/CComponent.php',
  362. 'CDbStatePersister' => '/base/CDbStatePersister.php',
  363. 'CErrorEvent' => '/base/CErrorEvent.php',
  364. 'CErrorHandler' => '/base/CErrorHandler.php',
  365. 'CException' => '/base/CException.php',
  366. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  367. 'CHttpException' => '/base/CHttpException.php',
  368. 'CModel' => '/base/CModel.php',
  369. 'CModelBehavior' => '/base/CModelBehavior.php',
  370. 'CModelEvent' => '/base/CModelEvent.php',
  371. 'CModule' => '/base/CModule.php',
  372. 'CSecurityManager' => '/base/CSecurityManager.php',
  373. 'CStatePersister' => '/base/CStatePersister.php',
  374. 'CApcCache' => '/caching/CApcCache.php',
  375. 'CCache' => '/caching/CCache.php',
  376. 'CDbCache' => '/caching/CDbCache.php',
  377. 'CDummyCache' => '/caching/CDummyCache.php',
  378. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  379. 'CFileCache' => '/caching/CFileCache.php',
  380. 'CMemCache' => '/caching/CMemCache.php',
  381. 'CRedisCache' => '/caching/CRedisCache.php',
  382. 'CWinCache' => '/caching/CWinCache.php',
  383. 'CXCache' => '/caching/CXCache.php',
  384. 'CZendDataCache' => '/caching/CZendDataCache.php',
  385. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  386. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  387. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  388. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  389. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  390. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  391. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  392. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  393. 'CConfiguration' => '/collections/CConfiguration.php',
  394. 'CList' => '/collections/CList.php',
  395. 'CListIterator' => '/collections/CListIterator.php',
  396. 'CMap' => '/collections/CMap.php',
  397. 'CMapIterator' => '/collections/CMapIterator.php',
  398. 'CQueue' => '/collections/CQueue.php',
  399. 'CQueueIterator' => '/collections/CQueueIterator.php',
  400. 'CStack' => '/collections/CStack.php',
  401. 'CStackIterator' => '/collections/CStackIterator.php',
  402. 'CTypedList' => '/collections/CTypedList.php',
  403. 'CTypedMap' => '/collections/CTypedMap.php',
  404. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  405. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  406. 'CConsoleCommandBehavior' => '/console/CConsoleCommandBehavior.php',
  407. 'CConsoleCommandEvent' => '/console/CConsoleCommandEvent.php',
  408. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  409. 'CHelpCommand' => '/console/CHelpCommand.php',
  410. 'CDbCommand' => '/db/CDbCommand.php',
  411. 'CDbConnection' => '/db/CDbConnection.php',
  412. 'CDbDataReader' => '/db/CDbDataReader.php',
  413. 'CDbException' => '/db/CDbException.php',
  414. 'CDbMigration' => '/db/CDbMigration.php',
  415. 'CDbTransaction' => '/db/CDbTransaction.php',
  416. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  417. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  418. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  419. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  420. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  421. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  422. 'CDbExpression' => '/db/schema/CDbExpression.php',
  423. 'CDbSchema' => '/db/schema/CDbSchema.php',
  424. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  425. 'CCubridColumnSchema' => '/db/schema/cubrid/CCubridColumnSchema.php',
  426. 'CCubridSchema' => '/db/schema/cubrid/CCubridSchema.php',
  427. 'CCubridTableSchema' => '/db/schema/cubrid/CCubridTableSchema.php',
  428. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  429. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  430. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  431. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  432. 'CMssqlSqlsrvPdoAdapter' => '/db/schema/mssql/CMssqlSqlsrvPdoAdapter.php',
  433. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  434. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  435. 'CMysqlCommandBuilder' => '/db/schema/mysql/CMysqlCommandBuilder.php',
  436. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  437. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  438. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  439. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  440. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  441. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  442. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  443. 'CPgsqlCommandBuilder' => '/db/schema/pgsql/CPgsqlCommandBuilder.php',
  444. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  445. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  446. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  447. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  448. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  449. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  450. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  451. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  452. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  453. 'CLocale' => '/i18n/CLocale.php',
  454. 'CMessageSource' => '/i18n/CMessageSource.php',
  455. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  456. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  457. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  458. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  459. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  460. 'CChainedLogFilter' => '/logging/CChainedLogFilter.php',
  461. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  462. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  463. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  464. 'CLogFilter' => '/logging/CLogFilter.php',
  465. 'CLogRoute' => '/logging/CLogRoute.php',
  466. 'CLogRouter' => '/logging/CLogRouter.php',
  467. 'CLogger' => '/logging/CLogger.php',
  468. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  469. 'CSysLogRoute' => '/logging/CSysLogRoute.php',
  470. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  471. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  472. 'CFileHelper' => '/utils/CFileHelper.php',
  473. 'CFormatter' => '/utils/CFormatter.php',
  474. 'CLocalizedFormatter' => '/utils/CLocalizedFormatter.php',
  475. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  476. 'CPasswordHelper' => '/utils/CPasswordHelper.php',
  477. 'CPropertyValue' => '/utils/CPropertyValue.php',
  478. 'CTimestamp' => '/utils/CTimestamp.php',
  479. 'CVarDumper' => '/utils/CVarDumper.php',
  480. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  481. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  482. 'CCompareValidator' => '/validators/CCompareValidator.php',
  483. 'CDateValidator' => '/validators/CDateValidator.php',
  484. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  485. 'CEmailValidator' => '/validators/CEmailValidator.php',
  486. 'CExistValidator' => '/validators/CExistValidator.php',
  487. 'CFileValidator' => '/validators/CFileValidator.php',
  488. 'CFilterValidator' => '/validators/CFilterValidator.php',
  489. 'CInlineValidator' => '/validators/CInlineValidator.php',
  490. 'CNumberValidator' => '/validators/CNumberValidator.php',
  491. 'CRangeValidator' => '/validators/CRangeValidator.php',
  492. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  493. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  494. 'CSafeValidator' => '/validators/CSafeValidator.php',
  495. 'CStringValidator' => '/validators/CStringValidator.php',
  496. 'CTypeValidator' => '/validators/CTypeValidator.php',
  497. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  498. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  499. 'CUrlValidator' => '/validators/CUrlValidator.php',
  500. 'CValidator' => '/validators/CValidator.php',
  501. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  502. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  503. 'CAssetManager' => '/web/CAssetManager.php',
  504. 'CBaseController' => '/web/CBaseController.php',
  505. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  506. 'CClientScript' => '/web/CClientScript.php',
  507. 'CController' => '/web/CController.php',
  508. 'CDataProvider' => '/web/CDataProvider.php',
  509. 'CDataProviderIterator' => '/web/CDataProviderIterator.php',
  510. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  511. 'CExtController' => '/web/CExtController.php',
  512. 'CFormModel' => '/web/CFormModel.php',
  513. 'CHttpCookie' => '/web/CHttpCookie.php',
  514. 'CHttpRequest' => '/web/CHttpRequest.php',
  515. 'CHttpSession' => '/web/CHttpSession.php',
  516. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  517. 'COutputEvent' => '/web/COutputEvent.php',
  518. 'CPagination' => '/web/CPagination.php',
  519. 'CSort' => '/web/CSort.php',
  520. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  521. 'CTheme' => '/web/CTheme.php',
  522. 'CThemeManager' => '/web/CThemeManager.php',
  523. 'CUploadedFile' => '/web/CUploadedFile.php',
  524. 'CUrlManager' => '/web/CUrlManager.php',
  525. 'CWebApplication' => '/web/CWebApplication.php',
  526. 'CWebModule' => '/web/CWebModule.php',
  527. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  528. 'CAction' => '/web/actions/CAction.php',
  529. 'CInlineAction' => '/web/actions/CInlineAction.php',
  530. 'CViewAction' => '/web/actions/CViewAction.php',
  531. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  532. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  533. 'CAuthItem' => '/web/auth/CAuthItem.php',
  534. 'CAuthManager' => '/web/auth/CAuthManager.php',
  535. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  536. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  537. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  538. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  539. 'CWebUser' => '/web/auth/CWebUser.php',
  540. 'CFilter' => '/web/filters/CFilter.php',
  541. 'CFilterChain' => '/web/filters/CFilterChain.php',
  542. 'CHttpCacheFilter' => '/web/filters/CHttpCacheFilter.php',
  543. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  544. 'CForm' => '/web/form/CForm.php',
  545. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  546. 'CFormElement' => '/web/form/CFormElement.php',
  547. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  548. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  549. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  550. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  551. 'CHtml' => '/web/helpers/CHtml.php',
  552. 'CJSON' => '/web/helpers/CJSON.php',
  553. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  554. 'CJavaScriptExpression' => '/web/helpers/CJavaScriptExpression.php',
  555. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  556. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  557. 'CWebService' => '/web/services/CWebService.php',
  558. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  559. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  560. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  561. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  562. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  563. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  564. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  565. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  566. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  567. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  568. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  569. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  570. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  571. 'COutputCache' => '/web/widgets/COutputCache.php',
  572. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  573. 'CStarRating' => '/web/widgets/CStarRating.php',
  574. 'CTabView' => '/web/widgets/CTabView.php',
  575. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  576. 'CTreeView' => '/web/widgets/CTreeView.php',
  577. 'CWidget' => '/web/widgets/CWidget.php',
  578. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  579. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  580. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  581. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  582. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  583. );
  584. }
  585. spl_autoload_register(array('YiiBase','autoload'));
  586. if(!class_exists('YiiBase', false))
  587. require(dirname(__FILE__).'/YiiBase.php');
  588. class Yii extends YiiBase
  589. {
  590. }
  591. class CComponent
  592. {
  593. private $_e;
  594. private $_m;
  595. public function __get($name)
  596. {
  597. $getter='get'.$name;
  598. if(method_exists($this,$getter))
  599. return $this->$getter();
  600. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  601. {
  602. // duplicating getEventHandlers() here for performance
  603. $name=strtolower($name);
  604. if(!isset($this->_e[$name]))
  605. $this->_e[$name]=new CList;
  606. return $this->_e[$name];
  607. }
  608. elseif(isset($this->_m[$name]))
  609. return $this->_m[$name];
  610. elseif(is_array($this->_m))
  611. {
  612. foreach($this->_m as $object)
  613. {
  614. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  615. return $object->$name;
  616. }
  617. }
  618. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  619. array('{class}'=>get_class($this), '{property}'=>$name)));
  620. }
  621. public function __set($name,$value)
  622. {
  623. $setter='set'.$name;
  624. if(method_exists($this,$setter))
  625. return $this->$setter($value);
  626. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  627. {
  628. // duplicating getEventHandlers() here for performance
  629. $name=strtolower($name);
  630. if(!isset($this->_e[$name]))
  631. $this->_e[$name]=new CList;
  632. return $this->_e[$name]->add($value);
  633. }
  634. elseif(is_array($this->_m))
  635. {
  636. foreach($this->_m as $object)
  637. {
  638. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  639. return $object->$name=$value;
  640. }
  641. }
  642. if(method_exists($this,'get'.$name))
  643. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  644. array('{class}'=>get_class($this), '{property}'=>$name)));
  645. else
  646. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  647. array('{class}'=>get_class($this), '{property}'=>$name)));
  648. }
  649. public function __isset($name)
  650. {
  651. $getter='get'.$name;
  652. if(method_exists($this,$getter))
  653. return $this->$getter()!==null;
  654. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  655. {
  656. $name=strtolower($name);
  657. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  658. }
  659. elseif(is_array($this->_m))
  660. {
  661. if(isset($this->_m[$name]))
  662. return true;
  663. foreach($this->_m as $object)
  664. {
  665. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  666. return $object->$name!==null;
  667. }
  668. }
  669. return false;
  670. }
  671. public function __unset($name)
  672. {
  673. $setter='set'.$name;
  674. if(method_exists($this,$setter))
  675. $this->$setter(null);
  676. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  677. unset($this->_e[strtolower($name)]);
  678. elseif(is_array($this->_m))
  679. {
  680. if(isset($this->_m[$name]))
  681. $this->detachBehavior($name);
  682. else
  683. {
  684. foreach($this->_m as $object)
  685. {
  686. if($object->getEnabled())
  687. {
  688. if(property_exists($object,$name))
  689. return $object->$name=null;
  690. elseif($object->canSetProperty($name))
  691. return $object->$setter(null);
  692. }
  693. }
  694. }
  695. }
  696. elseif(method_exists($this,'get'.$name))
  697. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  698. array('{class}'=>get_class($this), '{property}'=>$name)));
  699. }
  700. public function __call($name,$parameters)
  701. {
  702. if($this->_m!==null)
  703. {
  704. foreach($this->_m as $object)
  705. {
  706. if($object->getEnabled() && method_exists($object,$name))
  707. return call_user_func_array(array($object,$name),$parameters);
  708. }
  709. }
  710. if(class_exists('Closure', false) && ($this->canGetProperty($name) || property_exists($this, $name)) && $this->$name instanceof Closure)
  711. return call_user_func_array($this->$name, $parameters);
  712. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  713. array('{class}'=>get_class($this), '{name}'=>$name)));
  714. }
  715. public function asa($behavior)
  716. {
  717. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  718. }
  719. public function attachBehaviors($behaviors)
  720. {
  721. foreach($behaviors as $name=>$behavior)
  722. $this->attachBehavior($name,$behavior);
  723. }
  724. public function detachBehaviors()
  725. {
  726. if($this->_m!==null)
  727. {
  728. foreach($this->_m as $name=>$behavior)
  729. $this->detachBehavior($name);
  730. $this->_m=null;
  731. }
  732. }
  733. public function attachBehavior($name,$behavior)
  734. {
  735. if(!($behavior instanceof IBehavior))
  736. $behavior=Yii::createComponent($behavior);
  737. $behavior->setEnabled(true);
  738. $behavior->attach($this);
  739. return $this->_m[$name]=$behavior;
  740. }
  741. public function detachBehavior($name)
  742. {
  743. if(isset($this->_m[$name]))
  744. {
  745. $this->_m[$name]->detach($this);
  746. $behavior=$this->_m[$name];
  747. unset($this->_m[$name]);
  748. return $behavior;
  749. }
  750. }
  751. public function enableBehaviors()
  752. {
  753. if($this->_m!==null)
  754. {
  755. foreach($this->_m as $behavior)
  756. $behavior->setEnabled(true);
  757. }
  758. }
  759. public function disableBehaviors()
  760. {
  761. if($this->_m!==null)
  762. {
  763. foreach($this->_m as $behavior)
  764. $behavior->setEnabled(false);
  765. }
  766. }
  767. public function enableBehavior($name)
  768. {
  769. if(isset($this->_m[$name]))
  770. $this->_m[$name]->setEnabled(true);
  771. }
  772. public function disableBehavior($name)
  773. {
  774. if(isset($this->_m[$name]))
  775. $this->_m[$name]->setEnabled(false);
  776. }
  777. public function hasProperty($name)
  778. {
  779. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  780. }
  781. public function canGetProperty($name)
  782. {
  783. return method_exists($this,'get'.$name);
  784. }
  785. public function canSetProperty($name)
  786. {
  787. return method_exists($this,'set'.$name);
  788. }
  789. public function hasEvent($name)
  790. {
  791. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  792. }
  793. public function hasEventHandler($name)
  794. {
  795. $name=strtolower($name);
  796. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  797. }
  798. public function getEventHandlers($name)
  799. {
  800. if($this->hasEvent($name))
  801. {
  802. $name=strtolower($name);
  803. if(!isset($this->_e[$name]))
  804. $this->_e[$name]=new CList;
  805. return $this->_e[$name];
  806. }
  807. else
  808. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  809. array('{class}'=>get_class($this), '{event}'=>$name)));
  810. }
  811. public function attachEventHandler($name,$handler)
  812. {
  813. $this->getEventHandlers($name)->add($handler);
  814. }
  815. public function detachEventHandler($name,$handler)
  816. {
  817. if($this->hasEventHandler($name))
  818. return $this->getEventHandlers($name)->remove($handler)!==false;
  819. else
  820. return false;
  821. }
  822. public function raiseEvent($name,$event)
  823. {
  824. $name=strtolower($name);
  825. if(isset($this->_e[$name]))
  826. {
  827. foreach($this->_e[$name] as $handler)
  828. {
  829. if(is_string($handler))
  830. call_user_func($handler,$event);
  831. elseif(is_callable($handler,true))
  832. {
  833. if(is_array($handler))
  834. {
  835. // an array: 0 - object, 1 - method name
  836. list($object,$method)=$handler;
  837. if(is_string($object)) // static method call
  838. call_user_func($handler,$event);
  839. elseif(method_exists($object,$method))
  840. $object->$method($event);
  841. else
  842. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  843. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  844. }
  845. else // PHP 5.3: anonymous function
  846. call_user_func($handler,$event);
  847. }
  848. else
  849. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  850. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  851. // stop further handling if param.handled is set true
  852. if(($event instanceof CEvent) && $event->handled)
  853. return;
  854. }
  855. }
  856. elseif(YII_DEBUG && !$this->hasEvent($name))
  857. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  858. array('{class}'=>get_class($this), '{event}'=>$name)));
  859. }
  860. public function evaluateExpression($_expression_,$_data_=array())
  861. {
  862. if(is_string($_expression_))
  863. {
  864. extract($_data_);
  865. return eval('return '.$_expression_.';');
  866. }
  867. else
  868. {
  869. $_data_[]=$this;
  870. return call_user_func_array($_expression_, $_data_);
  871. }
  872. }
  873. }
  874. class CEvent extends CComponent
  875. {
  876. public $sender;
  877. public $handled=false;
  878. public $params;
  879. public function __construct($sender=null,$params=null)
  880. {
  881. $this->sender=$sender;
  882. $this->params=$params;
  883. }
  884. }
  885. class CEnumerable
  886. {
  887. }
  888. abstract class CModule extends CComponent
  889. {
  890. public $preload=array();
  891. public $behaviors=array();
  892. private $_id;
  893. private $_parentModule;
  894. private $_basePath;
  895. private $_modulePath;
  896. private $_params;
  897. private $_modules=array();
  898. private $_moduleConfig=array();
  899. private $_components=array();
  900. private $_componentConfig=array();
  901. public function __construct($id,$parent,$config=null)
  902. {
  903. $this->_id=$id;
  904. $this->_parentModule=$parent;
  905. // set basePath at early as possible to avoid trouble
  906. if(is_string($config))
  907. $config=require($config);
  908. if(isset($config['basePath']))
  909. {
  910. $this->setBasePath($config['basePath']);
  911. unset($config['basePath']);
  912. }
  913. Yii::setPathOfAlias($id,$this->getBasePath());
  914. $this->preinit();
  915. $this->configure($config);
  916. $this->attachBehaviors($this->behaviors);
  917. $this->preloadComponents();
  918. $this->init();
  919. }
  920. public function __get($name)
  921. {
  922. if($this->hasComponent($name))
  923. return $this->getComponent($name);
  924. else
  925. return parent::__get($name);
  926. }
  927. public function __isset($name)
  928. {
  929. if($this->hasComponent($name))
  930. return $this->getComponent($name)!==null;
  931. else
  932. return parent::__isset($name);
  933. }
  934. public function getId()
  935. {
  936. return $this->_id;
  937. }
  938. public function setId($id)
  939. {
  940. $this->_id=$id;
  941. }
  942. public function getBasePath()
  943. {
  944. if($this->_basePath===null)
  945. {
  946. $class=new ReflectionClass(get_class($this));
  947. $this->_basePath=dirname($class->getFileName());
  948. }
  949. return $this->_basePath;
  950. }
  951. public function setBasePath($path)
  952. {
  953. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  954. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  955. array('{path}'=>$path)));
  956. }
  957. public function getParams()
  958. {
  959. if($this->_params!==null)
  960. return $this->_params;
  961. else
  962. {
  963. $this->_params=new CAttributeCollection;
  964. $this->_params->caseSensitive=true;
  965. return $this->_params;
  966. }
  967. }
  968. public function setParams($value)
  969. {
  970. $params=$this->getParams();
  971. foreach($value as $k=>$v)
  972. $params->add($k,$v);
  973. }
  974. public function getModulePath()
  975. {
  976. if($this->_modulePath!==null)
  977. return $this->_modulePath;
  978. else
  979. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  980. }
  981. public function setModulePath($value)
  982. {
  983. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  984. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  985. array('{path}'=>$value)));
  986. }
  987. public function setImport($aliases)
  988. {
  989. foreach($aliases as $alias)
  990. Yii::import($alias);
  991. }
  992. public function setAliases($mappings)
  993. {
  994. foreach($mappings as $name=>$alias)
  995. {
  996. if(($path=Yii::getPathOfAlias($alias))!==false)
  997. Yii::setPathOfAlias($name,$path);
  998. else
  999. Yii::setPathOfAlias($name,$alias);
  1000. }
  1001. }
  1002. public function getParentModule()
  1003. {
  1004. return $this->_parentModule;
  1005. }
  1006. public function getModule($id)
  1007. {
  1008. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  1009. return $this->_modules[$id];
  1010. elseif(isset($this->_moduleConfig[$id]))
  1011. {
  1012. $config=$this->_moduleConfig[$id];
  1013. if(!isset($config['enabled']) || $config['enabled'])
  1014. {
  1015. $class=$config['class'];
  1016. unset($config['class'], $config['enabled']);
  1017. if($this===Yii::app())
  1018. $module=Yii::createComponent($class,$id,null,$config);
  1019. else
  1020. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  1021. return $this->_modules[$id]=$module;
  1022. }
  1023. }
  1024. }
  1025. public function hasModule($id)
  1026. {
  1027. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  1028. }
  1029. public function getModules()
  1030. {
  1031. return $this->_moduleConfig;
  1032. }
  1033. public function setModules($modules,$merge=true)
  1034. {
  1035. foreach($modules as $id=>$module)
  1036. {
  1037. if(is_int($id))
  1038. {
  1039. $id=$module;
  1040. $module=array();
  1041. }
  1042. if(isset($this->_moduleConfig[$id]) && $merge)
  1043. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1044. else
  1045. {
  1046. if(!isset($module['class']))
  1047. {
  1048. if (Yii::getPathOfAlias($id)===false)
  1049. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1050. $module['class']=$id.'.'.ucfirst($id).'Module';
  1051. }
  1052. $this->_moduleConfig[$id]=$module;
  1053. }
  1054. }
  1055. }
  1056. public function hasComponent($id)
  1057. {
  1058. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1059. }
  1060. public function getComponent($id,$createIfNull=true)
  1061. {
  1062. if(isset($this->_components[$id]))
  1063. return $this->_components[$id];
  1064. elseif(isset($this->_componentConfig[$id]) && $createIfNull)
  1065. {
  1066. $config=$this->_componentConfig[$id];
  1067. if(!isset($config['enabled']) || $config['enabled'])
  1068. {
  1069. unset($config['enabled']);
  1070. $component=Yii::createComponent($config);
  1071. $component->init();
  1072. return $this->_components[$id]=$component;
  1073. }
  1074. }
  1075. }
  1076. public function setComponent($id,$component,$merge=true)
  1077. {
  1078. if($component===null)
  1079. {
  1080. unset($this->_components[$id]);
  1081. return;
  1082. }
  1083. elseif($component instanceof IApplicationComponent)
  1084. {
  1085. $this->_components[$id]=$component;
  1086. if(!$component->getIsInitialized())
  1087. $component->init();
  1088. return;
  1089. }
  1090. elseif(isset($this->_components[$id]))
  1091. {
  1092. if(isset($component['class']) && get_class($this->_components[$id])!==$component['class'])
  1093. {
  1094. unset($this->_components[$id]);
  1095. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1096. return;
  1097. }
  1098. foreach($component as $key=>$value)
  1099. {
  1100. if($key!=='class')
  1101. $this->_components[$id]->$key=$value;
  1102. }
  1103. }
  1104. elseif(isset($this->_componentConfig[$id]['class'],$component['class'])
  1105. && $this->_componentConfig[$id]['class']!==$component['class'])
  1106. {
  1107. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1108. return;
  1109. }
  1110. if(isset($this->_componentConfig[$id]) && $merge)
  1111. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1112. else
  1113. $this->_componentConfig[$id]=$component;
  1114. }
  1115. public function getComponents($loadedOnly=true)
  1116. {
  1117. if($loadedOnly)
  1118. return $this->_components;
  1119. else
  1120. return array_merge($this->_componentConfig, $this->_components);
  1121. }
  1122. public function setComponents($components,$merge=true)
  1123. {
  1124. foreach($components as $id=>$component)
  1125. $this->setComponent($id,$component,$merge);
  1126. }
  1127. public function configure($config)
  1128. {
  1129. if(is_array($config))
  1130. {
  1131. foreach($config as $key=>$value)
  1132. $this->$key=$value;
  1133. }
  1134. }
  1135. protected function preloadComponents()
  1136. {
  1137. foreach($this->preload as $id)
  1138. $this->getComponent($id);
  1139. }
  1140. protected function preinit()
  1141. {
  1142. }
  1143. protected function init()
  1144. {
  1145. }
  1146. }
  1147. abstract class CApplication extends CModule
  1148. {
  1149. public $name='My Application';
  1150. public $charset='UTF-8';
  1151. public $sourceLanguage='en_us';
  1152. public $localeClass='CLocale';
  1153. private $_id;
  1154. private $_basePath;
  1155. private $_runtimePath;
  1156. private $_extensionPath;
  1157. private $_globalState;
  1158. private $_stateChanged;
  1159. private $_ended=false;
  1160. private $_language;
  1161. private $_homeUrl;
  1162. abstract public function processRequest();
  1163. public function __construct($config=null)
  1164. {
  1165. Yii::setApplication($this);
  1166. // set basePath at early as possible to avoid trouble
  1167. if(is_string($config))
  1168. $config=require($config);
  1169. if(isset($config['basePath']))
  1170. {
  1171. $this->setBasePath($config['basePath']);
  1172. unset($config['basePath']);
  1173. }
  1174. else
  1175. $this->setBasePath('protected');
  1176. Yii::setPathOfAlias('application',$this->getBasePath());
  1177. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1178. if(isset($config['extensionPath']))
  1179. {
  1180. $this->setExtensionPath($config['extensionPath']);
  1181. unset($config['extensionPath']);
  1182. }
  1183. else
  1184. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1185. if(isset($config['aliases']))
  1186. {
  1187. $this->setAliases($config['aliases']);
  1188. unset($config['aliases']);
  1189. }
  1190. $this->preinit();
  1191. $this->initSystemHandlers();
  1192. $this->registerCoreComponents();
  1193. $this->configure($config);
  1194. $this->attachBehaviors($this->behaviors);
  1195. $this->preloadComponents();
  1196. $this->init();
  1197. }
  1198. public function run()
  1199. {
  1200. if($this->hasEventHandler('onBeginRequest'))
  1201. $this->onBeginRequest(new CEvent($this));
  1202. register_shutdown_function(array($this,'end'),0,false);
  1203. $this->processRequest();
  1204. if($this->hasEventHandler('onEndRequest'))
  1205. $this->onEndRequest(new CEvent($this));
  1206. }
  1207. public function end($status=0,$exit=true)
  1208. {
  1209. if($this->hasEventHandler('onEndRequest'))
  1210. $this->onEndRequest(new CEvent($this));
  1211. if($exit)
  1212. exit($status);
  1213. }
  1214. public function onBeginRequest($event)
  1215. {
  1216. $this->raiseEvent('onBeginRequest',$event);
  1217. }
  1218. public function onEndRequest($event)
  1219. {
  1220. if(!$this->_ended)
  1221. {
  1222. $this->_ended=true;
  1223. $this->raiseEvent('onEndRequest',$event);
  1224. }
  1225. }
  1226. public function getId()
  1227. {
  1228. if($this->_id!==null)
  1229. return $this->_id;
  1230. else
  1231. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1232. }
  1233. public function setId($id)
  1234. {
  1235. $this->_id=$id;
  1236. }
  1237. public function getBasePath()
  1238. {
  1239. return $this->_basePath;
  1240. }
  1241. public function setBasePath($path)
  1242. {
  1243. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1244. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1245. array('{path}'=>$path)));
  1246. }
  1247. public function getRuntimePath()
  1248. {
  1249. if($this->_runtimePath!==null)
  1250. return $this->_runtimePath;
  1251. else
  1252. {
  1253. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1254. return $this->_runtimePath;
  1255. }
  1256. }
  1257. public function setRuntimePath($path)
  1258. {
  1259. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1260. 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.',
  1261. array('{path}'=>$path)));
  1262. $this->_runtimePath=$runtimePath;
  1263. }
  1264. public function getExtensionPath()
  1265. {
  1266. return Yii::getPathOfAlias('ext');
  1267. }
  1268. public function setExtensionPath($path)
  1269. {
  1270. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1271. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1272. array('{path}'=>$path)));
  1273. Yii::setPathOfAlias('ext',$extensionPath);
  1274. }
  1275. public function getLanguage()
  1276. {
  1277. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1278. }
  1279. public function setLanguage($language)
  1280. {
  1281. $this->_language=$language;
  1282. }
  1283. public function getTimeZone()
  1284. {
  1285. return date_default_timezone_get();
  1286. }
  1287. public function setTimeZone($value)
  1288. {
  1289. date_default_timezone_set($value);
  1290. }
  1291. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1292. {
  1293. if($srcLanguage===null)
  1294. $srcLanguage=$this->sourceLanguage;
  1295. if($language===null)
  1296. $language=$this->getLanguage();
  1297. if($language===$srcLanguage)
  1298. return $srcFile;
  1299. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1300. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1301. }
  1302. public function getLocale($localeID=null)
  1303. {
  1304. return call_user_func_array(array($this->localeClass, 'getInstance'),array($localeID===null?$this->getLanguage():$localeID));
  1305. }
  1306. public function getLocaleDataPath()
  1307. {
  1308. $vars=get_class_vars($this->localeClass);
  1309. if(empty($vars['dataPath']))
  1310. return Yii::getPathOfAlias('system.i18n.data');
  1311. return $vars['dataPath'];
  1312. }
  1313. public function setLocaleDataPath($value)
  1314. {
  1315. $property=new ReflectionProperty($this->localeClass,'dataPath');
  1316. $property->setValue($value);
  1317. }
  1318. public function getNumberFormatter()
  1319. {
  1320. return $this->getLocale()->getNumberFormatter();
  1321. }
  1322. public function getDateFormatter()
  1323. {
  1324. return $this->getLocale()->getDateFormatter();
  1325. }
  1326. public function getDb()
  1327. {
  1328. return $this->getComponent('db');
  1329. }
  1330. public function getErrorHandler()
  1331. {
  1332. return $this->getComponent('errorHandler');
  1333. }
  1334. public function getSecurityManager()
  1335. {
  1336. return $this->getComponent('securityManager');
  1337. }
  1338. public function getStatePersister()
  1339. {
  1340. return $this->getComponent('statePersister');
  1341. }
  1342. public function getCache()
  1343. {
  1344. return $this->getComponent('cache');
  1345. }
  1346. public function getCoreMessages()
  1347. {
  1348. return $this->getComponent('coreMessages');
  1349. }
  1350. public function getMessages()
  1351. {
  1352. return $this->getComponent('messages');
  1353. }
  1354. public function getRequest()
  1355. {
  1356. return $this->getComponent('request');
  1357. }
  1358. public function getUrlManager()
  1359. {
  1360. return $this->getComponent('urlManager');
  1361. }
  1362. public function getFormat()
  1363. {
  1364. return $this->getComponent('format');
  1365. }
  1366. public function getController()
  1367. {
  1368. return null;
  1369. }
  1370. public function createUrl($route,$params=array(),$ampersand='&')
  1371. {
  1372. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1373. }
  1374. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1375. {
  1376. $url=$this->createUrl($route,$params,$ampersand);
  1377. if(strpos($url,'http')===0)
  1378. return $url;
  1379. else
  1380. return $this->getRequest()->getHostInfo($schema).$url;
  1381. }
  1382. public function getBaseUrl($absolute=false)
  1383. {
  1384. return $this->getRequest()->getBaseUrl($absolute);
  1385. }
  1386. public function getHomeUrl()
  1387. {
  1388. if($this->_homeUrl===null)
  1389. {
  1390. if($this->getUrlManager()->showScriptName)
  1391. return $this->getRequest()->getScriptUrl();
  1392. else
  1393. return $this->getRequest()->getBaseUrl().'/';
  1394. }
  1395. else
  1396. return $this->_homeUrl;
  1397. }
  1398. public function setHomeUrl($value)
  1399. {
  1400. $this->_homeUrl=$value;
  1401. }
  1402. public function getGlobalState($key,$defaultValue=null)
  1403. {
  1404. if($this->_globalState===null)
  1405. $this->loadGlobalState();
  1406. if(isset($this->_globalState[$key]))
  1407. return $this->_globalState[$key];
  1408. else
  1409. return $defaultValue;
  1410. }
  1411. public function setGlobalState($key,$value,$defaultValue=null)
  1412. {
  1413. if($this->_globalState===null)
  1414. $this->loadGlobalState();
  1415. $changed=$this->_stateChanged;
  1416. if($value===$defaultValue)
  1417. {
  1418. if(isset($this->_globalState[$key]))
  1419. {
  1420. unset($this->_globalState[$key]);
  1421. $this->_stateChanged=true;
  1422. }
  1423. }
  1424. elseif(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1425. {
  1426. $this->_globalState[$key]=$value;
  1427. $this->_stateChanged=true;
  1428. }
  1429. if($this->_stateChanged!==$changed)
  1430. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1431. }
  1432. public function clearGlobalState($key)
  1433. {
  1434. $this->setGlobalState($key,true,true);
  1435. }
  1436. public function loadGlobalState()
  1437. {
  1438. $persister=$this->getStatePersister();
  1439. if(($this->_globalState=$persister->load())===null)
  1440. $this->_globalState=array();
  1441. $this->_stateChanged=false;
  1442. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1443. }
  1444. public function saveGlobalState()
  1445. {
  1446. if($this->_stateChanged)
  1447. {
  1448. $this->_stateChanged=false;
  1449. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1450. $this->getStatePersister()->save($this->_globalState);
  1451. }
  1452. }
  1453. public function handleException($exception)
  1454. {
  1455. // disable error capturing to avoid recursive errors
  1456. restore_error_handler();
  1457. restore_exception_handler();
  1458. $category='exception.'.get_class($exception);
  1459. if($exception instanceof CHttpException)
  1460. $category.='.'.$exception->statusCode;
  1461. // php <5.2 doesn't support string conversion auto-magically
  1462. $message=$exception->__toString();
  1463. if(isset($_SERVER['REQUEST_URI']))
  1464. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  1465. if(isset($_SERVER['HTTP_REFERER']))
  1466. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  1467. $message.="\n---";
  1468. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1469. try
  1470. {
  1471. $event=new CExceptionEvent($this,$exception);
  1472. $this->onException($event);
  1473. if(!$event->handled)
  1474. {
  1475. // try an error handler
  1476. if(($handler=$this->getErrorHandler())!==null)
  1477. $handler->handle($event);
  1478. else
  1479. $this->displayException($exception);
  1480. }
  1481. }
  1482. catch(Exception $e)
  1483. {
  1484. $this->displayException($e);
  1485. }
  1486. try
  1487. {
  1488. $this->end(1);
  1489. }
  1490. catch(Exception $e)
  1491. {
  1492. // use the most primitive way to log error
  1493. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1494. $msg .= $e->getTraceAsString()."\n";
  1495. $msg .= "Previous exception:\n";
  1496. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1497. $msg .= $exception->getTraceAsString()."\n";
  1498. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1499. error_log($msg);
  1500. exit(1);
  1501. }
  1502. }
  1503. public function handleError($code,$message,$file,$line)
  1504. {
  1505. if($code & error_reporting())
  1506. {
  1507. // disable error capturing to avoid recursive errors
  1508. restore_error_handler();
  1509. restore_exception_handler();
  1510. $log="$message ($file:$line)\nStack trace:\n";
  1511. $trace=debug_backtrace();
  1512. // skip the first 3 stacks as they do not tell the error position
  1513. if(count($trace)>3)
  1514. $trace=array_slice($trace,3);
  1515. foreach($trace as $i=>$t)
  1516. {
  1517. if(!isset($t['file']))
  1518. $t['file']='unknown';
  1519. if(!isset($t['line']))
  1520. $t['line']=0;
  1521. if(!isset($t['function']))
  1522. $t['function']='unknown';
  1523. $log.="#$i {$t['file']}({$t['line']}): ";
  1524. if(isset($t['object']) && is_object($t['object']))
  1525. $log.=get_class($t['object']).'->';
  1526. $log.="{$t['function']}()\n";
  1527. }
  1528. if(isset($_SERVER['REQUEST_URI']))
  1529. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1530. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1531. try
  1532. {
  1533. Yii::import('CErrorEvent',true);
  1534. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1535. $this->onError($event);
  1536. if(!$event->handled)
  1537. {
  1538. // try an error handler
  1539. if(($handler=$this->getErrorHandler())!==null)
  1540. $handler->handle($event);
  1541. else
  1542. $this->displayError($code,$message,$file,$line);
  1543. }
  1544. }
  1545. catch(Exception $e)
  1546. {
  1547. $this->displayException($e);
  1548. }
  1549. try
  1550. {
  1551. $this->end(1);
  1552. }
  1553. catch(Exception $e)
  1554. {
  1555. // use the most primitive way to log error
  1556. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1557. $msg .= $e->getTraceAsString()."\n";
  1558. $msg .= "Previous error:\n";
  1559. $msg .= $log."\n";
  1560. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1561. error_log($msg);
  1562. exit(1);
  1563. }
  1564. }
  1565. }
  1566. public function onException($event)
  1567. {
  1568. $this->raiseEvent('onException',$event);
  1569. }
  1570. public function onError($event)
  1571. {
  1572. $this->raiseEvent('onError',$event);
  1573. }
  1574. public function displayError($code,$message,$file,$line)
  1575. {
  1576. if(YII_DEBUG)
  1577. {
  1578. echo "<h1>PHP Error [$code]</h1>\n";
  1579. echo "<p>$message ($file:$line)</p>\n";
  1580. echo '<pre>';
  1581. $trace=debug_backtrace();
  1582. // skip the first 3 stacks as they do not tell the error position
  1583. if(count($trace)>3)
  1584. $trace=array_slice($trace,3);
  1585. foreach($trace as $i=>$t)
  1586. {
  1587. if(!isset($t['file']))
  1588. $t['file']='unknown';
  1589. if(!isset($t['line']))
  1590. $t['line']=0;
  1591. if(!isset($t['function']))
  1592. $t['function']='unknown';
  1593. echo "#$i {$t['file']}({$t['line']}): ";
  1594. if(isset($t['object']) && is_object($t['object']))
  1595. echo get_class($t['object']).'->';
  1596. echo "{$t['function']}()\n";
  1597. }
  1598. echo '</pre>';
  1599. }
  1600. else
  1601. {
  1602. echo "<h1>PHP Error [$code]</h1>\n";
  1603. echo "<p>$message</p>\n";
  1604. }
  1605. }
  1606. public function displayException($exception)
  1607. {
  1608. if(YII_DEBUG)
  1609. {
  1610. echo '<h1>'.get_class($exception)."</h1>\n";
  1611. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1612. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1613. }
  1614. else
  1615. {
  1616. echo '<h1>'.get_class($exception)."</h1>\n";
  1617. echo '<p>'.$exception->getMessage().'</p>';
  1618. }
  1619. }
  1620. protected function initSystemHandlers()
  1621. {
  1622. if(YII_ENABLE_EXCEPTION_HANDLER)
  1623. set_exception_handler(array($this,'handleException'));
  1624. if(YII_ENABLE_ERROR_HANDLER)
  1625. set_error_handler(array($this,'handleError'),error_reporting());
  1626. }
  1627. protected function registerCoreComponents()
  1628. {
  1629. $components=array(
  1630. 'coreMessages'=>array(
  1631. 'class'=>'CPhpMessageSource',
  1632. 'language'=>'en_us',
  1633. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1634. ),
  1635. 'db'=>array(
  1636. 'class'=>'CDbConnection',
  1637. ),
  1638. 'messages'=>array(
  1639. 'class'=>'CPhpMessageSource',
  1640. ),
  1641. 'errorHandler'=>array(
  1642. 'class'=>'CErrorHandler',
  1643. ),
  1644. 'securityManager'=>array(
  1645. 'class'=>'CSecurityManager',
  1646. ),
  1647. 'statePersister'=>array(
  1648. 'class'=>'CStatePersister',
  1649. ),
  1650. 'urlManager'=>array(
  1651. 'class'=>'CUrlManager',
  1652. ),
  1653. 'request'=>array(
  1654. 'class'=>'CHttpRequest',
  1655. ),
  1656. 'format'=>array(
  1657. 'class'=>'CFormatter',
  1658. ),
  1659. );
  1660. $this->setComponents($components);
  1661. }
  1662. }
  1663. class CWebApplication extends CApplication
  1664. {
  1665. public $defaultController='site';
  1666. public $layout='main';
  1667. public $controllerMap=array();
  1668. public $catchAllRequest;
  1669. public $controllerNamespace;
  1670. private $_controllerPath;
  1671. private $_viewPath;
  1672. private $_systemViewPath;
  1673. private $_layoutPath;
  1674. private $_controller;
  1675. private $_theme;
  1676. public function processRequest()
  1677. {
  1678. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1679. {
  1680. $route=$this->catchAllRequest[0];
  1681. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1682. $_GET[$name]=$value;
  1683. }
  1684. else
  1685. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1686. $this->runController($route);
  1687. }
  1688. protected function registerCoreComponents()
  1689. {
  1690. parent::registerCoreComponents();
  1691. $components=array(
  1692. 'session'=>array(
  1693. 'class'=>'CHttpSession',
  1694. ),
  1695. 'assetManager'=>array(
  1696. 'class'=>'CAssetManager',
  1697. ),
  1698. 'user'=>array(
  1699. 'class'=>'CWebUser',
  1700. ),
  1701. 'themeManager'=>array(
  1702. 'class'=>'CThemeManager',
  1703. ),
  1704. 'authManager'=>array(
  1705. 'class'=>'CPhpAuthManager',
  1706. ),
  1707. 'clientScript'=>array(
  1708. 'class'=>'CClientScript',
  1709. ),
  1710. 'widgetFactory'=>array(
  1711. 'class'=>'CWidgetFactory',
  1712. ),
  1713. );
  1714. $this->setComponents($components);
  1715. }
  1716. public function getAuthManager()
  1717. {
  1718. return $this->getComponent('authManager');
  1719. }
  1720. public function getAssetManager()
  1721. {
  1722. return $this->getComponent('assetManager');
  1723. }
  1724. public function getSession()
  1725. {
  1726. return $this->getComponent('session');
  1727. }
  1728. public function getUser()
  1729. {
  1730. return $this->getComponent('user');
  1731. }
  1732. public function getViewRenderer()
  1733. {
  1734. return $this->getComponent('viewRenderer');
  1735. }
  1736. public function getClientScript()
  1737. {
  1738. return $this->getComponent('clientScript');
  1739. }
  1740. public function getWidgetFactory()
  1741. {
  1742. return $this->getComponent('widgetFactory');
  1743. }
  1744. public function getThemeManager()
  1745. {
  1746. return $this->getComponent('themeManager');
  1747. }
  1748. public function getTheme()
  1749. {
  1750. if(is_string($this->_theme))
  1751. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1752. return $this->_theme;
  1753. }
  1754. public function setTheme($value)
  1755. {
  1756. $this->_theme=$value;
  1757. }
  1758. public function runController($route)
  1759. {
  1760. if(($ca=$this->createController($route))!==null)
  1761. {
  1762. list($controller,$actionID)=$ca;
  1763. $oldController=$this->_controller;
  1764. $this->_controller=$controller;
  1765. $controller->init();
  1766. $controller->run($actionID);
  1767. $this->_controller=$oldController;
  1768. }
  1769. else
  1770. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1771. array('{route}'=>$route===''?$this->defaultController:$route)));
  1772. }
  1773. public function createController($route,$owner=null)
  1774. {
  1775. if($owner===null)
  1776. $owner=$this;
  1777. if((array)$route===$route || ($route=trim($route,'/'))==='')
  1778. $route=$owner->defaultController;
  1779. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1780. $route.='/';
  1781. while(($pos=strpos($route,'/'))!==false)
  1782. {
  1783. $id=substr($route,0,$pos);
  1784. if(!preg_match('/^\w+$/',$id))
  1785. return null;
  1786. if(!$caseSensitive)
  1787. $id=strtolower($id);
  1788. $route=(string)substr($route,$pos+1);
  1789. if(!isset($basePath)) // first segment
  1790. {
  1791. if(isset($owner->controllerMap[$id]))
  1792. {
  1793. return array(
  1794. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1795. $this->parseActionParams($route),
  1796. );
  1797. }
  1798. if(($module=$owner->getModule($id))!==null)
  1799. return $this->createController($route,$module);
  1800. $basePath=$owner->getControllerPath();
  1801. $controllerID='';
  1802. }
  1803. else
  1804. $controllerID.='/';
  1805. $className=ucfirst($id).'Controller';
  1806. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1807. if($owner->controllerNamespace!==null)
  1808. $className=$owner->controllerNamespace.'\\'.str_replace('/','\\',$controllerID).$className;
  1809. if(is_file($classFile))
  1810. {
  1811. if(!class_exists($className,false))
  1812. require($classFile);
  1813. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1814. {
  1815. $id[0]=strtolower($id[0]);
  1816. return array(
  1817. new $className($controllerID.$id,$owner===$this?null:$owner),
  1818. $this->parseActionParams($route),
  1819. );
  1820. }
  1821. return null;
  1822. }
  1823. $controllerID.=$id;
  1824. $basePath.=DIRECTORY_SEPARATOR.$id;
  1825. }
  1826. }
  1827. protected function parseActionParams($pathInfo)
  1828. {
  1829. if(($pos=strpos($pathInfo,'/'))!==false)
  1830. {
  1831. $manager=$this->getUrlManager();
  1832. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1833. $actionID=substr($pathInfo,0,$pos);
  1834. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1835. }
  1836. else
  1837. return $pathInfo;
  1838. }
  1839. public function getController()
  1840. {
  1841. return $this->_controller;
  1842. }
  1843. public function setController($value)
  1844. {
  1845. $this->_controller=$value;
  1846. }
  1847. public function getControllerPath()
  1848. {
  1849. if($this->_controllerPath!==null)
  1850. return $this->_controllerPath;
  1851. else
  1852. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1853. }
  1854. public function setControllerPath($value)
  1855. {
  1856. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1857. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1858. array('{path}'=>$value)));
  1859. }
  1860. public function getViewPath()
  1861. {
  1862. if($this->_viewPath!==null)
  1863. return $this->_viewPath;
  1864. else
  1865. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1866. }
  1867. public function setViewPath($path)
  1868. {
  1869. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1870. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1871. array('{path}'=>$path)));
  1872. }
  1873. public function getSystemViewPath()
  1874. {
  1875. if($this->_systemViewPath!==null)
  1876. return $this->_systemViewPath;
  1877. else
  1878. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1879. }
  1880. public function setSystemViewPath($path)
  1881. {
  1882. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1883. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1884. array('{path}'=>$path)));
  1885. }
  1886. public function getLayoutPath()
  1887. {
  1888. if($this->_layoutPath!==null)
  1889. return $this->_layoutPath;
  1890. else
  1891. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1892. }
  1893. public function setLayoutPath($path)
  1894. {
  1895. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1896. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1897. array('{path}'=>$path)));
  1898. }
  1899. public function beforeControllerAction($controller,$action)
  1900. {
  1901. return true;
  1902. }
  1903. public function afterControllerAction($controller,$action)
  1904. {
  1905. }
  1906. public function findModule($id)
  1907. {
  1908. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1909. {
  1910. do
  1911. {
  1912. if(($m=$module->getModule($id))!==null)
  1913. return $m;
  1914. } while(($module=$module->getParentModule())!==null);
  1915. }
  1916. if(($m=$this->getModule($id))!==null)
  1917. return $m;
  1918. }
  1919. protected function init()
  1920. {
  1921. parent::init();
  1922. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1923. $this->getRequest();
  1924. }
  1925. }
  1926. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1927. {
  1928. private $_d=array();
  1929. private $_r=false;
  1930. public function __construct($data=null,$readOnly=false)
  1931. {
  1932. if($data!==null)
  1933. $this->copyFrom($data);
  1934. $this->setReadOnly($readOnly);
  1935. }
  1936. public function getReadOnly()
  1937. {
  1938. return $this->_r;
  1939. }
  1940. protected function setReadOnly($value)
  1941. {
  1942. $this->_r=$value;
  1943. }
  1944. public function getIterator()
  1945. {
  1946. return new CMapIterator($this->_d);
  1947. }
  1948. public function count()
  1949. {
  1950. return $this->getCount();
  1951. }
  1952. public function getCount()
  1953. {
  1954. return count($this->_d);
  1955. }
  1956. public function getKeys()
  1957. {
  1958. return array_keys($this->_d);
  1959. }
  1960. public function itemAt($key)
  1961. {
  1962. if(isset($this->_d[$key]))
  1963. return $this->_d[$key];
  1964. else
  1965. return null;
  1966. }
  1967. public function add($key,$value)
  1968. {
  1969. if(!$this->_r)
  1970. {
  1971. if($key===null)
  1972. $this->_d[]=$value;
  1973. else
  1974. $this->_d[$key]=$value;
  1975. }
  1976. else
  1977. throw new CException(Yii::t('yii','The map is read only.'));
  1978. }
  1979. public function remove($key)
  1980. {
  1981. if(!$this->_r)
  1982. {
  1983. if(isset($this->_d[$key]))
  1984. {
  1985. $value=$this->_d[$key];
  1986. unset($this->_d[$key]);
  1987. return $value;
  1988. }
  1989. else
  1990. {
  1991. // it is possible the value is null, which is not detected by isset
  1992. unset($this->_d[$key]);
  1993. return null;
  1994. }
  1995. }
  1996. else
  1997. throw new CException(Yii::t('yii','The map is read only.'));
  1998. }
  1999. public function clear()
  2000. {
  2001. foreach(array_keys($this->_d) as $key)
  2002. $this->remove($key);
  2003. }
  2004. public function contains($key)
  2005. {
  2006. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  2007. }
  2008. public function toArray()
  2009. {
  2010. return $this->_d;
  2011. }
  2012. public function copyFrom($data)
  2013. {
  2014. if(is_array($data) || $data instanceof Traversable)
  2015. {
  2016. if($this->getCount()>0)
  2017. $this->clear();
  2018. if($data instanceof CMap)
  2019. $data=$data->_d;
  2020. foreach($data as $key=>$value)
  2021. $this->add($key,$value);
  2022. }
  2023. elseif($data!==null)
  2024. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  2025. }
  2026. public function mergeWith($data,$recursive=true)
  2027. {
  2028. if(is_array($data) || $data instanceof Traversable)
  2029. {
  2030. if($data instanceof CMap)
  2031. $data=$data->_d;
  2032. if($recursive)
  2033. {
  2034. if($data instanceof Traversable)
  2035. {
  2036. $d=array();
  2037. foreach($data as $key=>$value)
  2038. $d[$key]=$value;
  2039. $this->_d=self::mergeArray($this->_d,$d);
  2040. }
  2041. else
  2042. $this->_d=self::mergeArray($this->_d,$data);
  2043. }
  2044. else
  2045. {
  2046. foreach($data as $key=>$value)
  2047. $this->add($key,$value);
  2048. }
  2049. }
  2050. elseif($data!==null)
  2051. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  2052. }
  2053. public static function mergeArray($a,$b)
  2054. {
  2055. $args=func_get_args();
  2056. $res=array_shift($args);
  2057. while(!empty($args))
  2058. {
  2059. $next=array_shift($args);
  2060. foreach($next as $k => $v)
  2061. {
  2062. if(is_integer($k))
  2063. isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
  2064. elseif(is_array($v) && isset($res[$k]) && is_array($res[$k]))
  2065. $res[$k]=self::mergeArray($res[$k],$v);
  2066. else
  2067. $res[$k]=$v;
  2068. }
  2069. }
  2070. return $res;
  2071. }
  2072. public function offsetExists($offset)
  2073. {
  2074. return $this->contains($offset);
  2075. }
  2076. public function offsetGet($offset)
  2077. {
  2078. return $this->itemAt($offset);
  2079. }
  2080. public function offsetSet($offset,$item)
  2081. {
  2082. $this->add($offset,$item);
  2083. }
  2084. public function offsetUnset($offset)
  2085. {
  2086. $this->remove($offset);
  2087. }
  2088. }
  2089. class CLogger extends CComponent
  2090. {
  2091. const LEVEL_TRACE='trace';
  2092. const LEVEL_WARNING='warning';
  2093. const LEVEL_ERROR='error';
  2094. const LEVEL_INFO='info';
  2095. const LEVEL_PROFILE='profile';
  2096. public $autoFlush=10000;
  2097. public $autoDump=false;
  2098. private $_logs=array();
  2099. private $_logCount=0;
  2100. private $_levels;
  2101. private $_categories;
  2102. private $_except=array();
  2103. private $_timings;
  2104. private $_processing=false;
  2105. public function log($message,$level='info',$category='application')
  2106. {
  2107. $this->_logs[]=array($message,$level,$category,microtime(true));
  2108. $this->_logCount++;
  2109. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
  2110. {
  2111. $this->_processing=true;
  2112. $this->flush($this->autoDump);
  2113. $this->_processing=false;
  2114. }
  2115. }
  2116. public function getLogs($levels='',$categories=array(), $except=array())
  2117. {
  2118. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2119. if (is_string($categories))
  2120. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2121. else
  2122. $this->_categories=array_filter(array_map('strtolower',$categories));
  2123. if (is_string($except))
  2124. $this->_except=preg_split('/[\s,]+/',strtolower($except),-1,PREG_SPLIT_NO_EMPTY);
  2125. else
  2126. $this->_except=array_filter(array_map('strtolower',$except));
  2127. $ret=$this->_logs;
  2128. if(!empty($levels))
  2129. $ret=array_values(array_filter($ret,array($this,'filterByLevel')));
  2130. if(!empty($this->_categories) || !empty($this->_except))
  2131. $ret=array_values(array_filter($ret,array($this,'filterByCategory')));
  2132. return $ret;
  2133. }
  2134. private function filterByCategory($value)
  2135. {
  2136. return $this->filterAllCategories($value, 2);
  2137. }
  2138. private function filterTimingByCategory($value)
  2139. {
  2140. return $this->filterAllCategories($value, 1);
  2141. }
  2142. private function filterAllCategories($value, $index)
  2143. {
  2144. $cat=strtolower($value[$index]);
  2145. $ret=empty($this->_categories);
  2146. foreach($this->_categories as $category)
  2147. {
  2148. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2149. $ret=true;
  2150. }
  2151. if($ret)
  2152. {
  2153. foreach($this->_except as $category)
  2154. {
  2155. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2156. $ret=false;
  2157. }
  2158. }
  2159. return $ret;
  2160. }
  2161. private function filterByLevel($value)
  2162. {
  2163. return in_array(strtolower($value[1]),$this->_levels);
  2164. }
  2165. public function getExecutionTime()
  2166. {
  2167. return microtime(true)-YII_BEGIN_TIME;
  2168. }
  2169. public function getMemoryUsage()
  2170. {
  2171. if(function_exists('memory_get_usage'))
  2172. return memory_get_usage();
  2173. else
  2174. {
  2175. $output=array();
  2176. if(strncmp(PHP_OS,'WIN',3)===0)
  2177. {
  2178. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2179. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2180. }
  2181. else
  2182. {
  2183. $pid=getmypid();
  2184. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2185. $output=explode(" ",$output[0]);
  2186. return isset($output[1]) ? $output[1]*1024 : 0;
  2187. }
  2188. }
  2189. }
  2190. public function getProfilingResults($token=null,$categories=null,$refresh=false)
  2191. {
  2192. if($this->_timings===null || $refresh)
  2193. $this->calculateTimings();
  2194. if($token===null && $categories===null)
  2195. return $this->_timings;
  2196. $timings = $this->_timings;
  2197. if($categories!==null) {
  2198. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2199. $timings=array_filter($timings,array($this,'filterTimingByCategory'));
  2200. }
  2201. $results=array();
  2202. foreach($timings as $timing)
  2203. {
  2204. if($token===null || $timing[0]===$token)
  2205. $results[]=$timing[2];
  2206. }
  2207. return $results;
  2208. }
  2209. private function calculateTimings()
  2210. {
  2211. $this->_timings=array();
  2212. $stack=array();
  2213. foreach($this->_logs as $log)
  2214. {
  2215. if($log[1]!==CLogger::LEVEL_PROFILE)
  2216. continue;
  2217. list($message,$level,$category,$timestamp)=$log;
  2218. if(!strncasecmp($message,'begin:',6))
  2219. {
  2220. $log[0]=substr($message,6);
  2221. $stack[]=$log;
  2222. }
  2223. elseif(!strncasecmp($message,'end:',4))
  2224. {
  2225. $token=substr($message,4);
  2226. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2227. {
  2228. $delta=$log[3]-$last[3];
  2229. $this->_timings[]=array($message,$category,$delta);
  2230. }
  2231. else
  2232. 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.',
  2233. array('{token}'=>$token)));
  2234. }
  2235. }
  2236. $now=microtime(true);
  2237. while(($last=array_pop($stack))!==null)
  2238. {
  2239. $delta=$now-$last[3];
  2240. $this->_timings[]=array($last[0],$last[2],$delta);
  2241. }
  2242. }
  2243. public function flush($dumpLogs=false)
  2244. {
  2245. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2246. $this->_logs=array();
  2247. $this->_logCount=0;
  2248. }
  2249. public function onFlush($event)
  2250. {
  2251. $this->raiseEvent('onFlush', $event);
  2252. }
  2253. }
  2254. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2255. {
  2256. public $behaviors=array();
  2257. private $_initialized=false;
  2258. public function init()
  2259. {
  2260. $this->attachBehaviors($this->behaviors);
  2261. $this->_initialized=true;
  2262. }
  2263. public function getIsInitialized()
  2264. {
  2265. return $this->_initialized;
  2266. }
  2267. }
  2268. class CHttpRequest extends CApplicationComponent
  2269. {
  2270. public $jsonAsArray = true;
  2271. public $enableCookieValidation=false;
  2272. public $enableCsrfValidation=false;
  2273. public $csrfTokenName='YII_CSRF_TOKEN';
  2274. public $csrfCookie;
  2275. private $_requestUri;
  2276. private $_pathInfo;
  2277. private $_scriptFile;
  2278. private $_scriptUrl;
  2279. private $_hostInfo;
  2280. private $_baseUrl;
  2281. private $_cookies;
  2282. private $_preferredAcceptTypes;
  2283. private $_preferredLanguages;
  2284. private $_csrfToken;
  2285. private $_restParams;
  2286. private $_httpVersion;
  2287. public function init()
  2288. {
  2289. parent::init();
  2290. $this->normalizeRequest();
  2291. }
  2292. protected function normalizeRequest()
  2293. {
  2294. // normalize request
  2295. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2296. {
  2297. if(isset($_GET))
  2298. $_GET=$this->stripSlashes($_GET);
  2299. if(isset($_POST))
  2300. $_POST=$this->stripSlashes($_POST);
  2301. if(isset($_REQUEST))
  2302. $_REQUEST=$this->stripSlashes($_REQUEST);
  2303. if(isset($_COOKIE))
  2304. $_COOKIE=$this->stripSlashes($_COOKIE);
  2305. }
  2306. if($this->enableCsrfValidation)
  2307. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2308. }
  2309. public function stripSlashes(&$data)
  2310. {
  2311. if(is_array($data))
  2312. {
  2313. if(count($data) == 0)
  2314. return $data;
  2315. $keys=array_map('stripslashes',array_keys($data));
  2316. $data=array_combine($keys,array_values($data));
  2317. return array_map(array($this,'stripSlashes'),$data);
  2318. }
  2319. else
  2320. return stripslashes($data);
  2321. }
  2322. public function getParam($name,$defaultValue=null)
  2323. {
  2324. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2325. }
  2326. public function getQuery($name,$defaultValue=null)
  2327. {
  2328. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2329. }
  2330. public function getPost($name,$defaultValue=null)
  2331. {
  2332. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2333. }
  2334. public function getDelete($name,$defaultValue=null)
  2335. {
  2336. if($this->getIsDeleteViaPostRequest())
  2337. return $this->getPost($name, $defaultValue);
  2338. if($this->getIsDeleteRequest())
  2339. {
  2340. $restParams=$this->getRestParams();
  2341. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2342. }
  2343. else
  2344. return $defaultValue;
  2345. }
  2346. public function getPut($name,$defaultValue=null)
  2347. {
  2348. if($this->getIsPutViaPostRequest())
  2349. return $this->getPost($name, $defaultValue);
  2350. if($this->getIsPutRequest())
  2351. {
  2352. $restParams=$this->getRestParams();
  2353. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2354. }
  2355. else
  2356. return $defaultValue;
  2357. }
  2358. public function getPatch($name,$defaultValue=null)
  2359. {
  2360. if($this->getIsPatchViaPostRequest())
  2361. return $this->getPost($name, $defaultValue);
  2362. if($this->getIsPatchRequest())
  2363. {
  2364. $restParams=$this->getRestParams();
  2365. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2366. }
  2367. else
  2368. return $defaultValue;
  2369. }
  2370. public function getRestParams()
  2371. {
  2372. if($this->_restParams===null)
  2373. {
  2374. $result=array();
  2375. if (strncmp($this->getContentType(), 'application/json', 16) === 0)
  2376. $result = CJSON::decode($this->getRawBody(), $this->jsonAsArray);
  2377. elseif(function_exists('mb_parse_str'))
  2378. mb_parse_str($this->getRawBody(), $result);
  2379. else
  2380. parse_str($this->getRawBody(), $result);
  2381. $this->_restParams=$result;
  2382. }
  2383. return $this->_restParams;
  2384. }
  2385. public function getRawBody()
  2386. {
  2387. static $rawBody;
  2388. if($rawBody===null)
  2389. $rawBody=file_get_contents('php://input');
  2390. return $rawBody;
  2391. }
  2392. public function getUrl()
  2393. {
  2394. return $this->getRequestUri();
  2395. }
  2396. public function getHostInfo($schema='')
  2397. {
  2398. if($this->_hostInfo===null)
  2399. {
  2400. if($secure=$this->getIsSecureConnection())
  2401. $http='https';
  2402. else
  2403. $http='http';
  2404. if(isset($_SERVER['HTTP_HOST']))
  2405. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2406. else
  2407. {
  2408. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2409. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2410. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2411. $this->_hostInfo.=':'.$port;
  2412. }
  2413. }
  2414. if($schema!=='')
  2415. {
  2416. $secure=$this->getIsSecureConnection();
  2417. if($secure && $schema==='https' || !$secure && $schema==='http')
  2418. return $this->_hostInfo;
  2419. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2420. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2421. $port=':'.$port;
  2422. else
  2423. $port='';
  2424. $pos=strpos($this->_hostInfo,':');
  2425. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2426. }
  2427. else
  2428. return $this->_hostInfo;
  2429. }
  2430. public function setHostInfo($value)
  2431. {
  2432. $this->_hostInfo=rtrim($value,'/');
  2433. }
  2434. public function getBaseUrl($absolute=false)
  2435. {
  2436. if($this->_baseUrl===null)
  2437. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2438. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2439. }
  2440. public function setBaseUrl($value)
  2441. {
  2442. $this->_baseUrl=$value;
  2443. }
  2444. public function getScriptUrl()
  2445. {
  2446. if($this->_scriptUrl===null)
  2447. {
  2448. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2449. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2450. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2451. elseif(basename($_SERVER['PHP_SELF'])===$scriptName)
  2452. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2453. elseif(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2454. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2455. elseif(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2456. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2457. elseif(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2458. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2459. else
  2460. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2461. }
  2462. return $this->_scriptUrl;
  2463. }
  2464. public function setScriptUrl($value)
  2465. {
  2466. $this->_scriptUrl='/'.trim($value,'/');
  2467. }
  2468. public function getPathInfo()
  2469. {
  2470. if($this->_pathInfo===null)
  2471. {
  2472. $pathInfo=$this->getRequestUri();
  2473. if(($pos=strpos($pathInfo,'?'))!==false)
  2474. $pathInfo=substr($pathInfo,0,$pos);
  2475. $pathInfo=$this->decodePathInfo($pathInfo);
  2476. $scriptUrl=$this->getScriptUrl();
  2477. $baseUrl=$this->getBaseUrl();
  2478. if(strpos($pathInfo,$scriptUrl)===0)
  2479. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2480. elseif($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2481. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2482. elseif(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2483. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2484. else
  2485. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2486. if($pathInfo==='/' || $pathInfo===false)
  2487. $pathInfo='';
  2488. elseif($pathInfo!=='' && $pathInfo[0]==='/')
  2489. $pathInfo=substr($pathInfo,1);
  2490. if(($posEnd=strlen($pathInfo)-1)>0 && $pathInfo[$posEnd]==='/')
  2491. $pathInfo=substr($pathInfo,0,$posEnd);
  2492. $this->_pathInfo=$pathInfo;
  2493. }
  2494. return $this->_pathInfo;
  2495. }
  2496. protected function decodePathInfo($pathInfo)
  2497. {
  2498. $pathInfo = urldecode($pathInfo);
  2499. // is it UTF-8?
  2500. // http://w3.org/International/questions/qa-forms-utf-8.html
  2501. if(preg_match('%^(?:
  2502. [\x09\x0A\x0D\x20-\x7E] # ASCII
  2503. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  2504. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  2505. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  2506. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  2507. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  2508. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  2509. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  2510. )*$%xs', $pathInfo))
  2511. {
  2512. return $pathInfo;
  2513. }
  2514. else
  2515. {
  2516. return utf8_encode($pathInfo);
  2517. }
  2518. }
  2519. public function getRequestUri()
  2520. {
  2521. if($this->_requestUri===null)
  2522. {
  2523. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2524. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2525. elseif(isset($_SERVER['REQUEST_URI']))
  2526. {
  2527. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2528. if(!empty($_SERVER['HTTP_HOST']))
  2529. {
  2530. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2531. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2532. }
  2533. else
  2534. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2535. }
  2536. elseif(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2537. {
  2538. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2539. if(!empty($_SERVER['QUERY_STRING']))
  2540. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2541. }
  2542. else
  2543. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2544. }
  2545. return $this->_requestUri;
  2546. }
  2547. public function getQueryString()
  2548. {
  2549. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2550. }
  2551. public function getIsSecureConnection()
  2552. {
  2553. return isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'],'on')===0 || $_SERVER['HTTPS']==1)
  2554. || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'],'https')===0;
  2555. }
  2556. public function getRequestType()
  2557. {
  2558. if(isset($_POST['_method']))
  2559. return strtoupper($_POST['_method']);
  2560. elseif(isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']))
  2561. return strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
  2562. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2563. }
  2564. public function getIsPostRequest()
  2565. {
  2566. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2567. }
  2568. public function getIsDeleteRequest()
  2569. {
  2570. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE')) || $this->getIsDeleteViaPostRequest();
  2571. }
  2572. protected function getIsDeleteViaPostRequest()
  2573. {
  2574. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'DELETE');
  2575. }
  2576. public function getIsPutRequest()
  2577. {
  2578. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT')) || $this->getIsPutViaPostRequest();
  2579. }
  2580. protected function getIsPutViaPostRequest()
  2581. {
  2582. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PUT');
  2583. }
  2584. public function getIsPatchRequest()
  2585. {
  2586. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PATCH')) || $this->getIsPatchViaPostRequest();
  2587. }
  2588. protected function getIsPatchViaPostRequest()
  2589. {
  2590. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PATCH');
  2591. }
  2592. public function getIsAjaxRequest()
  2593. {
  2594. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2595. }
  2596. public function getIsFlashRequest()
  2597. {
  2598. return isset($_SERVER['HTTP_USER_AGENT']) && (stripos($_SERVER['HTTP_USER_AGENT'],'Shockwave')!==false || stripos($_SERVER['HTTP_USER_AGENT'],'Flash')!==false);
  2599. }
  2600. public function getServerName()
  2601. {
  2602. return $_SERVER['SERVER_NAME'];
  2603. }
  2604. public function getServerPort()
  2605. {
  2606. return $_SERVER['SERVER_PORT'];
  2607. }
  2608. public function getUrlReferrer()
  2609. {
  2610. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2611. }
  2612. public function getUserAgent()
  2613. {
  2614. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2615. }
  2616. public function getUserHostAddress()
  2617. {
  2618. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2619. }
  2620. public function getUserHost()
  2621. {
  2622. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2623. }
  2624. public function getScriptFile()
  2625. {
  2626. if($this->_scriptFile!==null)
  2627. return $this->_scriptFile;
  2628. else
  2629. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2630. }
  2631. public function getBrowser($userAgent=null)
  2632. {
  2633. return get_browser($userAgent,true);
  2634. }
  2635. public function getAcceptTypes()
  2636. {
  2637. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2638. }
  2639. public function getContentType()
  2640. {
  2641. if (isset($_SERVER["CONTENT_TYPE"])) {
  2642. return $_SERVER["CONTENT_TYPE"];
  2643. } elseif (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
  2644. //fix bug https://bugs.php.net/bug.php?id=66606
  2645. return $_SERVER["HTTP_CONTENT_TYPE"];
  2646. }
  2647. return null;
  2648. }
  2649. private $_port;
  2650. public function getPort()
  2651. {
  2652. if($this->_port===null)
  2653. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2654. return $this->_port;
  2655. }
  2656. public function setPort($value)
  2657. {
  2658. $this->_port=(int)$value;
  2659. $this->_hostInfo=null;
  2660. }
  2661. private $_securePort;
  2662. public function getSecurePort()
  2663. {
  2664. if($this->_securePort===null)
  2665. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2666. return $this->_securePort;
  2667. }
  2668. public function setSecurePort($value)
  2669. {
  2670. $this->_securePort=(int)$value;
  2671. $this->_hostInfo=null;
  2672. }
  2673. public function getCookies()
  2674. {
  2675. if($this->_cookies!==null)
  2676. return $this->_cookies;
  2677. else
  2678. return $this->_cookies=new CCookieCollection($this);
  2679. }
  2680. public function redirect($url,$terminate=true,$statusCode=302)
  2681. {
  2682. if(strpos($url,'/')===0 && strpos($url,'//')!==0)
  2683. $url=$this->getHostInfo().$url;
  2684. header('Location: '.$url, true, $statusCode);
  2685. if($terminate)
  2686. Yii::app()->end();
  2687. }
  2688. public static function parseAcceptHeader($header)
  2689. {
  2690. $matches=array();
  2691. $accepts=array();
  2692. // get individual entries with their type, subtype, basetype and params
  2693. preg_match_all('/(?:\G\s?,\s?|^)(\w+|\*)\/(\w+|\*)(?:\+(\w+))?|(?<!^)\G(?:\s?;\s?(\w+)=([\w\.]+))/',$header,$matches);
  2694. // the regexp should (in theory) always return an array of 6 arrays
  2695. if(count($matches)===6)
  2696. {
  2697. $i=0;
  2698. $itemLen=count($matches[1]);
  2699. while($i<$itemLen)
  2700. {
  2701. // fill out a content type
  2702. $accept=array(
  2703. 'type'=>$matches[1][$i],
  2704. 'subType'=>$matches[2][$i],
  2705. 'baseType'=>null,
  2706. 'params'=>array(),
  2707. );
  2708. // fill in the base type if it exists
  2709. if($matches[3][$i]!==null && $matches[3][$i]!=='')
  2710. $accept['baseType']=$matches[3][$i];
  2711. // continue looping while there is no new content type, to fill in all accompanying params
  2712. for($i++;$i<$itemLen;$i++)
  2713. {
  2714. // if the next content type is null, then the item is a param for the current content type
  2715. if($matches[1][$i]===null || $matches[1][$i]==='')
  2716. {
  2717. // if this is the quality param, convert it to a double
  2718. if($matches[4][$i]==='q')
  2719. {
  2720. // sanity check on q value
  2721. $q=(double)$matches[5][$i];
  2722. if($q>1)
  2723. $q=(double)1;
  2724. elseif($q<0)
  2725. $q=(double)0;
  2726. $accept['params'][$matches[4][$i]]=$q;
  2727. }
  2728. else
  2729. $accept['params'][$matches[4][$i]]=$matches[5][$i];
  2730. }
  2731. else
  2732. break;
  2733. }
  2734. // q defaults to 1 if not explicitly given
  2735. if(!isset($accept['params']['q']))
  2736. $accept['params']['q']=(double)1;
  2737. $accepts[] = $accept;
  2738. }
  2739. }
  2740. return $accepts;
  2741. }
  2742. public static function compareAcceptTypes($a,$b)
  2743. {
  2744. // check for equal quality first
  2745. if($a['params']['q']===$b['params']['q'])
  2746. if(!($a['type']==='*' xor $b['type']==='*'))
  2747. if (!($a['subType']==='*' xor $b['subType']==='*'))
  2748. // finally, higher number of parameters counts as greater precedence
  2749. if(count($a['params'])===count($b['params']))
  2750. return 0;
  2751. else
  2752. return count($a['params'])<count($b['params']) ? 1 : -1;
  2753. // more specific takes precedence - whichever one doesn't have a * subType
  2754. else
  2755. return $a['subType']==='*' ? 1 : -1;
  2756. // more specific takes precedence - whichever one doesn't have a * type
  2757. else
  2758. return $a['type']==='*' ? 1 : -1;
  2759. else
  2760. return ($a['params']['q']<$b['params']['q']) ? 1 : -1;
  2761. }
  2762. public function getPreferredAcceptTypes()
  2763. {
  2764. if($this->_preferredAcceptTypes===null)
  2765. {
  2766. $accepts=self::parseAcceptHeader($this->getAcceptTypes());
  2767. usort($accepts,array(get_class($this),'compareAcceptTypes'));
  2768. $this->_preferredAcceptTypes=$accepts;
  2769. }
  2770. return $this->_preferredAcceptTypes;
  2771. }
  2772. public function getPreferredAcceptType()
  2773. {
  2774. $preferredAcceptTypes=$this->getPreferredAcceptTypes();
  2775. return empty($preferredAcceptTypes) ? false : $preferredAcceptTypes[0];
  2776. }
  2777. public function getPreferredLanguages()
  2778. {
  2779. if($this->_preferredLanguages===null)
  2780. {
  2781. $sortedLanguages=array();
  2782. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $n=preg_match_all('/([\w\-_]+)(?:\s*;\s*q\s*=\s*(\d*\.?\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))
  2783. {
  2784. $languages=array();
  2785. for($i=0;$i<$n;++$i)
  2786. {
  2787. $q=$matches[2][$i];
  2788. if($q==='')
  2789. $q=1;
  2790. if($q)
  2791. $languages[]=array((float)$q,$matches[1][$i]);
  2792. }
  2793. usort($languages,create_function('$a,$b','if($a[0]==$b[0]) {return 0;} return ($a[0]<$b[0]) ? 1 : -1;'));
  2794. foreach($languages as $language)
  2795. $sortedLanguages[]=$language[1];
  2796. }
  2797. $this->_preferredLanguages=$sortedLanguages;
  2798. }
  2799. return $this->_preferredLanguages;
  2800. }
  2801. public function getPreferredLanguage($languages=array())
  2802. {
  2803. $preferredLanguages=$this->getPreferredLanguages();
  2804. if(empty($languages)) {
  2805. return !empty($preferredLanguages) ? CLocale::getCanonicalID($preferredLanguages[0]) : false;
  2806. }
  2807. foreach ($preferredLanguages as $preferredLanguage) {
  2808. $preferredLanguage=CLocale::getCanonicalID($preferredLanguage);
  2809. foreach ($languages as $language) {
  2810. $language=CLocale::getCanonicalID($language);
  2811. // en_us==en_us, en==en_us, en_us==en
  2812. if($language===$preferredLanguage || strpos($preferredLanguage,$language.'_')===0 || strpos($language,$preferredLanguage.'_')===0) {
  2813. return $language;
  2814. }
  2815. }
  2816. }
  2817. return reset($languages);
  2818. }
  2819. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2820. {
  2821. if($mimeType===null)
  2822. {
  2823. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2824. $mimeType='text/plain';
  2825. }
  2826. $fileSize=(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content));
  2827. $contentStart=0;
  2828. $contentEnd=$fileSize-1;
  2829. $httpVersion=$this->getHttpVersion();
  2830. if(isset($_SERVER['HTTP_RANGE']))
  2831. {
  2832. header('Accept-Ranges: bytes');
  2833. //client sent us a multibyte range, can not hold this one for now
  2834. if(strpos($_SERVER['HTTP_RANGE'],',')!==false)
  2835. {
  2836. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2837. throw new CHttpException(416,'Requested Range Not Satisfiable');
  2838. }
  2839. $range=str_replace('bytes=','',$_SERVER['HTTP_RANGE']);
  2840. //range requests starts from "-", so it means that data must be dumped the end point.
  2841. if($range[0]==='-')
  2842. $contentStart=$fileSize-substr($range,1);
  2843. else
  2844. {
  2845. $range=explode('-',$range);
  2846. $contentStart=$range[0];
  2847. // check if the last-byte-pos presents in header
  2848. if((isset($range[1]) && is_numeric($range[1])))
  2849. $contentEnd=$range[1];
  2850. }
  2851. /* Check the range and make sure it's treated according to the specs.
  2852. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  2853. */
  2854. // End bytes can not be larger than $end.
  2855. $contentEnd=($contentEnd > $fileSize) ? $fileSize-1 : $contentEnd;
  2856. // Validate the requested range and return an error if it's not correct.
  2857. $wrongContentStart=($contentStart>$contentEnd || $contentStart>$fileSize-1 || $contentStart<0);
  2858. if($wrongContentStart)
  2859. {
  2860. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2861. throw new CHttpException(416,'Requested Range Not Satisfiable');
  2862. }
  2863. header("HTTP/$httpVersion 206 Partial Content");
  2864. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2865. }
  2866. else
  2867. header("HTTP/$httpVersion 200 OK");
  2868. $length=$contentEnd-$contentStart+1; // Calculate new content length
  2869. header('Pragma: public');
  2870. header('Expires: 0');
  2871. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2872. header("Content-Type: $mimeType");
  2873. header('Content-Length: '.$length);
  2874. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2875. header('Content-Transfer-Encoding: binary');
  2876. $content=function_exists('mb_substr') ? mb_substr($content,$contentStart,$length,'8bit') : substr($content,$contentStart,$length);
  2877. if($terminate)
  2878. {
  2879. // clean up the application first because the file downloading could take long time
  2880. // which may cause timeout of some resources (such as DB connection)
  2881. ob_start();
  2882. Yii::app()->end(0,false);
  2883. ob_end_clean();
  2884. echo $content;
  2885. exit(0);
  2886. }
  2887. else
  2888. echo $content;
  2889. }
  2890. public function xSendFile($filePath, $options=array())
  2891. {
  2892. if(!isset($options['forceDownload']) || $options['forceDownload'])
  2893. $disposition='attachment';
  2894. else
  2895. $disposition='inline';
  2896. if(!isset($options['saveName']))
  2897. $options['saveName']=basename($filePath);
  2898. if(!isset($options['mimeType']))
  2899. {
  2900. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2901. $options['mimeType']='text/plain';
  2902. }
  2903. if(!isset($options['xHeader']))
  2904. $options['xHeader']='X-Sendfile';
  2905. if($options['mimeType']!==null)
  2906. header('Content-Type: '.$options['mimeType']);
  2907. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  2908. if(isset($options['addHeaders']))
  2909. {
  2910. foreach($options['addHeaders'] as $header=>$value)
  2911. header($header.': '.$value);
  2912. }
  2913. header(trim($options['xHeader']).': '.$filePath);
  2914. if(!isset($options['terminate']) || $options['terminate'])
  2915. Yii::app()->end();
  2916. }
  2917. public function getCsrfToken()
  2918. {
  2919. if($this->_csrfToken===null)
  2920. {
  2921. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2922. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2923. {
  2924. $cookie=$this->createCsrfCookie();
  2925. $this->_csrfToken=$cookie->value;
  2926. $this->getCookies()->add($cookie->name,$cookie);
  2927. }
  2928. }
  2929. return $this->_csrfToken;
  2930. }
  2931. protected function createCsrfCookie()
  2932. {
  2933. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2934. if(is_array($this->csrfCookie))
  2935. {
  2936. foreach($this->csrfCookie as $name=>$value)
  2937. $cookie->$name=$value;
  2938. }
  2939. return $cookie;
  2940. }
  2941. public function validateCsrfToken($event)
  2942. {
  2943. if ($this->getIsPostRequest() ||
  2944. $this->getIsPutRequest() ||
  2945. $this->getIsPatchRequest() ||
  2946. $this->getIsDeleteRequest())
  2947. {
  2948. $cookies=$this->getCookies();
  2949. $method=$this->getRequestType();
  2950. switch($method)
  2951. {
  2952. case 'POST':
  2953. $userToken=$this->getPost($this->csrfTokenName);
  2954. break;
  2955. case 'PUT':
  2956. $userToken=$this->getPut($this->csrfTokenName);
  2957. break;
  2958. case 'PATCH':
  2959. $userToken=$this->getPatch($this->csrfTokenName);
  2960. break;
  2961. case 'DELETE':
  2962. $userToken=$this->getDelete($this->csrfTokenName);
  2963. }
  2964. if (!empty($userToken) && $cookies->contains($this->csrfTokenName))
  2965. {
  2966. $cookieToken=$cookies->itemAt($this->csrfTokenName)->value;
  2967. $valid=$cookieToken===$userToken;
  2968. }
  2969. else
  2970. $valid = false;
  2971. if (!$valid)
  2972. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2973. }
  2974. }
  2975. public function getHttpVersion()
  2976. {
  2977. if($this->_httpVersion===null)
  2978. {
  2979. if(isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL']==='HTTP/1.0')
  2980. $this->_httpVersion='1.0';
  2981. else
  2982. $this->_httpVersion='1.1';
  2983. }
  2984. return $this->_httpVersion;
  2985. }
  2986. }
  2987. class CCookieCollection extends CMap
  2988. {
  2989. private $_request;
  2990. private $_initialized=false;
  2991. public function __construct(CHttpRequest $request)
  2992. {
  2993. $this->_request=$request;
  2994. $this->copyfrom($this->getCookies());
  2995. $this->_initialized=true;
  2996. }
  2997. public function getRequest()
  2998. {
  2999. return $this->_request;
  3000. }
  3001. protected function getCookies()
  3002. {
  3003. $cookies=array();
  3004. if($this->_request->enableCookieValidation)
  3005. {
  3006. $sm=Yii::app()->getSecurityManager();
  3007. foreach($_COOKIE as $name=>$value)
  3008. {
  3009. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  3010. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  3011. }
  3012. }
  3013. else
  3014. {
  3015. foreach($_COOKIE as $name=>$value)
  3016. $cookies[$name]=new CHttpCookie($name,$value);
  3017. }
  3018. return $cookies;
  3019. }
  3020. public function add($name,$cookie)
  3021. {
  3022. if($cookie instanceof CHttpCookie)
  3023. {
  3024. $this->remove($name);
  3025. parent::add($name,$cookie);
  3026. if($this->_initialized)
  3027. $this->addCookie($cookie);
  3028. }
  3029. else
  3030. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  3031. }
  3032. public function remove($name,$options=array())
  3033. {
  3034. if(($cookie=parent::remove($name))!==null)
  3035. {
  3036. if($this->_initialized)
  3037. {
  3038. $cookie->configure($options);
  3039. $this->removeCookie($cookie);
  3040. }
  3041. }
  3042. return $cookie;
  3043. }
  3044. protected function addCookie($cookie)
  3045. {
  3046. $value=$cookie->value;
  3047. if($this->_request->enableCookieValidation)
  3048. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  3049. if(version_compare(PHP_VERSION,'5.2.0','>='))
  3050. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  3051. else
  3052. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  3053. }
  3054. protected function removeCookie($cookie)
  3055. {
  3056. if(version_compare(PHP_VERSION,'5.2.0','>='))
  3057. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  3058. else
  3059. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure);
  3060. }
  3061. }
  3062. class CUrlManager extends CApplicationComponent
  3063. {
  3064. const CACHE_KEY='Yii.CUrlManager.rules';
  3065. const GET_FORMAT='get';
  3066. const PATH_FORMAT='path';
  3067. public $rules=array();
  3068. public $urlSuffix='';
  3069. public $showScriptName=true;
  3070. public $appendParams=true;
  3071. public $routeVar='r';
  3072. public $caseSensitive=true;
  3073. public $matchValue=false;
  3074. public $cacheID='cache';
  3075. public $useStrictParsing=false;
  3076. public $urlRuleClass='CUrlRule';
  3077. private $_urlFormat=self::GET_FORMAT;
  3078. private $_rules=array();
  3079. private $_baseUrl;
  3080. public function init()
  3081. {
  3082. parent::init();
  3083. $this->processRules();
  3084. }
  3085. protected function processRules()
  3086. {
  3087. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  3088. return;
  3089. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  3090. {
  3091. $hash=md5(serialize($this->rules));
  3092. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  3093. {
  3094. $this->_rules=$data[0];
  3095. return;
  3096. }
  3097. }
  3098. foreach($this->rules as $pattern=>$route)
  3099. $this->_rules[]=$this->createUrlRule($route,$pattern);
  3100. if(isset($cache))
  3101. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  3102. }
  3103. public function addRules($rules,$append=true)
  3104. {
  3105. if ($append)
  3106. {
  3107. foreach($rules as $pattern=>$route)
  3108. $this->_rules[]=$this->createUrlRule($route,$pattern);
  3109. }
  3110. else
  3111. {
  3112. $rules=array_reverse($rules);
  3113. foreach($rules as $pattern=>$route)
  3114. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  3115. }
  3116. }
  3117. protected function createUrlRule($route,$pattern)
  3118. {
  3119. if(is_array($route) && isset($route['class']))
  3120. return $route;
  3121. else
  3122. {
  3123. $urlRuleClass=Yii::import($this->urlRuleClass,true);
  3124. return new $urlRuleClass($route,$pattern);
  3125. }
  3126. }
  3127. public function createUrl($route,$params=array(),$ampersand='&')
  3128. {
  3129. unset($params[$this->routeVar]);
  3130. foreach($params as $i=>$param)
  3131. if($param===null)
  3132. $params[$i]='';
  3133. if(isset($params['#']))
  3134. {
  3135. $anchor='#'.$params['#'];
  3136. unset($params['#']);
  3137. }
  3138. else
  3139. $anchor='';
  3140. $route=trim($route,'/');
  3141. foreach($this->_rules as $i=>$rule)
  3142. {
  3143. if(is_array($rule))
  3144. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  3145. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  3146. {
  3147. if($rule->hasHostInfo)
  3148. return $url==='' ? '/'.$anchor : $url.$anchor;
  3149. else
  3150. return $this->getBaseUrl().'/'.$url.$anchor;
  3151. }
  3152. }
  3153. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  3154. }
  3155. protected function createUrlDefault($route,$params,$ampersand)
  3156. {
  3157. if($this->getUrlFormat()===self::PATH_FORMAT)
  3158. {
  3159. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  3160. if($this->appendParams)
  3161. {
  3162. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  3163. return $route==='' ? $url : $url.$this->urlSuffix;
  3164. }
  3165. else
  3166. {
  3167. if($route!=='')
  3168. $url.=$this->urlSuffix;
  3169. $query=$this->createPathInfo($params,'=',$ampersand);
  3170. return $query==='' ? $url : $url.'?'.$query;
  3171. }
  3172. }
  3173. else
  3174. {
  3175. $url=$this->getBaseUrl();
  3176. if(!$this->showScriptName)
  3177. $url.='/';
  3178. if($route!=='')
  3179. {
  3180. $url.='?'.$this->routeVar.'='.$route;
  3181. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  3182. $url.=$ampersand.$query;
  3183. }
  3184. elseif(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  3185. $url.='?'.$query;
  3186. return $url;
  3187. }
  3188. }
  3189. public function parseUrl($request)
  3190. {
  3191. if($this->getUrlFormat()===self::PATH_FORMAT)
  3192. {
  3193. $rawPathInfo=$request->getPathInfo();
  3194. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3195. foreach($this->_rules as $i=>$rule)
  3196. {
  3197. if(is_array($rule))
  3198. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  3199. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  3200. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  3201. }
  3202. if($this->useStrictParsing)
  3203. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  3204. array('{route}'=>$pathInfo)));
  3205. else
  3206. return $pathInfo;
  3207. }
  3208. elseif(isset($_GET[$this->routeVar]))
  3209. return $_GET[$this->routeVar];
  3210. elseif(isset($_POST[$this->routeVar]))
  3211. return $_POST[$this->routeVar];
  3212. else
  3213. return '';
  3214. }
  3215. public function parsePathInfo($pathInfo)
  3216. {
  3217. if($pathInfo==='')
  3218. return;
  3219. $segs=explode('/',$pathInfo.'/');
  3220. $n=count($segs);
  3221. for($i=0;$i<$n-1;$i+=2)
  3222. {
  3223. $key=$segs[$i];
  3224. if($key==='') continue;
  3225. $value=$segs[$i+1];
  3226. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  3227. {
  3228. $name=substr($key,0,$pos);
  3229. for($j=$m-1;$j>=0;--$j)
  3230. {
  3231. if($matches[1][$j]==='')
  3232. $value=array($value);
  3233. else
  3234. $value=array($matches[1][$j]=>$value);
  3235. }
  3236. if(isset($_GET[$name]) && is_array($_GET[$name]))
  3237. $value=CMap::mergeArray($_GET[$name],$value);
  3238. $_REQUEST[$name]=$_GET[$name]=$value;
  3239. }
  3240. else
  3241. $_REQUEST[$key]=$_GET[$key]=$value;
  3242. }
  3243. }
  3244. public function createPathInfo($params,$equal,$ampersand, $key=null)
  3245. {
  3246. $pairs = array();
  3247. foreach($params as $k => $v)
  3248. {
  3249. if ($key!==null)
  3250. $k = $key.'['.$k.']';
  3251. if (is_array($v))
  3252. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  3253. else
  3254. $pairs[]=urlencode($k).$equal.urlencode($v);
  3255. }
  3256. return implode($ampersand,$pairs);
  3257. }
  3258. public function removeUrlSuffix($pathInfo,$urlSuffix)
  3259. {
  3260. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  3261. return substr($pathInfo,0,-strlen($urlSuffix));
  3262. else
  3263. return $pathInfo;
  3264. }
  3265. public function getBaseUrl()
  3266. {
  3267. if($this->_baseUrl!==null)
  3268. return $this->_baseUrl;
  3269. else
  3270. {
  3271. if($this->showScriptName)
  3272. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  3273. else
  3274. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  3275. return $this->_baseUrl;
  3276. }
  3277. }
  3278. public function setBaseUrl($value)
  3279. {
  3280. $this->_baseUrl=$value;
  3281. }
  3282. public function getUrlFormat()
  3283. {
  3284. return $this->_urlFormat;
  3285. }
  3286. public function setUrlFormat($value)
  3287. {
  3288. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  3289. $this->_urlFormat=$value;
  3290. else
  3291. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  3292. }
  3293. }
  3294. abstract class CBaseUrlRule extends CComponent
  3295. {
  3296. public $hasHostInfo=false;
  3297. abstract public function createUrl($manager,$route,$params,$ampersand);
  3298. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  3299. }
  3300. class CUrlRule extends CBaseUrlRule
  3301. {
  3302. public $urlSuffix;
  3303. public $caseSensitive;
  3304. public $defaultParams=array();
  3305. public $matchValue;
  3306. public $verb;
  3307. public $parsingOnly=false;
  3308. public $route;
  3309. public $references=array();
  3310. public $routePattern;
  3311. public $pattern;
  3312. public $template;
  3313. public $params=array();
  3314. public $append;
  3315. public $hasHostInfo;
  3316. protected function escapeRegexpSpecialChars($matches)
  3317. {
  3318. return preg_quote($matches[0]);
  3319. }
  3320. public function __construct($route,$pattern)
  3321. {
  3322. if(is_array($route))
  3323. {
  3324. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  3325. {
  3326. if(isset($route[$name]))
  3327. $this->$name=$route[$name];
  3328. }
  3329. if(isset($route['pattern']))
  3330. $pattern=$route['pattern'];
  3331. $route=$route[0];
  3332. }
  3333. $this->route=trim($route,'/');
  3334. $tr2['/']=$tr['/']='\\/';
  3335. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  3336. {
  3337. foreach($matches2[1] as $name)
  3338. $this->references[$name]="<$name>";
  3339. }
  3340. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  3341. if($this->verb!==null)
  3342. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  3343. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  3344. {
  3345. $tokens=array_combine($matches[1],$matches[2]);
  3346. foreach($tokens as $name=>$value)
  3347. {
  3348. if($value==='')
  3349. $value='[^\/]+';
  3350. $tr["<$name>"]="(?P<$name>$value)";
  3351. if(isset($this->references[$name]))
  3352. $tr2["<$name>"]=$tr["<$name>"];
  3353. else
  3354. $this->params[$name]=$value;
  3355. }
  3356. }
  3357. $p=rtrim($pattern,'*');
  3358. $this->append=$p!==$pattern;
  3359. $p=trim($p,'/');
  3360. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  3361. $p=$this->template;
  3362. if(!$this->parsingOnly)
  3363. $p=preg_replace_callback('/(?<=^|>)[^<]+(?=<|$)/',array($this,'escapeRegexpSpecialChars'),$p);
  3364. $this->pattern='/^'.strtr($p,$tr).'\/';
  3365. if($this->append)
  3366. $this->pattern.='/u';
  3367. else
  3368. $this->pattern.='$/u';
  3369. if($this->references!==array())
  3370. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  3371. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  3372. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  3373. array('{route}'=>$route,'{pattern}'=>$pattern)));
  3374. }
  3375. public function createUrl($manager,$route,$params,$ampersand)
  3376. {
  3377. if($this->parsingOnly)
  3378. return false;
  3379. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3380. $case='';
  3381. else
  3382. $case='i';
  3383. $tr=array();
  3384. if($route!==$this->route)
  3385. {
  3386. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  3387. {
  3388. foreach($this->references as $key=>$name)
  3389. $tr[$name]=$matches[$key];
  3390. }
  3391. else
  3392. return false;
  3393. }
  3394. foreach($this->defaultParams as $key=>$value)
  3395. {
  3396. if(isset($params[$key]))
  3397. {
  3398. if($params[$key]==$value)
  3399. unset($params[$key]);
  3400. else
  3401. return false;
  3402. }
  3403. }
  3404. foreach($this->params as $key=>$value)
  3405. if(!isset($params[$key]))
  3406. return false;
  3407. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  3408. {
  3409. foreach($this->params as $key=>$value)
  3410. {
  3411. if(!preg_match('/\A'.$value.'\z/u'.$case,$params[$key]))
  3412. return false;
  3413. }
  3414. }
  3415. foreach($this->params as $key=>$value)
  3416. {
  3417. $tr["<$key>"]=urlencode($params[$key]);
  3418. unset($params[$key]);
  3419. }
  3420. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3421. $url=strtr($this->template,$tr);
  3422. if($this->hasHostInfo)
  3423. {
  3424. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  3425. if(stripos($url,$hostInfo)===0)
  3426. $url=substr($url,strlen($hostInfo));
  3427. }
  3428. if(empty($params))
  3429. return $url!=='' ? $url.$suffix : $url;
  3430. if($this->append)
  3431. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  3432. else
  3433. {
  3434. if($url!=='')
  3435. $url.=$suffix;
  3436. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  3437. }
  3438. return $url;
  3439. }
  3440. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  3441. {
  3442. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  3443. return false;
  3444. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3445. $case='';
  3446. else
  3447. $case='i';
  3448. if($this->urlSuffix!==null)
  3449. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3450. // URL suffix required, but not found in the requested URL
  3451. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3452. {
  3453. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3454. if($urlSuffix!='' && $urlSuffix!=='/')
  3455. return false;
  3456. }
  3457. if($this->hasHostInfo)
  3458. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3459. $pathInfo.='/';
  3460. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3461. {
  3462. foreach($this->defaultParams as $name=>$value)
  3463. {
  3464. if(!isset($_GET[$name]))
  3465. $_REQUEST[$name]=$_GET[$name]=$value;
  3466. }
  3467. $tr=array();
  3468. foreach($matches as $key=>$value)
  3469. {
  3470. if(isset($this->references[$key]))
  3471. $tr[$this->references[$key]]=$value;
  3472. elseif(isset($this->params[$key]))
  3473. $_REQUEST[$key]=$_GET[$key]=$value;
  3474. }
  3475. if($pathInfo!==$matches[0]) // there're additional GET params
  3476. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3477. if($this->routePattern!==null)
  3478. return strtr($this->route,$tr);
  3479. else
  3480. return $this->route;
  3481. }
  3482. else
  3483. return false;
  3484. }
  3485. }
  3486. abstract class CBaseController extends CComponent
  3487. {
  3488. private $_widgetStack=array();
  3489. abstract public function getViewFile($viewName);
  3490. public function renderFile($viewFile,$data=null,$return=false)
  3491. {
  3492. $widgetCount=count($this->_widgetStack);
  3493. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3494. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3495. else
  3496. $content=$this->renderInternal($viewFile,$data,$return);
  3497. if(count($this->_widgetStack)===$widgetCount)
  3498. return $content;
  3499. else
  3500. {
  3501. $widget=end($this->_widgetStack);
  3502. 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.',
  3503. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3504. }
  3505. }
  3506. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3507. {
  3508. // we use special variable names here to avoid conflict when extracting data
  3509. if(is_array($_data_))
  3510. extract($_data_,EXTR_PREFIX_SAME,'data');
  3511. else
  3512. $data=$_data_;
  3513. if($_return_)
  3514. {
  3515. ob_start();
  3516. ob_implicit_flush(false);
  3517. require($_viewFile_);
  3518. return ob_get_clean();
  3519. }
  3520. else
  3521. require($_viewFile_);
  3522. }
  3523. public function createWidget($className,$properties=array())
  3524. {
  3525. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3526. $widget->init();
  3527. return $widget;
  3528. }
  3529. public function widget($className,$properties=array(),$captureOutput=false)
  3530. {
  3531. if($captureOutput)
  3532. {
  3533. ob_start();
  3534. ob_implicit_flush(false);
  3535. try
  3536. {
  3537. $widget=$this->createWidget($className,$properties);
  3538. $widget->run();
  3539. }
  3540. catch(Exception $e)
  3541. {
  3542. ob_end_clean();
  3543. throw $e;
  3544. }
  3545. return ob_get_clean();
  3546. }
  3547. else
  3548. {
  3549. $widget=$this->createWidget($className,$properties);
  3550. $widget->run();
  3551. return $widget;
  3552. }
  3553. }
  3554. public function beginWidget($className,$properties=array())
  3555. {
  3556. $widget=$this->createWidget($className,$properties);
  3557. $this->_widgetStack[]=$widget;
  3558. return $widget;
  3559. }
  3560. public function endWidget($id='')
  3561. {
  3562. if(($widget=array_pop($this->_widgetStack))!==null)
  3563. {
  3564. $widget->run();
  3565. return $widget;
  3566. }
  3567. else
  3568. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3569. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3570. }
  3571. public function beginClip($id,$properties=array())
  3572. {
  3573. $properties['id']=$id;
  3574. $this->beginWidget('CClipWidget',$properties);
  3575. }
  3576. public function endClip()
  3577. {
  3578. $this->endWidget('CClipWidget');
  3579. }
  3580. public function beginCache($id,$properties=array())
  3581. {
  3582. $properties['id']=$id;
  3583. $cache=$this->beginWidget('COutputCache',$properties);
  3584. if($cache->getIsContentCached())
  3585. {
  3586. $this->endCache();
  3587. return false;
  3588. }
  3589. else
  3590. return true;
  3591. }
  3592. public function endCache()
  3593. {
  3594. $this->endWidget('COutputCache');
  3595. }
  3596. public function beginContent($view=null,$data=array())
  3597. {
  3598. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3599. }
  3600. public function endContent()
  3601. {
  3602. $this->endWidget('CContentDecorator');
  3603. }
  3604. }
  3605. class CController extends CBaseController
  3606. {
  3607. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3608. public $layout;
  3609. public $defaultAction='index';
  3610. private $_id;
  3611. private $_action;
  3612. private $_pageTitle;
  3613. private $_cachingStack;
  3614. private $_clips;
  3615. private $_dynamicOutput;
  3616. private $_pageStates;
  3617. private $_module;
  3618. public function __construct($id,$module=null)
  3619. {
  3620. $this->_id=$id;
  3621. $this->_module=$module;
  3622. $this->attachBehaviors($this->behaviors());
  3623. }
  3624. public function init()
  3625. {
  3626. }
  3627. public function filters()
  3628. {
  3629. return array();
  3630. }
  3631. public function actions()
  3632. {
  3633. return array();
  3634. }
  3635. public function behaviors()
  3636. {
  3637. return array();
  3638. }
  3639. public function accessRules()
  3640. {
  3641. return array();
  3642. }
  3643. public function run($actionID)
  3644. {
  3645. if(($action=$this->createAction($actionID))!==null)
  3646. {
  3647. if(($parent=$this->getModule())===null)
  3648. $parent=Yii::app();
  3649. if($parent->beforeControllerAction($this,$action))
  3650. {
  3651. $this->runActionWithFilters($action,$this->filters());
  3652. $parent->afterControllerAction($this,$action);
  3653. }
  3654. }
  3655. else
  3656. $this->missingAction($actionID);
  3657. }
  3658. public function runActionWithFilters($action,$filters)
  3659. {
  3660. if(empty($filters))
  3661. $this->runAction($action);
  3662. else
  3663. {
  3664. $priorAction=$this->_action;
  3665. $this->_action=$action;
  3666. CFilterChain::create($this,$action,$filters)->run();
  3667. $this->_action=$priorAction;
  3668. }
  3669. }
  3670. public function runAction($action)
  3671. {
  3672. $priorAction=$this->_action;
  3673. $this->_action=$action;
  3674. if($this->beforeAction($action))
  3675. {
  3676. if($action->runWithParams($this->getActionParams())===false)
  3677. $this->invalidActionParams($action);
  3678. else
  3679. $this->afterAction($action);
  3680. }
  3681. $this->_action=$priorAction;
  3682. }
  3683. public function getActionParams()
  3684. {
  3685. return $_GET;
  3686. }
  3687. public function invalidActionParams($action)
  3688. {
  3689. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3690. }
  3691. public function processOutput($output)
  3692. {
  3693. Yii::app()->getClientScript()->render($output);
  3694. // if using page caching, we should delay dynamic output replacement
  3695. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3696. {
  3697. $output=$this->processDynamicOutput($output);
  3698. $this->_dynamicOutput=null;
  3699. }
  3700. if($this->_pageStates===null)
  3701. $this->_pageStates=$this->loadPageStates();
  3702. if(!empty($this->_pageStates))
  3703. $this->savePageStates($this->_pageStates,$output);
  3704. return $output;
  3705. }
  3706. public function processDynamicOutput($output)
  3707. {
  3708. if($this->_dynamicOutput)
  3709. {
  3710. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3711. }
  3712. return $output;
  3713. }
  3714. protected function replaceDynamicOutput($matches)
  3715. {
  3716. $content=$matches[0];
  3717. if(isset($this->_dynamicOutput[$matches[1]]))
  3718. {
  3719. $content=$this->_dynamicOutput[$matches[1]];
  3720. $this->_dynamicOutput[$matches[1]]=null;
  3721. }
  3722. return $content;
  3723. }
  3724. public function createAction($actionID)
  3725. {
  3726. if($actionID==='')
  3727. $actionID=$this->defaultAction;
  3728. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3729. return new CInlineAction($this,$actionID);
  3730. else
  3731. {
  3732. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3733. if($action!==null && !method_exists($action,'run'))
  3734. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3735. return $action;
  3736. }
  3737. }
  3738. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3739. {
  3740. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3741. {
  3742. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3743. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3744. }
  3745. elseif($pos===false)
  3746. return null;
  3747. // the action is defined in a provider
  3748. $prefix=substr($actionID,0,$pos+1);
  3749. if(!isset($actionMap[$prefix]))
  3750. return null;
  3751. $actionID=(string)substr($actionID,$pos+1);
  3752. $provider=$actionMap[$prefix];
  3753. if(is_string($provider))
  3754. $providerType=$provider;
  3755. elseif(is_array($provider) && isset($provider['class']))
  3756. {
  3757. $providerType=$provider['class'];
  3758. if(isset($provider[$actionID]))
  3759. {
  3760. if(is_string($provider[$actionID]))
  3761. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3762. else
  3763. $config=array_merge($provider[$actionID],$config);
  3764. }
  3765. }
  3766. else
  3767. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3768. $class=Yii::import($providerType,true);
  3769. $map=call_user_func(array($class,'actions'));
  3770. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3771. }
  3772. public function missingAction($actionID)
  3773. {
  3774. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3775. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3776. }
  3777. public function getAction()
  3778. {
  3779. return $this->_action;
  3780. }
  3781. public function setAction($value)
  3782. {
  3783. $this->_action=$value;
  3784. }
  3785. public function getId()
  3786. {
  3787. return $this->_id;
  3788. }
  3789. public function getUniqueId()
  3790. {
  3791. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3792. }
  3793. public function getRoute()
  3794. {
  3795. if(($action=$this->getAction())!==null)
  3796. return $this->getUniqueId().'/'.$action->getId();
  3797. else
  3798. return $this->getUniqueId();
  3799. }
  3800. public function getModule()
  3801. {
  3802. return $this->_module;
  3803. }
  3804. public function getViewPath()
  3805. {
  3806. if(($module=$this->getModule())===null)
  3807. $module=Yii::app();
  3808. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3809. }
  3810. public function getViewFile($viewName)
  3811. {
  3812. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3813. return $viewFile;
  3814. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3815. if(($module=$this->getModule())!==null)
  3816. $moduleViewPath=$module->getViewPath();
  3817. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3818. }
  3819. public function getLayoutFile($layoutName)
  3820. {
  3821. if($layoutName===false)
  3822. return false;
  3823. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3824. return $layoutFile;
  3825. if(empty($layoutName))
  3826. {
  3827. $module=$this->getModule();
  3828. while($module!==null)
  3829. {
  3830. if($module->layout===false)
  3831. return false;
  3832. if(!empty($module->layout))
  3833. break;
  3834. $module=$module->getParentModule();
  3835. }
  3836. if($module===null)
  3837. $module=Yii::app();
  3838. $layoutName=$module->layout;
  3839. }
  3840. elseif(($module=$this->getModule())===null)
  3841. $module=Yii::app();
  3842. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3843. }
  3844. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3845. {
  3846. if(empty($viewName))
  3847. return false;
  3848. if($moduleViewPath===null)
  3849. $moduleViewPath=$basePath;
  3850. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3851. $extension=$renderer->fileExtension;
  3852. else
  3853. $extension='.php';
  3854. if($viewName[0]==='/')
  3855. {
  3856. if(strncmp($viewName,'//',2)===0)
  3857. $viewFile=$basePath.$viewName;
  3858. else
  3859. $viewFile=$moduleViewPath.$viewName;
  3860. }
  3861. elseif(strpos($viewName,'.'))
  3862. $viewFile=Yii::getPathOfAlias($viewName);
  3863. else
  3864. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3865. if(is_file($viewFile.$extension))
  3866. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3867. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  3868. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3869. else
  3870. return false;
  3871. }
  3872. public function getClips()
  3873. {
  3874. if($this->_clips!==null)
  3875. return $this->_clips;
  3876. else
  3877. return $this->_clips=new CMap;
  3878. }
  3879. public function forward($route,$exit=true)
  3880. {
  3881. if(strpos($route,'/')===false)
  3882. $this->run($route);
  3883. else
  3884. {
  3885. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3886. $route=$module->getId().'/'.$route;
  3887. Yii::app()->runController($route);
  3888. }
  3889. if($exit)
  3890. Yii::app()->end();
  3891. }
  3892. public function render($view,$data=null,$return=false)
  3893. {
  3894. if($this->beforeRender($view))
  3895. {
  3896. $output=$this->renderPartial($view,$data,true);
  3897. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3898. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3899. $this->afterRender($view,$output);
  3900. $output=$this->processOutput($output);
  3901. if($return)
  3902. return $output;
  3903. else
  3904. echo $output;
  3905. }
  3906. }
  3907. protected function beforeRender($view)
  3908. {
  3909. return true;
  3910. }
  3911. protected function afterRender($view, &$output)
  3912. {
  3913. }
  3914. public function renderText($text,$return=false)
  3915. {
  3916. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3917. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3918. $text=$this->processOutput($text);
  3919. if($return)
  3920. return $text;
  3921. else
  3922. echo $text;
  3923. }
  3924. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3925. {
  3926. if(($viewFile=$this->getViewFile($view))!==false)
  3927. {
  3928. $output=$this->renderFile($viewFile,$data,true);
  3929. if($processOutput)
  3930. $output=$this->processOutput($output);
  3931. if($return)
  3932. return $output;
  3933. else
  3934. echo $output;
  3935. }
  3936. else
  3937. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3938. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3939. }
  3940. public function renderClip($name,$params=array(),$return=false)
  3941. {
  3942. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  3943. if($return)
  3944. return $text;
  3945. else
  3946. echo $text;
  3947. }
  3948. public function renderDynamic($callback)
  3949. {
  3950. $n=count($this->_dynamicOutput);
  3951. echo "<###dynamic-$n###>";
  3952. $params=func_get_args();
  3953. array_shift($params);
  3954. $this->renderDynamicInternal($callback,$params);
  3955. }
  3956. public function renderDynamicInternal($callback,$params)
  3957. {
  3958. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3959. if(is_string($callback) && method_exists($this,$callback))
  3960. $callback=array($this,$callback);
  3961. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3962. }
  3963. public function createUrl($route,$params=array(),$ampersand='&')
  3964. {
  3965. if($route==='')
  3966. $route=$this->getId().'/'.$this->getAction()->getId();
  3967. elseif(strpos($route,'/')===false)
  3968. $route=$this->getId().'/'.$route;
  3969. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3970. $route=$module->getId().'/'.$route;
  3971. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3972. }
  3973. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3974. {
  3975. $url=$this->createUrl($route,$params,$ampersand);
  3976. if(strpos($url,'http')===0)
  3977. return $url;
  3978. else
  3979. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  3980. }
  3981. public function getPageTitle()
  3982. {
  3983. if($this->_pageTitle!==null)
  3984. return $this->_pageTitle;
  3985. else
  3986. {
  3987. $name=ucfirst(basename($this->getId()));
  3988. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3989. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3990. else
  3991. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3992. }
  3993. }
  3994. public function setPageTitle($value)
  3995. {
  3996. $this->_pageTitle=$value;
  3997. }
  3998. public function redirect($url,$terminate=true,$statusCode=302)
  3999. {
  4000. if(is_array($url))
  4001. {
  4002. $route=isset($url[0]) ? $url[0] : '';
  4003. $url=$this->createUrl($route,array_splice($url,1));
  4004. }
  4005. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  4006. }
  4007. public function refresh($terminate=true,$anchor='')
  4008. {
  4009. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  4010. }
  4011. public function recordCachingAction($context,$method,$params)
  4012. {
  4013. if($this->_cachingStack) // record only when there is an active output cache
  4014. {
  4015. foreach($this->_cachingStack as $cache)
  4016. $cache->recordAction($context,$method,$params);
  4017. }
  4018. }
  4019. public function getCachingStack($createIfNull=true)
  4020. {
  4021. if(!$this->_cachingStack)
  4022. $this->_cachingStack=new CStack;
  4023. return $this->_cachingStack;
  4024. }
  4025. public function isCachingStackEmpty()
  4026. {
  4027. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  4028. }
  4029. protected function beforeAction($action)
  4030. {
  4031. return true;
  4032. }
  4033. protected function afterAction($action)
  4034. {
  4035. }
  4036. public function filterPostOnly($filterChain)
  4037. {
  4038. if(Yii::app()->getRequest()->getIsPostRequest())
  4039. $filterChain->run();
  4040. else
  4041. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  4042. }
  4043. public function filterAjaxOnly($filterChain)
  4044. {
  4045. if(Yii::app()->getRequest()->getIsAjaxRequest())
  4046. $filterChain->run();
  4047. else
  4048. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  4049. }
  4050. public function filterAccessControl($filterChain)
  4051. {
  4052. $filter=new CAccessControlFilter;
  4053. $filter->setRules($this->accessRules());
  4054. $filter->filter($filterChain);
  4055. }
  4056. public function getPageState($name,$defaultValue=null)
  4057. {
  4058. if($this->_pageStates===null)
  4059. $this->_pageStates=$this->loadPageStates();
  4060. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  4061. }
  4062. public function setPageState($name,$value,$defaultValue=null)
  4063. {
  4064. if($this->_pageStates===null)
  4065. $this->_pageStates=$this->loadPageStates();
  4066. if($value===$defaultValue)
  4067. unset($this->_pageStates[$name]);
  4068. else
  4069. $this->_pageStates[$name]=$value;
  4070. $params=func_get_args();
  4071. $this->recordCachingAction('','setPageState',$params);
  4072. }
  4073. public function clearPageStates()
  4074. {
  4075. $this->_pageStates=array();
  4076. }
  4077. protected function loadPageStates()
  4078. {
  4079. if(!empty($_POST[self::STATE_INPUT_NAME]))
  4080. {
  4081. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  4082. {
  4083. if(extension_loaded('zlib'))
  4084. $data=@gzuncompress($data);
  4085. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  4086. return unserialize($data);
  4087. }
  4088. }
  4089. return array();
  4090. }
  4091. protected function savePageStates($states,&$output)
  4092. {
  4093. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  4094. if(extension_loaded('zlib'))
  4095. $data=gzcompress($data);
  4096. $value=base64_encode($data);
  4097. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  4098. }
  4099. }
  4100. abstract class CAction extends CComponent implements IAction
  4101. {
  4102. private $_id;
  4103. private $_controller;
  4104. public function __construct($controller,$id)
  4105. {
  4106. $this->_controller=$controller;
  4107. $this->_id=$id;
  4108. }
  4109. public function getController()
  4110. {
  4111. return $this->_controller;
  4112. }
  4113. public function getId()
  4114. {
  4115. return $this->_id;
  4116. }
  4117. public function runWithParams($params)
  4118. {
  4119. $method=new ReflectionMethod($this, 'run');
  4120. if($method->getNumberOfParameters()>0)
  4121. return $this->runWithParamsInternal($this, $method, $params);
  4122. $this->run();
  4123. return true;
  4124. }
  4125. protected function runWithParamsInternal($object, $method, $params)
  4126. {
  4127. $ps=array();
  4128. foreach($method->getParameters() as $i=>$param)
  4129. {
  4130. $name=$param->getName();
  4131. if(isset($params[$name]))
  4132. {
  4133. if($param->isArray())
  4134. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  4135. elseif(!is_array($params[$name]))
  4136. $ps[]=$params[$name];
  4137. else
  4138. return false;
  4139. }
  4140. elseif($param->isDefaultValueAvailable())
  4141. $ps[]=$param->getDefaultValue();
  4142. else
  4143. return false;
  4144. }
  4145. $method->invokeArgs($object,$ps);
  4146. return true;
  4147. }
  4148. }
  4149. class CInlineAction extends CAction
  4150. {
  4151. public function run()
  4152. {
  4153. $method='action'.$this->getId();
  4154. $this->getController()->$method();
  4155. }
  4156. public function runWithParams($params)
  4157. {
  4158. $methodName='action'.$this->getId();
  4159. $controller=$this->getController();
  4160. $method=new ReflectionMethod($controller, $methodName);
  4161. if($method->getNumberOfParameters()>0)
  4162. return $this->runWithParamsInternal($controller, $method, $params);
  4163. $controller->$methodName();
  4164. return true;
  4165. }
  4166. }
  4167. class CWebUser extends CApplicationComponent implements IWebUser
  4168. {
  4169. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  4170. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  4171. const STATES_VAR='__states';
  4172. const AUTH_TIMEOUT_VAR='__timeout';
  4173. const AUTH_ABSOLUTE_TIMEOUT_VAR='__absolute_timeout';
  4174. public $allowAutoLogin=false;
  4175. public $guestName='Guest';
  4176. public $loginUrl=array('/site/login');
  4177. public $identityCookie;
  4178. public $authTimeout;
  4179. public $absoluteAuthTimeout;
  4180. public $autoRenewCookie=false;
  4181. public $autoUpdateFlash=true;
  4182. public $loginRequiredAjaxResponse;
  4183. private $_keyPrefix;
  4184. private $_access=array();
  4185. public function __get($name)
  4186. {
  4187. if($this->hasState($name))
  4188. return $this->getState($name);
  4189. else
  4190. return parent::__get($name);
  4191. }
  4192. public function __set($name,$value)
  4193. {
  4194. if($this->hasState($name))
  4195. $this->setState($name,$value);
  4196. else
  4197. parent::__set($name,$value);
  4198. }
  4199. public function __isset($name)
  4200. {
  4201. if($this->hasState($name))
  4202. return $this->getState($name)!==null;
  4203. else
  4204. return parent::__isset($name);
  4205. }
  4206. public function __unset($name)
  4207. {
  4208. if($this->hasState($name))
  4209. $this->setState($name,null);
  4210. else
  4211. parent::__unset($name);
  4212. }
  4213. public function init()
  4214. {
  4215. parent::init();
  4216. Yii::app()->getSession()->open();
  4217. if($this->getIsGuest() && $this->allowAutoLogin)
  4218. $this->restoreFromCookie();
  4219. elseif($this->autoRenewCookie && $this->allowAutoLogin)
  4220. $this->renewCookie();
  4221. if($this->autoUpdateFlash)
  4222. $this->updateFlash();
  4223. $this->updateAuthStatus();
  4224. }
  4225. public function login($identity,$duration=0)
  4226. {
  4227. $id=$identity->getId();
  4228. $states=$identity->getPersistentStates();
  4229. if($this->beforeLogin($id,$states,false))
  4230. {
  4231. $this->changeIdentity($id,$identity->getName(),$states);
  4232. if($duration>0)
  4233. {
  4234. if($this->allowAutoLogin)
  4235. $this->saveToCookie($duration);
  4236. else
  4237. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  4238. array('{class}'=>get_class($this))));
  4239. }
  4240. if ($this->absoluteAuthTimeout)
  4241. $this->setState(self::AUTH_ABSOLUTE_TIMEOUT_VAR, time()+$this->absoluteAuthTimeout);
  4242. $this->afterLogin(false);
  4243. }
  4244. return !$this->getIsGuest();
  4245. }
  4246. public function logout($destroySession=true)
  4247. {
  4248. if($this->beforeLogout())
  4249. {
  4250. if($this->allowAutoLogin)
  4251. {
  4252. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  4253. if($this->identityCookie!==null)
  4254. {
  4255. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4256. $cookie->value=null;
  4257. $cookie->expire=0;
  4258. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  4259. }
  4260. }
  4261. if($destroySession)
  4262. Yii::app()->getSession()->destroy();
  4263. else
  4264. $this->clearStates();
  4265. $this->_access=array();
  4266. $this->afterLogout();
  4267. }
  4268. }
  4269. public function getIsGuest()
  4270. {
  4271. return $this->getState('__id')===null;
  4272. }
  4273. public function getId()
  4274. {
  4275. return $this->getState('__id');
  4276. }
  4277. public function setId($value)
  4278. {
  4279. $this->setState('__id',$value);
  4280. }
  4281. public function getName()
  4282. {
  4283. if(($name=$this->getState('__name'))!==null)
  4284. return $name;
  4285. else
  4286. return $this->guestName;
  4287. }
  4288. public function setName($value)
  4289. {
  4290. $this->setState('__name',$value);
  4291. }
  4292. public function getReturnUrl($defaultUrl=null)
  4293. {
  4294. if($defaultUrl===null)
  4295. {
  4296. $defaultReturnUrl=Yii::app()->getUrlManager()->showScriptName ? Yii::app()->getRequest()->getScriptUrl() : Yii::app()->getRequest()->getBaseUrl().'/';
  4297. }
  4298. else
  4299. {
  4300. $defaultReturnUrl=CHtml::normalizeUrl($defaultUrl);
  4301. }
  4302. return $this->getState('__returnUrl',$defaultReturnUrl);
  4303. }
  4304. public function setReturnUrl($value)
  4305. {
  4306. $this->setState('__returnUrl',$value);
  4307. }
  4308. public function loginRequired()
  4309. {
  4310. $app=Yii::app();
  4311. $request=$app->getRequest();
  4312. if(!$request->getIsAjaxRequest())
  4313. {
  4314. $this->setReturnUrl($request->getUrl());
  4315. if(($url=$this->loginUrl)!==null)
  4316. {
  4317. if(is_array($url))
  4318. {
  4319. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  4320. $url=$app->createUrl($route,array_splice($url,1));
  4321. }
  4322. $request->redirect($url);
  4323. }
  4324. }
  4325. elseif(isset($this->loginRequiredAjaxResponse))
  4326. {
  4327. echo $this->loginRequiredAjaxResponse;
  4328. Yii::app()->end();
  4329. }
  4330. throw new CHttpException(403,Yii::t('yii','Login Required'));
  4331. }
  4332. protected function beforeLogin($id,$states,$fromCookie)
  4333. {
  4334. return true;
  4335. }
  4336. protected function afterLogin($fromCookie)
  4337. {
  4338. }
  4339. protected function beforeLogout()
  4340. {
  4341. return true;
  4342. }
  4343. protected function afterLogout()
  4344. {
  4345. }
  4346. protected function restoreFromCookie()
  4347. {
  4348. $app=Yii::app();
  4349. $request=$app->getRequest();
  4350. $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  4351. if($cookie && !empty($cookie->value) && is_string($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  4352. {
  4353. $data=@unserialize($data);
  4354. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4355. {
  4356. list($id,$name,$duration,$states)=$data;
  4357. if($this->beforeLogin($id,$states,true))
  4358. {
  4359. $this->changeIdentity($id,$name,$states);
  4360. if($this->autoRenewCookie)
  4361. {
  4362. $this->saveToCookie($duration);
  4363. }
  4364. $this->afterLogin(true);
  4365. }
  4366. }
  4367. }
  4368. }
  4369. protected function renewCookie()
  4370. {
  4371. $request=Yii::app()->getRequest();
  4372. $cookies=$request->getCookies();
  4373. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  4374. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  4375. {
  4376. $data=@unserialize($data);
  4377. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4378. {
  4379. $this->saveToCookie($data[2]);
  4380. }
  4381. }
  4382. }
  4383. protected function saveToCookie($duration)
  4384. {
  4385. $app=Yii::app();
  4386. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4387. $cookie->expire=time()+$duration;
  4388. $data=array(
  4389. $this->getId(),
  4390. $this->getName(),
  4391. $duration,
  4392. $this->saveIdentityStates(),
  4393. );
  4394. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  4395. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  4396. }
  4397. protected function createIdentityCookie($name)
  4398. {
  4399. $cookie=new CHttpCookie($name,'');
  4400. if(is_array($this->identityCookie))
  4401. {
  4402. foreach($this->identityCookie as $name=>$value)
  4403. $cookie->$name=$value;
  4404. }
  4405. return $cookie;
  4406. }
  4407. public function getStateKeyPrefix()
  4408. {
  4409. if($this->_keyPrefix!==null)
  4410. return $this->_keyPrefix;
  4411. else
  4412. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  4413. }
  4414. public function setStateKeyPrefix($value)
  4415. {
  4416. $this->_keyPrefix=$value;
  4417. }
  4418. public function getState($key,$defaultValue=null)
  4419. {
  4420. $key=$this->getStateKeyPrefix().$key;
  4421. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4422. }
  4423. public function setState($key,$value,$defaultValue=null)
  4424. {
  4425. $key=$this->getStateKeyPrefix().$key;
  4426. if($value===$defaultValue)
  4427. unset($_SESSION[$key]);
  4428. else
  4429. $_SESSION[$key]=$value;
  4430. }
  4431. public function hasState($key)
  4432. {
  4433. $key=$this->getStateKeyPrefix().$key;
  4434. return isset($_SESSION[$key]);
  4435. }
  4436. public function clearStates()
  4437. {
  4438. $keys=array_keys($_SESSION);
  4439. $prefix=$this->getStateKeyPrefix();
  4440. $n=strlen($prefix);
  4441. foreach($keys as $key)
  4442. {
  4443. if(!strncmp($key,$prefix,$n))
  4444. unset($_SESSION[$key]);
  4445. }
  4446. }
  4447. public function getFlashes($delete=true)
  4448. {
  4449. $flashes=array();
  4450. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  4451. $keys=array_keys($_SESSION);
  4452. $n=strlen($prefix);
  4453. foreach($keys as $key)
  4454. {
  4455. if(!strncmp($key,$prefix,$n))
  4456. {
  4457. $flashes[substr($key,$n)]=$_SESSION[$key];
  4458. if($delete)
  4459. unset($_SESSION[$key]);
  4460. }
  4461. }
  4462. if($delete)
  4463. $this->setState(self::FLASH_COUNTERS,array());
  4464. return $flashes;
  4465. }
  4466. public function getFlash($key,$defaultValue=null,$delete=true)
  4467. {
  4468. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4469. if($delete)
  4470. $this->setFlash($key,null);
  4471. return $value;
  4472. }
  4473. public function setFlash($key,$value,$defaultValue=null)
  4474. {
  4475. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4476. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4477. if($value===$defaultValue)
  4478. unset($counters[$key]);
  4479. else
  4480. $counters[$key]=0;
  4481. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4482. }
  4483. public function hasFlash($key)
  4484. {
  4485. return $this->getFlash($key, null, false)!==null;
  4486. }
  4487. protected function changeIdentity($id,$name,$states)
  4488. {
  4489. Yii::app()->getSession()->regenerateID(true);
  4490. $this->setId($id);
  4491. $this->setName($name);
  4492. $this->loadIdentityStates($states);
  4493. }
  4494. protected function saveIdentityStates()
  4495. {
  4496. $states=array();
  4497. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4498. $states[$name]=$this->getState($name);
  4499. return $states;
  4500. }
  4501. protected function loadIdentityStates($states)
  4502. {
  4503. $names=array();
  4504. if(is_array($states))
  4505. {
  4506. foreach($states as $name=>$value)
  4507. {
  4508. $this->setState($name,$value);
  4509. $names[$name]=true;
  4510. }
  4511. }
  4512. $this->setState(self::STATES_VAR,$names);
  4513. }
  4514. protected function updateFlash()
  4515. {
  4516. $counters=$this->getState(self::FLASH_COUNTERS);
  4517. if(!is_array($counters))
  4518. return;
  4519. foreach($counters as $key=>$count)
  4520. {
  4521. if($count)
  4522. {
  4523. unset($counters[$key]);
  4524. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4525. }
  4526. else
  4527. $counters[$key]++;
  4528. }
  4529. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4530. }
  4531. protected function updateAuthStatus()
  4532. {
  4533. if(($this->authTimeout!==null || $this->absoluteAuthTimeout!==null) && !$this->getIsGuest())
  4534. {
  4535. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4536. $expiresAbsolute=$this->getState(self::AUTH_ABSOLUTE_TIMEOUT_VAR);
  4537. if ($expires!==null && $expires < time() || $expiresAbsolute!==null && $expiresAbsolute < time())
  4538. $this->logout(false);
  4539. else
  4540. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4541. }
  4542. }
  4543. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4544. {
  4545. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4546. return $this->_access[$operation];
  4547. $access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4548. if($allowCaching && $params===array())
  4549. $this->_access[$operation]=$access;
  4550. return $access;
  4551. }
  4552. }
  4553. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4554. {
  4555. public $autoStart=true;
  4556. public function init()
  4557. {
  4558. parent::init();
  4559. if($this->autoStart)
  4560. $this->open();
  4561. register_shutdown_function(array($this,'close'));
  4562. }
  4563. public function getUseCustomStorage()
  4564. {
  4565. return false;
  4566. }
  4567. public function open()
  4568. {
  4569. if($this->getUseCustomStorage())
  4570. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4571. @session_start();
  4572. if(YII_DEBUG && session_id()=='')
  4573. {
  4574. $message=Yii::t('yii','Failed to start session.');
  4575. if(function_exists('error_get_last'))
  4576. {
  4577. $error=error_get_last();
  4578. if(isset($error['message']))
  4579. $message=$error['message'];
  4580. }
  4581. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4582. }
  4583. }
  4584. public function close()
  4585. {
  4586. if(session_id()!=='')
  4587. @session_write_close();
  4588. }
  4589. public function destroy()
  4590. {
  4591. if(session_id()!=='')
  4592. {
  4593. @session_unset();
  4594. @session_destroy();
  4595. }
  4596. }
  4597. public function getIsStarted()
  4598. {
  4599. return session_id()!=='';
  4600. }
  4601. public function getSessionID()
  4602. {
  4603. return session_id();
  4604. }
  4605. public function setSessionID($value)
  4606. {
  4607. session_id($value);
  4608. }
  4609. public function regenerateID($deleteOldSession=false)
  4610. {
  4611. if($this->getIsStarted())
  4612. session_regenerate_id($deleteOldSession);
  4613. }
  4614. public function getSessionName()
  4615. {
  4616. return session_name();
  4617. }
  4618. public function setSessionName($value)
  4619. {
  4620. session_name($value);
  4621. }
  4622. public function getSavePath()
  4623. {
  4624. return session_save_path();
  4625. }
  4626. public function setSavePath($value)
  4627. {
  4628. if(is_dir($value))
  4629. session_save_path($value);
  4630. else
  4631. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4632. array('{path}'=>$value)));
  4633. }
  4634. public function getCookieParams()
  4635. {
  4636. return session_get_cookie_params();
  4637. }
  4638. public function setCookieParams($value)
  4639. {
  4640. $data=session_get_cookie_params();
  4641. extract($data);
  4642. extract($value);
  4643. if(isset($httponly))
  4644. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4645. else
  4646. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4647. }
  4648. public function getCookieMode()
  4649. {
  4650. if(ini_get('session.use_cookies')==='0')
  4651. return 'none';
  4652. elseif(ini_get('session.use_only_cookies')==='0')
  4653. return 'allow';
  4654. else
  4655. return 'only';
  4656. }
  4657. public function setCookieMode($value)
  4658. {
  4659. if($value==='none')
  4660. {
  4661. ini_set('session.use_cookies','0');
  4662. ini_set('session.use_only_cookies','0');
  4663. }
  4664. elseif($value==='allow')
  4665. {
  4666. ini_set('session.use_cookies','1');
  4667. ini_set('session.use_only_cookies','0');
  4668. }
  4669. elseif($value==='only')
  4670. {
  4671. ini_set('session.use_cookies','1');
  4672. ini_set('session.use_only_cookies','1');
  4673. }
  4674. else
  4675. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4676. }
  4677. public function getGCProbability()
  4678. {
  4679. return (float)(ini_get('session.gc_probability')/ini_get('session.gc_divisor')*100);
  4680. }
  4681. public function setGCProbability($value)
  4682. {
  4683. if($value>=0 && $value<=100)
  4684. {
  4685. // percent * 21474837 / 2147483647 ≈ percent * 0.01
  4686. ini_set('session.gc_probability',floor($value*21474836.47));
  4687. ini_set('session.gc_divisor',2147483647);
  4688. }
  4689. else
  4690. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be a float between 0 and 100.',
  4691. array('{value}'=>$value)));
  4692. }
  4693. public function getUseTransparentSessionID()
  4694. {
  4695. return ini_get('session.use_trans_sid')==1;
  4696. }
  4697. public function setUseTransparentSessionID($value)
  4698. {
  4699. ini_set('session.use_trans_sid',$value?'1':'0');
  4700. }
  4701. public function getTimeout()
  4702. {
  4703. return (int)ini_get('session.gc_maxlifetime');
  4704. }
  4705. public function setTimeout($value)
  4706. {
  4707. ini_set('session.gc_maxlifetime',$value);
  4708. }
  4709. public function openSession($savePath,$sessionName)
  4710. {
  4711. return true;
  4712. }
  4713. public function closeSession()
  4714. {
  4715. return true;
  4716. }
  4717. public function readSession($id)
  4718. {
  4719. return '';
  4720. }
  4721. public function writeSession($id,$data)
  4722. {
  4723. return true;
  4724. }
  4725. public function destroySession($id)
  4726. {
  4727. return true;
  4728. }
  4729. public function gcSession($maxLifetime)
  4730. {
  4731. return true;
  4732. }
  4733. //------ The following methods enable CHttpSession to be CMap-like -----
  4734. public function getIterator()
  4735. {
  4736. return new CHttpSessionIterator;
  4737. }
  4738. public function getCount()
  4739. {
  4740. return count($_SESSION);
  4741. }
  4742. public function count()
  4743. {
  4744. return $this->getCount();
  4745. }
  4746. public function getKeys()
  4747. {
  4748. return array_keys($_SESSION);
  4749. }
  4750. public function get($key,$defaultValue=null)
  4751. {
  4752. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4753. }
  4754. public function itemAt($key)
  4755. {
  4756. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4757. }
  4758. public function add($key,$value)
  4759. {
  4760. $_SESSION[$key]=$value;
  4761. }
  4762. public function remove($key)
  4763. {
  4764. if(isset($_SESSION[$key]))
  4765. {
  4766. $value=$_SESSION[$key];
  4767. unset($_SESSION[$key]);
  4768. return $value;
  4769. }
  4770. else
  4771. return null;
  4772. }
  4773. public function clear()
  4774. {
  4775. foreach(array_keys($_SESSION) as $key)
  4776. unset($_SESSION[$key]);
  4777. }
  4778. public function contains($key)
  4779. {
  4780. return isset($_SESSION[$key]);
  4781. }
  4782. public function toArray()
  4783. {
  4784. return $_SESSION;
  4785. }
  4786. public function offsetExists($offset)
  4787. {
  4788. return isset($_SESSION[$offset]);
  4789. }
  4790. public function offsetGet($offset)
  4791. {
  4792. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4793. }
  4794. public function offsetSet($offset,$item)
  4795. {
  4796. $_SESSION[$offset]=$item;
  4797. }
  4798. public function offsetUnset($offset)
  4799. {
  4800. unset($_SESSION[$offset]);
  4801. }
  4802. }
  4803. class CHtml
  4804. {
  4805. const ID_PREFIX='yt';
  4806. public static $errorSummaryCss='errorSummary';
  4807. public static $errorMessageCss='errorMessage';
  4808. public static $errorCss='error';
  4809. public static $errorContainerTag='div';
  4810. public static $requiredCss='required';
  4811. public static $beforeRequiredLabel='';
  4812. public static $afterRequiredLabel=' <span class="required">*</span>';
  4813. public static $count=0;
  4814. public static $liveEvents=true;
  4815. public static $closeSingleTags=true;
  4816. public static $renderSpecialAttributesValue=true;
  4817. private static $_modelNameConverter;
  4818. public static function encode($text)
  4819. {
  4820. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4821. }
  4822. public static function decode($text)
  4823. {
  4824. return htmlspecialchars_decode($text,ENT_QUOTES);
  4825. }
  4826. public static function encodeArray($data)
  4827. {
  4828. $d=array();
  4829. foreach($data as $key=>$value)
  4830. {
  4831. if(is_string($key))
  4832. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4833. if(is_string($value))
  4834. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4835. elseif(is_array($value))
  4836. $value=self::encodeArray($value);
  4837. $d[$key]=$value;
  4838. }
  4839. return $d;
  4840. }
  4841. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4842. {
  4843. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4844. if($content===false)
  4845. return $closeTag && self::$closeSingleTags ? $html.' />' : $html.'>';
  4846. else
  4847. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4848. }
  4849. public static function openTag($tag,$htmlOptions=array())
  4850. {
  4851. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4852. }
  4853. public static function closeTag($tag)
  4854. {
  4855. return '</'.$tag.'>';
  4856. }
  4857. public static function cdata($text)
  4858. {
  4859. return '<![CDATA[' . $text . ']]>';
  4860. }
  4861. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4862. {
  4863. if($name!==null)
  4864. $options['name']=$name;
  4865. if($httpEquiv!==null)
  4866. $options['http-equiv']=$httpEquiv;
  4867. $options['content']=$content;
  4868. return self::tag('meta',$options);
  4869. }
  4870. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4871. {
  4872. if($relation!==null)
  4873. $options['rel']=$relation;
  4874. if($type!==null)
  4875. $options['type']=$type;
  4876. if($href!==null)
  4877. $options['href']=$href;
  4878. if($media!==null)
  4879. $options['media']=$media;
  4880. return self::tag('link',$options);
  4881. }
  4882. public static function css($text,$media='')
  4883. {
  4884. if($media!=='')
  4885. $media=' media="'.$media.'"';
  4886. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4887. }
  4888. public static function refresh($seconds,$url='')
  4889. {
  4890. $content="$seconds";
  4891. if($url!=='')
  4892. $content.=';url='.self::normalizeUrl($url);
  4893. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4894. }
  4895. public static function cssFile($url,$media='')
  4896. {
  4897. return CHtml::linkTag('stylesheet','text/css',$url,$media!=='' ? $media : null);
  4898. }
  4899. public static function script($text,array $htmlOptions=array())
  4900. {
  4901. $defaultHtmlOptions=array(
  4902. 'type'=>'text/javascript',
  4903. );
  4904. $htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
  4905. return self::tag('script',$htmlOptions,"\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n");
  4906. }
  4907. public static function scriptFile($url,array $htmlOptions=array())
  4908. {
  4909. $defaultHtmlOptions=array(
  4910. 'type'=>'text/javascript',
  4911. 'src'=>$url
  4912. );
  4913. $htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
  4914. return self::tag('script',$htmlOptions,'');
  4915. }
  4916. public static function form($action='',$method='post',$htmlOptions=array())
  4917. {
  4918. return self::beginForm($action,$method,$htmlOptions);
  4919. }
  4920. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4921. {
  4922. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4923. if(strcasecmp($method,'get')!==0 && strcasecmp($method,'post')!==0)
  4924. {
  4925. $customMethod=$method;
  4926. $method='post';
  4927. }
  4928. else
  4929. $customMethod=false;
  4930. $htmlOptions['method']=$method;
  4931. $form=self::tag('form',$htmlOptions,false,false);
  4932. $hiddens=array();
  4933. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4934. {
  4935. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4936. {
  4937. if(($pos=strpos($pair,'='))!==false)
  4938. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4939. else
  4940. $hiddens[]=self::hiddenField(urldecode($pair),'',array('id'=>false));
  4941. }
  4942. }
  4943. $request=Yii::app()->request;
  4944. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4945. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4946. if($customMethod!==false)
  4947. $hiddens[]=self::hiddenField('_method',$customMethod);
  4948. if($hiddens!==array())
  4949. $form.="\n".implode("\n",$hiddens);
  4950. return $form;
  4951. }
  4952. public static function endForm()
  4953. {
  4954. return '</form>';
  4955. }
  4956. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4957. {
  4958. return self::form($action,$method,$htmlOptions)."\n".
  4959. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4960. }
  4961. public static function pageStateField($value)
  4962. {
  4963. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4964. }
  4965. public static function link($text,$url='#',$htmlOptions=array())
  4966. {
  4967. if($url!=='')
  4968. $htmlOptions['href']=self::normalizeUrl($url);
  4969. self::clientChange('click',$htmlOptions);
  4970. return self::tag('a',$htmlOptions,$text);
  4971. }
  4972. public static function mailto($text,$email='',$htmlOptions=array())
  4973. {
  4974. if($email==='')
  4975. $email=$text;
  4976. return self::link($text,'mailto:'.$email,$htmlOptions);
  4977. }
  4978. public static function image($src,$alt='',$htmlOptions=array())
  4979. {
  4980. $htmlOptions['src']=$src;
  4981. $htmlOptions['alt']=$alt;
  4982. return self::tag('img',$htmlOptions);
  4983. }
  4984. public static function button($label='button',$htmlOptions=array())
  4985. {
  4986. if(!isset($htmlOptions['name']))
  4987. {
  4988. if(!array_key_exists('name',$htmlOptions))
  4989. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4990. }
  4991. if(!isset($htmlOptions['type']))
  4992. $htmlOptions['type']='button';
  4993. if(!isset($htmlOptions['value']) && $htmlOptions['type']!='image')
  4994. $htmlOptions['value']=$label;
  4995. self::clientChange('click',$htmlOptions);
  4996. return self::tag('input',$htmlOptions);
  4997. }
  4998. public static function htmlButton($label='button',$htmlOptions=array())
  4999. {
  5000. if(!isset($htmlOptions['name']))
  5001. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  5002. if(!isset($htmlOptions['type']))
  5003. $htmlOptions['type']='button';
  5004. self::clientChange('click',$htmlOptions);
  5005. return self::tag('button',$htmlOptions,$label);
  5006. }
  5007. public static function submitButton($label='submit',$htmlOptions=array())
  5008. {
  5009. $htmlOptions['type']='submit';
  5010. return self::button($label,$htmlOptions);
  5011. }
  5012. public static function resetButton($label='reset',$htmlOptions=array())
  5013. {
  5014. $htmlOptions['type']='reset';
  5015. return self::button($label,$htmlOptions);
  5016. }
  5017. public static function imageButton($src,$htmlOptions=array())
  5018. {
  5019. $htmlOptions['src']=$src;
  5020. $htmlOptions['type']='image';
  5021. return self::button('submit',$htmlOptions);
  5022. }
  5023. public static function linkButton($label='submit',$htmlOptions=array())
  5024. {
  5025. if(!isset($htmlOptions['submit']))
  5026. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  5027. return self::link($label,'#',$htmlOptions);
  5028. }
  5029. public static function label($label,$for,$htmlOptions=array())
  5030. {
  5031. if($for===false)
  5032. unset($htmlOptions['for']);
  5033. else
  5034. $htmlOptions['for']=$for;
  5035. if(isset($htmlOptions['required']))
  5036. {
  5037. if($htmlOptions['required'])
  5038. {
  5039. if(isset($htmlOptions['class']))
  5040. $htmlOptions['class'].=' '.self::$requiredCss;
  5041. else
  5042. $htmlOptions['class']=self::$requiredCss;
  5043. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  5044. }
  5045. unset($htmlOptions['required']);
  5046. }
  5047. return self::tag('label',$htmlOptions,$label);
  5048. }
  5049. public static function colorField($name,$value='',$htmlOptions=array())
  5050. {
  5051. self::clientChange('change',$htmlOptions);
  5052. return self::inputField('color',$name,$value,$htmlOptions);
  5053. }
  5054. public static function textField($name,$value='',$htmlOptions=array())
  5055. {
  5056. self::clientChange('change',$htmlOptions);
  5057. return self::inputField('text',$name,$value,$htmlOptions);
  5058. }
  5059. public static function searchField($name,$value='',$htmlOptions=array())
  5060. {
  5061. self::clientChange('change',$htmlOptions);
  5062. return self::inputField('search',$name,$value,$htmlOptions);
  5063. }
  5064. public static function numberField($name,$value='',$htmlOptions=array())
  5065. {
  5066. self::clientChange('change',$htmlOptions);
  5067. return self::inputField('number',$name,$value,$htmlOptions);
  5068. }
  5069. public static function rangeField($name,$value='',$htmlOptions=array())
  5070. {
  5071. self::clientChange('change',$htmlOptions);
  5072. return self::inputField('range',$name,$value,$htmlOptions);
  5073. }
  5074. public static function dateField($name,$value='',$htmlOptions=array())
  5075. {
  5076. self::clientChange('change',$htmlOptions);
  5077. return self::inputField('date',$name,$value,$htmlOptions);
  5078. }
  5079. public static function timeField($name,$value='',$htmlOptions=array())
  5080. {
  5081. self::clientChange('change',$htmlOptions);
  5082. return self::inputField('time',$name,$value,$htmlOptions);
  5083. }
  5084. public static function dateTimeField($name,$value='',$htmlOptions=array())
  5085. {
  5086. self::clientChange('change',$htmlOptions);
  5087. return self::inputField('datetime',$name,$value,$htmlOptions);
  5088. }
  5089. public static function dateTimeLocalField($name,$value='',$htmlOptions=array())
  5090. {
  5091. self::clientChange('change',$htmlOptions);
  5092. return self::inputField('datetime-local',$name,$value,$htmlOptions);
  5093. }
  5094. public static function weekField($name,$value='',$htmlOptions=array())
  5095. {
  5096. self::clientChange('change',$htmlOptions);
  5097. return self::inputField('week',$name,$value,$htmlOptions);
  5098. }
  5099. public static function emailField($name,$value='',$htmlOptions=array())
  5100. {
  5101. self::clientChange('change',$htmlOptions);
  5102. return self::inputField('email',$name,$value,$htmlOptions);
  5103. }
  5104. public static function telField($name,$value='',$htmlOptions=array())
  5105. {
  5106. self::clientChange('change',$htmlOptions);
  5107. return self::inputField('tel',$name,$value,$htmlOptions);
  5108. }
  5109. public static function urlField($name,$value='',$htmlOptions=array())
  5110. {
  5111. self::clientChange('change',$htmlOptions);
  5112. return self::inputField('url',$name,$value,$htmlOptions);
  5113. }
  5114. public static function hiddenField($name,$value='',$htmlOptions=array())
  5115. {
  5116. return self::inputField('hidden',$name,$value,$htmlOptions);
  5117. }
  5118. public static function passwordField($name,$value='',$htmlOptions=array())
  5119. {
  5120. self::clientChange('change',$htmlOptions);
  5121. return self::inputField('password',$name,$value,$htmlOptions);
  5122. }
  5123. public static function fileField($name,$value='',$htmlOptions=array())
  5124. {
  5125. return self::inputField('file',$name,$value,$htmlOptions);
  5126. }
  5127. public static function textArea($name,$value='',$htmlOptions=array())
  5128. {
  5129. $htmlOptions['name']=$name;
  5130. if(!isset($htmlOptions['id']))
  5131. $htmlOptions['id']=self::getIdByName($name);
  5132. elseif($htmlOptions['id']===false)
  5133. unset($htmlOptions['id']);
  5134. self::clientChange('change',$htmlOptions);
  5135. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  5136. }
  5137. public static function radioButton($name,$checked=false,$htmlOptions=array())
  5138. {
  5139. if($checked)
  5140. $htmlOptions['checked']='checked';
  5141. else
  5142. unset($htmlOptions['checked']);
  5143. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  5144. self::clientChange('click',$htmlOptions);
  5145. if(array_key_exists('uncheckValue',$htmlOptions))
  5146. {
  5147. $uncheck=$htmlOptions['uncheckValue'];
  5148. unset($htmlOptions['uncheckValue']);
  5149. }
  5150. else
  5151. $uncheck=null;
  5152. if($uncheck!==null)
  5153. {
  5154. // add a hidden field so that if the radio button is not selected, it still submits a value
  5155. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  5156. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  5157. else
  5158. $uncheckOptions=array('id'=>false);
  5159. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  5160. }
  5161. else
  5162. $hidden='';
  5163. // add a hidden field so that if the radio button is not selected, it still submits a value
  5164. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  5165. }
  5166. public static function checkBox($name,$checked=false,$htmlOptions=array())
  5167. {
  5168. if($checked)
  5169. $htmlOptions['checked']='checked';
  5170. else
  5171. unset($htmlOptions['checked']);
  5172. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  5173. self::clientChange('click',$htmlOptions);
  5174. if(array_key_exists('uncheckValue',$htmlOptions))
  5175. {
  5176. $uncheck=$htmlOptions['uncheckValue'];
  5177. unset($htmlOptions['uncheckValue']);
  5178. }
  5179. else
  5180. $uncheck=null;
  5181. if($uncheck!==null)
  5182. {
  5183. // add a hidden field so that if the check box is not checked, it still submits a value
  5184. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  5185. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  5186. else
  5187. $uncheckOptions=array('id'=>false);
  5188. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  5189. }
  5190. else
  5191. $hidden='';
  5192. // add a hidden field so that if the check box is not checked, it still submits a value
  5193. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  5194. }
  5195. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  5196. {
  5197. $htmlOptions['name']=$name;
  5198. if(!isset($htmlOptions['id']))
  5199. $htmlOptions['id']=self::getIdByName($name);
  5200. elseif($htmlOptions['id']===false)
  5201. unset($htmlOptions['id']);
  5202. self::clientChange('change',$htmlOptions);
  5203. $options="\n".self::listOptions($select,$data,$htmlOptions);
  5204. $hidden='';
  5205. if(!empty($htmlOptions['multiple']))
  5206. {
  5207. if(substr($htmlOptions['name'],-2)!=='[]')
  5208. $htmlOptions['name'].='[]';
  5209. if(isset($htmlOptions['unselectValue']))
  5210. {
  5211. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5212. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  5213. unset($htmlOptions['unselectValue']);
  5214. }
  5215. }
  5216. // add a hidden field so that if the option is not selected, it still submits a value
  5217. return $hidden . self::tag('select',$htmlOptions,$options);
  5218. }
  5219. public static function listBox($name,$select,$data,$htmlOptions=array())
  5220. {
  5221. if(!isset($htmlOptions['size']))
  5222. $htmlOptions['size']=4;
  5223. if(!empty($htmlOptions['multiple']))
  5224. {
  5225. if(substr($name,-2)!=='[]')
  5226. $name.='[]';
  5227. }
  5228. return self::dropDownList($name,$select,$data,$htmlOptions);
  5229. }
  5230. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  5231. {
  5232. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  5233. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:self::tag('br');
  5234. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  5235. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  5236. if(substr($name,-2)!=='[]')
  5237. $name.='[]';
  5238. if(isset($htmlOptions['checkAll']))
  5239. {
  5240. $checkAllLabel=$htmlOptions['checkAll'];
  5241. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  5242. }
  5243. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  5244. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  5245. unset($htmlOptions['labelOptions']);
  5246. $items=array();
  5247. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  5248. unset($htmlOptions['baseID']);
  5249. $id=0;
  5250. $checkAll=true;
  5251. foreach($data as $value=>$labelTitle)
  5252. {
  5253. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  5254. $checkAll=$checkAll && $checked;
  5255. $htmlOptions['value']=$value;
  5256. $htmlOptions['id']=$baseID.'_'.$id++;
  5257. $option=self::checkBox($name,$checked,$htmlOptions);
  5258. $beginLabel=self::openTag('label',$labelOptions);
  5259. $label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
  5260. $endLabel=self::closeTag('label');
  5261. $items[]=strtr($template,array(
  5262. '{input}'=>$option,
  5263. '{beginLabel}'=>$beginLabel,
  5264. '{label}'=>$label,
  5265. '{labelTitle}'=>$labelTitle,
  5266. '{endLabel}'=>$endLabel,
  5267. ));
  5268. }
  5269. if(isset($checkAllLabel))
  5270. {
  5271. $htmlOptions['value']=1;
  5272. $htmlOptions['id']=$id=$baseID.'_all';
  5273. $option=self::checkBox($id,$checkAll,$htmlOptions);
  5274. $beginLabel=self::openTag('label',$labelOptions);
  5275. $label=self::label($checkAllLabel,$id,$labelOptions);
  5276. $endLabel=self::closeTag('label');
  5277. $item=strtr($template,array(
  5278. '{input}'=>$option,
  5279. '{beginLabel}'=>$beginLabel,
  5280. '{label}'=>$label,
  5281. '{labelTitle}'=>$checkAllLabel,
  5282. '{endLabel}'=>$endLabel,
  5283. ));
  5284. if($checkAllLast)
  5285. $items[]=$item;
  5286. else
  5287. array_unshift($items,$item);
  5288. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  5289. $js=<<<EOD
  5290. jQuery('#$id').click(function() {
  5291. jQuery("input[name='$name']").prop('checked', this.checked);
  5292. });
  5293. jQuery("input[name='$name']").click(function() {
  5294. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  5295. });
  5296. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  5297. EOD;
  5298. $cs=Yii::app()->getClientScript();
  5299. $cs->registerCoreScript('jquery');
  5300. $cs->registerScript($id,$js);
  5301. }
  5302. if(empty($container))
  5303. return implode($separator,$items);
  5304. else
  5305. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  5306. }
  5307. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  5308. {
  5309. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  5310. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:self::tag('br');
  5311. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  5312. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  5313. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  5314. unset($htmlOptions['labelOptions']);
  5315. if(isset($htmlOptions['empty']))
  5316. {
  5317. if(!is_array($htmlOptions['empty']))
  5318. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5319. $data=CMap::mergeArray($htmlOptions['empty'],$data);
  5320. unset($htmlOptions['empty']);
  5321. }
  5322. $items=array();
  5323. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  5324. unset($htmlOptions['baseID']);
  5325. $id=0;
  5326. foreach($data as $value=>$labelTitle)
  5327. {
  5328. $checked=!strcmp($value,$select);
  5329. $htmlOptions['value']=$value;
  5330. $htmlOptions['id']=$baseID.'_'.$id++;
  5331. $option=self::radioButton($name,$checked,$htmlOptions);
  5332. $beginLabel=self::openTag('label',$labelOptions);
  5333. $label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
  5334. $endLabel=self::closeTag('label');
  5335. $items[]=strtr($template,array(
  5336. '{input}'=>$option,
  5337. '{beginLabel}'=>$beginLabel,
  5338. '{label}'=>$label,
  5339. '{labelTitle}'=>$labelTitle,
  5340. '{endLabel}'=>$endLabel,
  5341. ));
  5342. }
  5343. if(empty($container))
  5344. return implode($separator,$items);
  5345. else
  5346. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  5347. }
  5348. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  5349. {
  5350. if(!isset($htmlOptions['href']))
  5351. $htmlOptions['href']='#';
  5352. $ajaxOptions['url']=$url;
  5353. $htmlOptions['ajax']=$ajaxOptions;
  5354. self::clientChange('click',$htmlOptions);
  5355. return self::tag('a',$htmlOptions,$text);
  5356. }
  5357. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  5358. {
  5359. $ajaxOptions['url']=$url;
  5360. $htmlOptions['ajax']=$ajaxOptions;
  5361. return self::button($label,$htmlOptions);
  5362. }
  5363. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  5364. {
  5365. $ajaxOptions['type']='POST';
  5366. $htmlOptions['type']='submit';
  5367. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  5368. }
  5369. public static function ajax($options)
  5370. {
  5371. Yii::app()->getClientScript()->registerCoreScript('jquery');
  5372. if(!isset($options['url']))
  5373. $options['url']=new CJavaScriptExpression('location.href');
  5374. else
  5375. $options['url']=self::normalizeUrl($options['url']);
  5376. if(!isset($options['cache']))
  5377. $options['cache']=false;
  5378. if(!isset($options['data']) && isset($options['type']))
  5379. $options['data']=new CJavaScriptExpression('jQuery(this).parents("form").serialize()');
  5380. foreach(array('beforeSend','complete','error','success') as $name)
  5381. {
  5382. if(isset($options[$name]) && !($options[$name] instanceof CJavaScriptExpression))
  5383. $options[$name]=new CJavaScriptExpression($options[$name]);
  5384. }
  5385. if(isset($options['update']))
  5386. {
  5387. if(!isset($options['success']))
  5388. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['update'].'").html(html)}');
  5389. unset($options['update']);
  5390. }
  5391. if(isset($options['replace']))
  5392. {
  5393. if(!isset($options['success']))
  5394. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['replace'].'").replaceWith(html)}');
  5395. unset($options['replace']);
  5396. }
  5397. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  5398. }
  5399. public static function asset($path,$hashByName=false)
  5400. {
  5401. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  5402. }
  5403. public static function normalizeUrl($url)
  5404. {
  5405. if(is_array($url))
  5406. {
  5407. if(isset($url[0]))
  5408. {
  5409. if(($c=Yii::app()->getController())!==null)
  5410. $url=$c->createUrl($url[0],array_splice($url,1));
  5411. else
  5412. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  5413. }
  5414. else
  5415. $url='';
  5416. }
  5417. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  5418. }
  5419. protected static function inputField($type,$name,$value,$htmlOptions)
  5420. {
  5421. $htmlOptions['type']=$type;
  5422. $htmlOptions['value']=$value;
  5423. $htmlOptions['name']=$name;
  5424. if(!isset($htmlOptions['id']))
  5425. $htmlOptions['id']=self::getIdByName($name);
  5426. elseif($htmlOptions['id']===false)
  5427. unset($htmlOptions['id']);
  5428. return self::tag('input',$htmlOptions);
  5429. }
  5430. public static function activeLabel($model,$attribute,$htmlOptions=array())
  5431. {
  5432. $inputName=self::resolveName($model,$attribute);
  5433. if(isset($htmlOptions['for']))
  5434. {
  5435. $for=$htmlOptions['for'];
  5436. unset($htmlOptions['for']);
  5437. }
  5438. else
  5439. $for=self::getIdByName($inputName);
  5440. if(isset($htmlOptions['label']))
  5441. {
  5442. if(($label=$htmlOptions['label'])===false)
  5443. return '';
  5444. unset($htmlOptions['label']);
  5445. }
  5446. else
  5447. $label=$model->getAttributeLabel($attribute);
  5448. if($model->hasErrors($attribute))
  5449. self::addErrorCss($htmlOptions);
  5450. return self::label($label,$for,$htmlOptions);
  5451. }
  5452. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  5453. {
  5454. $realAttribute=$attribute;
  5455. self::resolveName($model,$attribute); // strip off square brackets if any
  5456. if (!isset($htmlOptions['required']))
  5457. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  5458. return self::activeLabel($model,$realAttribute,$htmlOptions);
  5459. }
  5460. public static function activeTextField($model,$attribute,$htmlOptions=array())
  5461. {
  5462. self::resolveNameID($model,$attribute,$htmlOptions);
  5463. self::clientChange('change',$htmlOptions);
  5464. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  5465. }
  5466. public static function activeSearchField($model,$attribute,$htmlOptions=array())
  5467. {
  5468. self::resolveNameID($model,$attribute,$htmlOptions);
  5469. self::clientChange('change',$htmlOptions);
  5470. return self::activeInputField('search',$model,$attribute,$htmlOptions);
  5471. }
  5472. public static function activeUrlField($model,$attribute,$htmlOptions=array())
  5473. {
  5474. self::resolveNameID($model,$attribute,$htmlOptions);
  5475. self::clientChange('change',$htmlOptions);
  5476. return self::activeInputField('url',$model,$attribute,$htmlOptions);
  5477. }
  5478. public static function activeEmailField($model,$attribute,$htmlOptions=array())
  5479. {
  5480. self::resolveNameID($model,$attribute,$htmlOptions);
  5481. self::clientChange('change',$htmlOptions);
  5482. return self::activeInputField('email',$model,$attribute,$htmlOptions);
  5483. }
  5484. public static function activeNumberField($model,$attribute,$htmlOptions=array())
  5485. {
  5486. self::resolveNameID($model,$attribute,$htmlOptions);
  5487. self::clientChange('change',$htmlOptions);
  5488. return self::activeInputField('number',$model,$attribute,$htmlOptions);
  5489. }
  5490. public static function activeRangeField($model,$attribute,$htmlOptions=array())
  5491. {
  5492. self::resolveNameID($model,$attribute,$htmlOptions);
  5493. self::clientChange('change',$htmlOptions);
  5494. return self::activeInputField('range',$model,$attribute,$htmlOptions);
  5495. }
  5496. public static function activeDateField($model,$attribute,$htmlOptions=array())
  5497. {
  5498. self::resolveNameID($model,$attribute,$htmlOptions);
  5499. self::clientChange('change',$htmlOptions);
  5500. return self::activeInputField('date',$model,$attribute,$htmlOptions);
  5501. }
  5502. public static function activeTimeField($model,$attribute,$htmlOptions=array())
  5503. {
  5504. self::resolveNameID($model,$attribute,$htmlOptions);
  5505. self::clientChange('change',$htmlOptions);
  5506. return self::activeInputField('time',$model,$attribute,$htmlOptions);
  5507. }
  5508. public static function activeDateTimeField($model,$attribute,$htmlOptions=array())
  5509. {
  5510. self::resolveNameID($model,$attribute,$htmlOptions);
  5511. self::clientChange('change',$htmlOptions);
  5512. return self::activeInputField('datetime',$model,$attribute,$htmlOptions);
  5513. }
  5514. public static function activeDateTimeLocalField($model,$attribute,$htmlOptions=array())
  5515. {
  5516. self::resolveNameID($model,$attribute,$htmlOptions);
  5517. self::clientChange('change',$htmlOptions);
  5518. return self::activeInputField('datetime-local',$model,$attribute,$htmlOptions);
  5519. }
  5520. public static function activeWeekField($model,$attribute,$htmlOptions=array())
  5521. {
  5522. self::resolveNameID($model,$attribute,$htmlOptions);
  5523. self::clientChange('change',$htmlOptions);
  5524. return self::activeInputField('week',$model,$attribute,$htmlOptions);
  5525. }
  5526. public static function activeColorField($model,$attribute,$htmlOptions=array())
  5527. {
  5528. self::resolveNameID($model,$attribute,$htmlOptions);
  5529. self::clientChange('change',$htmlOptions);
  5530. return self::activeInputField('color',$model,$attribute,$htmlOptions);
  5531. }
  5532. public static function activeTelField($model,$attribute,$htmlOptions=array())
  5533. {
  5534. self::resolveNameID($model,$attribute,$htmlOptions);
  5535. self::clientChange('change',$htmlOptions);
  5536. return self::activeInputField('tel',$model,$attribute,$htmlOptions);
  5537. }
  5538. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  5539. {
  5540. self::resolveNameID($model,$attribute,$htmlOptions);
  5541. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  5542. }
  5543. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  5544. {
  5545. self::resolveNameID($model,$attribute,$htmlOptions);
  5546. self::clientChange('change',$htmlOptions);
  5547. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  5548. }
  5549. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  5550. {
  5551. self::resolveNameID($model,$attribute,$htmlOptions);
  5552. self::clientChange('change',$htmlOptions);
  5553. if($model->hasErrors($attribute))
  5554. self::addErrorCss($htmlOptions);
  5555. if(isset($htmlOptions['value']))
  5556. {
  5557. $text=$htmlOptions['value'];
  5558. unset($htmlOptions['value']);
  5559. }
  5560. else
  5561. $text=self::resolveValue($model,$attribute);
  5562. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  5563. }
  5564. public static function activeFileField($model,$attribute,$htmlOptions=array())
  5565. {
  5566. self::resolveNameID($model,$attribute,$htmlOptions);
  5567. // add a hidden field so that if a model only has a file field, we can
  5568. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  5569. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5570. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  5571. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  5572. }
  5573. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  5574. {
  5575. self::resolveNameID($model,$attribute,$htmlOptions);
  5576. if(!isset($htmlOptions['value']))
  5577. $htmlOptions['value']=1;
  5578. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5579. $htmlOptions['checked']='checked';
  5580. self::clientChange('click',$htmlOptions);
  5581. if(array_key_exists('uncheckValue',$htmlOptions))
  5582. {
  5583. $uncheck=$htmlOptions['uncheckValue'];
  5584. unset($htmlOptions['uncheckValue']);
  5585. }
  5586. else
  5587. $uncheck='0';
  5588. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5589. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5590. // add a hidden field so that if the radio button is not selected, it still submits a value
  5591. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  5592. }
  5593. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  5594. {
  5595. self::resolveNameID($model,$attribute,$htmlOptions);
  5596. if(!isset($htmlOptions['value']))
  5597. $htmlOptions['value']=1;
  5598. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5599. $htmlOptions['checked']='checked';
  5600. self::clientChange('click',$htmlOptions);
  5601. if(array_key_exists('uncheckValue',$htmlOptions))
  5602. {
  5603. $uncheck=$htmlOptions['uncheckValue'];
  5604. unset($htmlOptions['uncheckValue']);
  5605. }
  5606. else
  5607. $uncheck='0';
  5608. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5609. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5610. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  5611. }
  5612. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  5613. {
  5614. self::resolveNameID($model,$attribute,$htmlOptions);
  5615. $selection=self::resolveValue($model,$attribute);
  5616. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  5617. self::clientChange('change',$htmlOptions);
  5618. if($model->hasErrors($attribute))
  5619. self::addErrorCss($htmlOptions);
  5620. $hidden='';
  5621. if(!empty($htmlOptions['multiple']))
  5622. {
  5623. if(substr($htmlOptions['name'],-2)!=='[]')
  5624. $htmlOptions['name'].='[]';
  5625. if(isset($htmlOptions['unselectValue']))
  5626. {
  5627. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5628. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  5629. unset($htmlOptions['unselectValue']);
  5630. }
  5631. }
  5632. return $hidden . self::tag('select',$htmlOptions,$options);
  5633. }
  5634. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  5635. {
  5636. if(!isset($htmlOptions['size']))
  5637. $htmlOptions['size']=4;
  5638. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  5639. }
  5640. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  5641. {
  5642. self::resolveNameID($model,$attribute,$htmlOptions);
  5643. $selection=self::resolveValue($model,$attribute);
  5644. if($model->hasErrors($attribute))
  5645. self::addErrorCss($htmlOptions);
  5646. $name=$htmlOptions['name'];
  5647. unset($htmlOptions['name']);
  5648. if(array_key_exists('uncheckValue',$htmlOptions))
  5649. {
  5650. $uncheck=$htmlOptions['uncheckValue'];
  5651. unset($htmlOptions['uncheckValue']);
  5652. }
  5653. else
  5654. $uncheck='';
  5655. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5656. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5657. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  5658. }
  5659. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  5660. {
  5661. self::resolveNameID($model,$attribute,$htmlOptions);
  5662. $selection=self::resolveValue($model,$attribute);
  5663. if($model->hasErrors($attribute))
  5664. self::addErrorCss($htmlOptions);
  5665. $name=$htmlOptions['name'];
  5666. unset($htmlOptions['name']);
  5667. if(array_key_exists('uncheckValue',$htmlOptions))
  5668. {
  5669. $uncheck=$htmlOptions['uncheckValue'];
  5670. unset($htmlOptions['uncheckValue']);
  5671. }
  5672. else
  5673. $uncheck='';
  5674. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5675. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5676. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  5677. }
  5678. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  5679. {
  5680. $content='';
  5681. if(!is_array($model))
  5682. $model=array($model);
  5683. if(isset($htmlOptions['firstError']))
  5684. {
  5685. $firstError=$htmlOptions['firstError'];
  5686. unset($htmlOptions['firstError']);
  5687. }
  5688. else
  5689. $firstError=false;
  5690. foreach($model as $m)
  5691. {
  5692. foreach($m->getErrors() as $errors)
  5693. {
  5694. foreach($errors as $error)
  5695. {
  5696. if($error!='')
  5697. $content.="<li>$error</li>\n";
  5698. if($firstError)
  5699. break;
  5700. }
  5701. }
  5702. }
  5703. if($content!=='')
  5704. {
  5705. if($header===null)
  5706. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5707. if(!isset($htmlOptions['class']))
  5708. $htmlOptions['class']=self::$errorSummaryCss;
  5709. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5710. }
  5711. else
  5712. return '';
  5713. }
  5714. public static function error($model,$attribute,$htmlOptions=array())
  5715. {
  5716. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5717. $error=$model->getError($attribute);
  5718. if($error!='')
  5719. {
  5720. if(!isset($htmlOptions['class']))
  5721. $htmlOptions['class']=self::$errorMessageCss;
  5722. return self::tag(self::$errorContainerTag,$htmlOptions,$error);
  5723. }
  5724. else
  5725. return '';
  5726. }
  5727. public static function listData($models,$valueField,$textField,$groupField='')
  5728. {
  5729. $listData=array();
  5730. if($groupField==='')
  5731. {
  5732. foreach($models as $model)
  5733. {
  5734. $value=self::value($model,$valueField);
  5735. $text=self::value($model,$textField);
  5736. $listData[$value]=$text;
  5737. }
  5738. }
  5739. else
  5740. {
  5741. foreach($models as $model)
  5742. {
  5743. $group=self::value($model,$groupField);
  5744. $value=self::value($model,$valueField);
  5745. $text=self::value($model,$textField);
  5746. if($group===null)
  5747. $listData[$value]=$text;
  5748. else
  5749. $listData[$group][$value]=$text;
  5750. }
  5751. }
  5752. return $listData;
  5753. }
  5754. public static function value($model,$attribute,$defaultValue=null)
  5755. {
  5756. if(is_scalar($attribute) || $attribute===null)
  5757. foreach(explode('.',$attribute) as $name)
  5758. {
  5759. if(is_object($model) && isset($model->$name))
  5760. $model=$model->$name;
  5761. elseif(is_array($model) && isset($model[$name]))
  5762. $model=$model[$name];
  5763. else
  5764. return $defaultValue;
  5765. }
  5766. else
  5767. return call_user_func($attribute,$model);
  5768. return $model;
  5769. }
  5770. public static function getIdByName($name)
  5771. {
  5772. return str_replace(array('[]','][','[',']',' '),array('','_','_','','_'),$name);
  5773. }
  5774. public static function activeId($model,$attribute)
  5775. {
  5776. return self::getIdByName(self::activeName($model,$attribute));
  5777. }
  5778. public static function modelName($model)
  5779. {
  5780. if(is_callable(self::$_modelNameConverter))
  5781. return call_user_func(self::$_modelNameConverter,$model);
  5782. $className=is_object($model) ? get_class($model) : (string)$model;
  5783. return trim(str_replace('\\','_',$className),'_');
  5784. }
  5785. public static function setModelNameConverter($converter)
  5786. {
  5787. if(is_callable($converter))
  5788. self::$_modelNameConverter=$converter;
  5789. elseif($converter===null)
  5790. self::$_modelNameConverter=null;
  5791. else
  5792. throw new CException(Yii::t('yii','The $converter argument must be a valid callback or null.'));
  5793. }
  5794. public static function activeName($model,$attribute)
  5795. {
  5796. $a=$attribute; // because the attribute name may be changed by resolveName
  5797. return self::resolveName($model,$a);
  5798. }
  5799. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5800. {
  5801. $htmlOptions['type']=$type;
  5802. if($type==='text'||$type==='password'||$type==='color'||$type==='date'||$type==='datetime'||
  5803. $type==='datetime-local'||$type==='email'||$type==='month'||$type==='number'||$type==='range'||
  5804. $type==='search'||$type==='tel'||$type==='time'||$type==='url'||$type==='week')
  5805. {
  5806. if(!isset($htmlOptions['maxlength']))
  5807. {
  5808. foreach($model->getValidators($attribute) as $validator)
  5809. {
  5810. if($validator instanceof CStringValidator && $validator->max!==null)
  5811. {
  5812. $htmlOptions['maxlength']=$validator->max;
  5813. break;
  5814. }
  5815. }
  5816. }
  5817. elseif($htmlOptions['maxlength']===false)
  5818. unset($htmlOptions['maxlength']);
  5819. }
  5820. if($type==='file')
  5821. unset($htmlOptions['value']);
  5822. elseif(!isset($htmlOptions['value']))
  5823. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5824. if($model->hasErrors($attribute))
  5825. self::addErrorCss($htmlOptions);
  5826. return self::tag('input',$htmlOptions);
  5827. }
  5828. public static function listOptions($selection,$listData,&$htmlOptions)
  5829. {
  5830. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5831. $content='';
  5832. if(isset($htmlOptions['prompt']))
  5833. {
  5834. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;','>'=>'&gt;'))."</option>\n";
  5835. unset($htmlOptions['prompt']);
  5836. }
  5837. if(isset($htmlOptions['empty']))
  5838. {
  5839. if(!is_array($htmlOptions['empty']))
  5840. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5841. foreach($htmlOptions['empty'] as $value=>$label)
  5842. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;','>'=>'&gt;'))."</option>\n";
  5843. unset($htmlOptions['empty']);
  5844. }
  5845. if(isset($htmlOptions['options']))
  5846. {
  5847. $options=$htmlOptions['options'];
  5848. unset($htmlOptions['options']);
  5849. }
  5850. else
  5851. $options=array();
  5852. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  5853. if(is_array($selection))
  5854. {
  5855. foreach($selection as $i=>$item)
  5856. {
  5857. if(is_object($item))
  5858. $selection[$i]=$item->$key;
  5859. }
  5860. }
  5861. elseif(is_object($selection))
  5862. $selection=$selection->$key;
  5863. foreach($listData as $key=>$value)
  5864. {
  5865. if(is_array($value))
  5866. {
  5867. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  5868. $dummy=array('options'=>$options);
  5869. if(isset($htmlOptions['encode']))
  5870. $dummy['encode']=$htmlOptions['encode'];
  5871. $content.=self::listOptions($selection,$value,$dummy);
  5872. $content.='</optgroup>'."\n";
  5873. }
  5874. else
  5875. {
  5876. $attributes=array('value'=>(string)$key,'encode'=>!$raw);
  5877. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  5878. $attributes['selected']='selected';
  5879. if(isset($options[$key]))
  5880. $attributes=array_merge($attributes,$options[$key]);
  5881. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  5882. }
  5883. }
  5884. unset($htmlOptions['key']);
  5885. return $content;
  5886. }
  5887. protected static function clientChange($event,&$htmlOptions)
  5888. {
  5889. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  5890. return;
  5891. if(isset($htmlOptions['live']))
  5892. {
  5893. $live=$htmlOptions['live'];
  5894. unset($htmlOptions['live']);
  5895. }
  5896. else
  5897. $live = self::$liveEvents;
  5898. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  5899. $return='return true';
  5900. else
  5901. $return='return false';
  5902. if(isset($htmlOptions['on'.$event]))
  5903. {
  5904. $handler=trim($htmlOptions['on'.$event],';').';';
  5905. unset($htmlOptions['on'.$event]);
  5906. }
  5907. else
  5908. $handler='';
  5909. if(isset($htmlOptions['id']))
  5910. $id=$htmlOptions['id'];
  5911. else
  5912. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  5913. $cs=Yii::app()->getClientScript();
  5914. $cs->registerCoreScript('jquery');
  5915. if(isset($htmlOptions['submit']))
  5916. {
  5917. $cs->registerCoreScript('yii');
  5918. $request=Yii::app()->getRequest();
  5919. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  5920. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  5921. if(isset($htmlOptions['params']))
  5922. $params=CJavaScript::encode($htmlOptions['params']);
  5923. else
  5924. $params='{}';
  5925. if($htmlOptions['submit']!=='')
  5926. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  5927. else
  5928. $url='';
  5929. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  5930. }
  5931. if(isset($htmlOptions['ajax']))
  5932. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  5933. if(isset($htmlOptions['confirm']))
  5934. {
  5935. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  5936. if($handler!=='')
  5937. $handler="if($confirm) {".$handler."} else return false;";
  5938. else
  5939. $handler="return $confirm;";
  5940. }
  5941. if($live)
  5942. $cs->registerScript('Yii.CHtml.#' . $id,"jQuery('body').on('$event','#$id',function(){{$handler}});");
  5943. else
  5944. $cs->registerScript('Yii.CHtml.#' . $id,"jQuery('#$id').on('$event', function(){{$handler}});");
  5945. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  5946. }
  5947. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  5948. {
  5949. if(!isset($htmlOptions['name']))
  5950. $htmlOptions['name']=self::resolveName($model,$attribute);
  5951. if(!isset($htmlOptions['id']))
  5952. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  5953. elseif($htmlOptions['id']===false)
  5954. unset($htmlOptions['id']);
  5955. }
  5956. public static function resolveName($model,&$attribute)
  5957. {
  5958. $modelName=self::modelName($model);
  5959. if(($pos=strpos($attribute,'['))!==false)
  5960. {
  5961. if($pos!==0) // e.g. name[a][b]
  5962. return $modelName.'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5963. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5964. {
  5965. $sub=substr($attribute,0,$pos+1);
  5966. $attribute=substr($attribute,$pos+1);
  5967. return $modelName.$sub.'['.$attribute.']';
  5968. }
  5969. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5970. {
  5971. $name=$modelName.'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5972. $attribute=$matches[1];
  5973. return $name;
  5974. }
  5975. }
  5976. return $modelName.'['.$attribute.']';
  5977. }
  5978. public static function resolveValue($model,$attribute)
  5979. {
  5980. if(($pos=strpos($attribute,'['))!==false)
  5981. {
  5982. if($pos===0) // [a]name[b][c], should ignore [a]
  5983. {
  5984. if(preg_match('/\](\w+(\[.+)?)/',$attribute,$matches))
  5985. $attribute=$matches[1]; // we get: name[b][c]
  5986. if(($pos=strpos($attribute,'['))===false)
  5987. return $model->$attribute;
  5988. }
  5989. $name=substr($attribute,0,$pos);
  5990. $value=$model->$name;
  5991. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5992. {
  5993. if((is_array($value) || $value instanceof ArrayAccess) && isset($value[$id]))
  5994. $value=$value[$id];
  5995. else
  5996. return null;
  5997. }
  5998. return $value;
  5999. }
  6000. else
  6001. return $model->$attribute;
  6002. }
  6003. protected static function addErrorCss(&$htmlOptions)
  6004. {
  6005. if(empty(self::$errorCss))
  6006. return;
  6007. if(isset($htmlOptions['class']))
  6008. $htmlOptions['class'].=' '.self::$errorCss;
  6009. else
  6010. $htmlOptions['class']=self::$errorCss;
  6011. }
  6012. public static function renderAttributes($htmlOptions)
  6013. {
  6014. static $specialAttributes=array(
  6015. 'autofocus'=>1,
  6016. 'autoplay'=>1,
  6017. 'async'=>1,
  6018. 'checked'=>1,
  6019. 'controls'=>1,
  6020. 'declare'=>1,
  6021. 'default'=>1,
  6022. 'defer'=>1,
  6023. 'disabled'=>1,
  6024. 'formnovalidate'=>1,
  6025. 'hidden'=>1,
  6026. 'ismap'=>1,
  6027. 'itemscope'=>1,
  6028. 'loop'=>1,
  6029. 'multiple'=>1,
  6030. 'muted'=>1,
  6031. 'nohref'=>1,
  6032. 'noresize'=>1,
  6033. 'novalidate'=>1,
  6034. 'open'=>1,
  6035. 'readonly'=>1,
  6036. 'required'=>1,
  6037. 'reversed'=>1,
  6038. 'scoped'=>1,
  6039. 'seamless'=>1,
  6040. 'selected'=>1,
  6041. 'typemustmatch'=>1,
  6042. );
  6043. if($htmlOptions===array())
  6044. return '';
  6045. $html='';
  6046. if(isset($htmlOptions['encode']))
  6047. {
  6048. $raw=!$htmlOptions['encode'];
  6049. unset($htmlOptions['encode']);
  6050. }
  6051. else
  6052. $raw=false;
  6053. foreach($htmlOptions as $name=>$value)
  6054. {
  6055. if(isset($specialAttributes[$name]))
  6056. {
  6057. if($value===false && $name==='async') {
  6058. $html .= ' ' . $name.'="false"';
  6059. }
  6060. elseif($value)
  6061. {
  6062. $html .= ' ' . $name;
  6063. if(self::$renderSpecialAttributesValue)
  6064. $html .= '="' . $name . '"';
  6065. }
  6066. }
  6067. elseif($value!==null)
  6068. $html .= ' ' . $name . '="' . ($raw ? $value : self::encode($value)) . '"';
  6069. }
  6070. return $html;
  6071. }
  6072. }
  6073. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  6074. {
  6075. public $enableSkin=false;
  6076. public $widgets=array();
  6077. public $skinnableWidgets;
  6078. public $skinPath;
  6079. private $_skins=array(); // class name, skin name, property name => value
  6080. public function init()
  6081. {
  6082. parent::init();
  6083. if($this->enableSkin && $this->skinPath===null)
  6084. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  6085. }
  6086. public function createWidget($owner,$className,$properties=array())
  6087. {
  6088. $className=Yii::import($className,true);
  6089. $widget=new $className($owner);
  6090. if(isset($this->widgets[$className]))
  6091. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  6092. if($this->enableSkin)
  6093. {
  6094. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  6095. {
  6096. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  6097. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  6098. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  6099. }
  6100. }
  6101. foreach($properties as $name=>$value)
  6102. $widget->$name=$value;
  6103. return $widget;
  6104. }
  6105. protected function getSkin($className,$skinName)
  6106. {
  6107. if(!isset($this->_skins[$className][$skinName]))
  6108. {
  6109. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  6110. if(is_file($skinFile))
  6111. $this->_skins[$className]=require($skinFile);
  6112. else
  6113. $this->_skins[$className]=array();
  6114. if(($theme=Yii::app()->getTheme())!==null)
  6115. {
  6116. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  6117. if(is_file($skinFile))
  6118. {
  6119. $skins=require($skinFile);
  6120. foreach($skins as $name=>$skin)
  6121. $this->_skins[$className][$name]=$skin;
  6122. }
  6123. }
  6124. if(!isset($this->_skins[$className][$skinName]))
  6125. $this->_skins[$className][$skinName]=array();
  6126. }
  6127. return $this->_skins[$className][$skinName];
  6128. }
  6129. }
  6130. class CWidget extends CBaseController
  6131. {
  6132. public $actionPrefix;
  6133. public $skin='default';
  6134. private static $_viewPaths;
  6135. private static $_counter=0;
  6136. private $_id;
  6137. private $_owner;
  6138. public static function actions()
  6139. {
  6140. return array();
  6141. }
  6142. public function __construct($owner=null)
  6143. {
  6144. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  6145. }
  6146. public function getOwner()
  6147. {
  6148. return $this->_owner;
  6149. }
  6150. public function getId($autoGenerate=true)
  6151. {
  6152. if($this->_id!==null)
  6153. return $this->_id;
  6154. elseif($autoGenerate)
  6155. return $this->_id='yw'.self::$_counter++;
  6156. }
  6157. public function setId($value)
  6158. {
  6159. $this->_id=$value;
  6160. }
  6161. public function getController()
  6162. {
  6163. if($this->_owner instanceof CController)
  6164. return $this->_owner;
  6165. else
  6166. return Yii::app()->getController();
  6167. }
  6168. public function init()
  6169. {
  6170. }
  6171. public function run()
  6172. {
  6173. }
  6174. public function getViewPath($checkTheme=false)
  6175. {
  6176. $className=get_class($this);
  6177. $scope=$checkTheme?'theme':'local';
  6178. if(isset(self::$_viewPaths[$className][$scope]))
  6179. return self::$_viewPaths[$className][$scope];
  6180. else
  6181. {
  6182. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  6183. {
  6184. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  6185. if(strpos($className,'\\')!==false) // namespaced class
  6186. $path.=str_replace('\\','_',ltrim($className,'\\'));
  6187. else
  6188. $path.=$className;
  6189. if(is_dir($path))
  6190. return self::$_viewPaths[$className]['theme']=$path;
  6191. }
  6192. $class=new ReflectionClass($className);
  6193. return self::$_viewPaths[$className]['local']=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  6194. }
  6195. }
  6196. public function getViewFile($viewName)
  6197. {
  6198. if(($renderer=Yii::app()->getViewRenderer())!==null)
  6199. $extension=$renderer->fileExtension;
  6200. else
  6201. $extension='.php';
  6202. if(strpos($viewName,'.')) // a path alias
  6203. $viewFile=Yii::getPathOfAlias($viewName);
  6204. else
  6205. {
  6206. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  6207. if(is_file($viewFile.$extension))
  6208. return Yii::app()->findLocalizedFile($viewFile.$extension);
  6209. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  6210. return Yii::app()->findLocalizedFile($viewFile.'.php');
  6211. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  6212. }
  6213. if(is_file($viewFile.$extension))
  6214. return Yii::app()->findLocalizedFile($viewFile.$extension);
  6215. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  6216. return Yii::app()->findLocalizedFile($viewFile.'.php');
  6217. else
  6218. return false;
  6219. }
  6220. public function render($view,$data=null,$return=false)
  6221. {
  6222. if(($viewFile=$this->getViewFile($view))!==false)
  6223. return $this->renderFile($viewFile,$data,$return);
  6224. else
  6225. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  6226. array('{widget}'=>get_class($this), '{view}'=>$view)));
  6227. }
  6228. }
  6229. class CClientScript extends CApplicationComponent
  6230. {
  6231. const POS_HEAD=0;
  6232. const POS_BEGIN=1;
  6233. const POS_END=2;
  6234. const POS_LOAD=3;
  6235. const POS_READY=4;
  6236. public $enableJavaScript=true;
  6237. public $scriptMap=array();
  6238. public $packages=array();
  6239. public $corePackages;
  6240. public $scripts=array();
  6241. protected $cssFiles=array();
  6242. protected $scriptFiles=array();
  6243. protected $metaTags=array();
  6244. protected $linkTags=array();
  6245. protected $css=array();
  6246. protected $hasScripts=false;
  6247. protected $coreScripts=array();
  6248. public $coreScriptPosition=self::POS_HEAD;
  6249. public $defaultScriptFilePosition=self::POS_HEAD;
  6250. public $defaultScriptPosition=self::POS_READY;
  6251. private $_baseUrl;
  6252. public function reset()
  6253. {
  6254. $this->hasScripts=false;
  6255. $this->coreScripts=array();
  6256. $this->cssFiles=array();
  6257. $this->css=array();
  6258. $this->scriptFiles=array();
  6259. $this->scripts=array();
  6260. $this->metaTags=array();
  6261. $this->linkTags=array();
  6262. $this->recordCachingAction('clientScript','reset',array());
  6263. }
  6264. public function render(&$output)
  6265. {
  6266. if(!$this->hasScripts)
  6267. return;
  6268. $this->renderCoreScripts();
  6269. if(!empty($this->scriptMap))
  6270. $this->remapScripts();
  6271. $this->unifyScripts();
  6272. $this->renderHead($output);
  6273. if($this->enableJavaScript)
  6274. {
  6275. $this->renderBodyBegin($output);
  6276. $this->renderBodyEnd($output);
  6277. }
  6278. }
  6279. protected function unifyScripts()
  6280. {
  6281. if(!$this->enableJavaScript)
  6282. return;
  6283. $map=array();
  6284. if(isset($this->scriptFiles[self::POS_HEAD]))
  6285. $map=$this->scriptFiles[self::POS_HEAD];
  6286. if(isset($this->scriptFiles[self::POS_BEGIN]))
  6287. {
  6288. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile=>$scriptFileValue)
  6289. {
  6290. if(isset($map[$scriptFile]))
  6291. unset($this->scriptFiles[self::POS_BEGIN][$scriptFile]);
  6292. else
  6293. $map[$scriptFile]=true;
  6294. }
  6295. }
  6296. if(isset($this->scriptFiles[self::POS_END]))
  6297. {
  6298. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  6299. {
  6300. if(isset($map[$key]))
  6301. unset($this->scriptFiles[self::POS_END][$key]);
  6302. }
  6303. }
  6304. }
  6305. protected function remapScripts()
  6306. {
  6307. $cssFiles=array();
  6308. foreach($this->cssFiles as $url=>$media)
  6309. {
  6310. $name=basename($url);
  6311. if(isset($this->scriptMap[$name]))
  6312. {
  6313. if($this->scriptMap[$name]!==false)
  6314. $cssFiles[$this->scriptMap[$name]]=$media;
  6315. }
  6316. elseif(isset($this->scriptMap['*.css']))
  6317. {
  6318. if($this->scriptMap['*.css']!==false)
  6319. $cssFiles[$this->scriptMap['*.css']]=$media;
  6320. }
  6321. else
  6322. $cssFiles[$url]=$media;
  6323. }
  6324. $this->cssFiles=$cssFiles;
  6325. $jsFiles=array();
  6326. foreach($this->scriptFiles as $position=>$scriptFiles)
  6327. {
  6328. $jsFiles[$position]=array();
  6329. foreach($scriptFiles as $scriptFile=>$scriptFileValue)
  6330. {
  6331. $name=basename($scriptFile);
  6332. if(isset($this->scriptMap[$name]))
  6333. {
  6334. if($this->scriptMap[$name]!==false)
  6335. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  6336. }
  6337. elseif(isset($this->scriptMap['*.js']))
  6338. {
  6339. if($this->scriptMap['*.js']!==false)
  6340. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  6341. }
  6342. else
  6343. $jsFiles[$position][$scriptFile]=$scriptFileValue;
  6344. }
  6345. }
  6346. $this->scriptFiles=$jsFiles;
  6347. }
  6348. protected function renderScriptBatch(array $scripts)
  6349. {
  6350. $html = '';
  6351. $scriptBatches = array();
  6352. foreach($scripts as $scriptValue)
  6353. {
  6354. if(is_array($scriptValue))
  6355. {
  6356. $scriptContent = $scriptValue['content'];
  6357. unset($scriptValue['content']);
  6358. $scriptHtmlOptions = $scriptValue;
  6359. ksort($scriptHtmlOptions);
  6360. }
  6361. else
  6362. {
  6363. $scriptContent = $scriptValue;
  6364. $scriptHtmlOptions = array();
  6365. }
  6366. $key=serialize($scriptHtmlOptions);
  6367. $scriptBatches[$key]['htmlOptions']=$scriptHtmlOptions;
  6368. $scriptBatches[$key]['scripts'][]=$scriptContent;
  6369. }
  6370. foreach($scriptBatches as $scriptBatch)
  6371. if(!empty($scriptBatch['scripts']))
  6372. $html.=CHtml::script(implode("\n",$scriptBatch['scripts']),$scriptBatch['htmlOptions'])."\n";
  6373. return $html;
  6374. }
  6375. public function renderCoreScripts()
  6376. {
  6377. if($this->coreScripts===null)
  6378. return;
  6379. $cssFiles=array();
  6380. $jsFiles=array();
  6381. foreach($this->coreScripts as $name=>$package)
  6382. {
  6383. $baseUrl=$this->getPackageBaseUrl($name);
  6384. if(!empty($package['js']))
  6385. {
  6386. foreach($package['js'] as $js)
  6387. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  6388. }
  6389. if(!empty($package['css']))
  6390. {
  6391. foreach($package['css'] as $css)
  6392. $cssFiles[$baseUrl.'/'.$css]='';
  6393. }
  6394. }
  6395. // merge in place
  6396. if($cssFiles!==array())
  6397. {
  6398. foreach($this->cssFiles as $cssFile=>$media)
  6399. $cssFiles[$cssFile]=$media;
  6400. $this->cssFiles=$cssFiles;
  6401. }
  6402. if($jsFiles!==array())
  6403. {
  6404. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  6405. {
  6406. foreach($this->scriptFiles[$this->coreScriptPosition] as $url => $value)
  6407. $jsFiles[$url]=$value;
  6408. }
  6409. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  6410. }
  6411. }
  6412. public function renderHead(&$output)
  6413. {
  6414. $html='';
  6415. foreach($this->metaTags as $meta)
  6416. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  6417. foreach($this->linkTags as $link)
  6418. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  6419. foreach($this->cssFiles as $url=>$media)
  6420. $html.=CHtml::cssFile($url,$media)."\n";
  6421. foreach($this->css as $css)
  6422. $html.=CHtml::css($css[0],$css[1])."\n";
  6423. if($this->enableJavaScript)
  6424. {
  6425. if(isset($this->scriptFiles[self::POS_HEAD]))
  6426. {
  6427. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFileValueUrl=>$scriptFileValue)
  6428. {
  6429. if(is_array($scriptFileValue))
  6430. $html.=CHtml::scriptFile($scriptFileValueUrl,$scriptFileValue)."\n";
  6431. else
  6432. $html.=CHtml::scriptFile($scriptFileValueUrl)."\n";
  6433. }
  6434. }
  6435. if(isset($this->scripts[self::POS_HEAD]))
  6436. $html.=$this->renderScriptBatch($this->scripts[self::POS_HEAD]);
  6437. }
  6438. if($html!=='')
  6439. {
  6440. $count=0;
  6441. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  6442. if($count)
  6443. $output=str_replace('<###head###>',$html,$output);
  6444. else
  6445. $output=$html.$output;
  6446. }
  6447. }
  6448. public function renderBodyBegin(&$output)
  6449. {
  6450. $html='';
  6451. if(isset($this->scriptFiles[self::POS_BEGIN]))
  6452. {
  6453. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFileUrl=>$scriptFileValue)
  6454. {
  6455. if(is_array($scriptFileValue))
  6456. $html.=CHtml::scriptFile($scriptFileUrl,$scriptFileValue)."\n";
  6457. else
  6458. $html.=CHtml::scriptFile($scriptFileUrl)."\n";
  6459. }
  6460. }
  6461. if(isset($this->scripts[self::POS_BEGIN]))
  6462. $html.=$this->renderScriptBatch($this->scripts[self::POS_BEGIN]);
  6463. if($html!=='')
  6464. {
  6465. $count=0;
  6466. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  6467. if($count)
  6468. $output=str_replace('<###begin###>',$html,$output);
  6469. else
  6470. $output=$html.$output;
  6471. }
  6472. }
  6473. public function renderBodyEnd(&$output)
  6474. {
  6475. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  6476. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  6477. return;
  6478. $fullPage=0;
  6479. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  6480. $html='';
  6481. if(isset($this->scriptFiles[self::POS_END]))
  6482. {
  6483. foreach($this->scriptFiles[self::POS_END] as $scriptFileUrl=>$scriptFileValue)
  6484. {
  6485. if(is_array($scriptFileValue))
  6486. $html.=CHtml::scriptFile($scriptFileUrl,$scriptFileValue)."\n";
  6487. else
  6488. $html.=CHtml::scriptFile($scriptFileUrl)."\n";
  6489. }
  6490. }
  6491. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  6492. if(isset($this->scripts[self::POS_READY]))
  6493. {
  6494. if($fullPage)
  6495. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  6496. else
  6497. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  6498. }
  6499. if(isset($this->scripts[self::POS_LOAD]))
  6500. {
  6501. if($fullPage)
  6502. $scripts[]="jQuery(window).on('load',function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  6503. else
  6504. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  6505. }
  6506. if(!empty($scripts))
  6507. $html.=$this->renderScriptBatch($scripts);
  6508. if($fullPage)
  6509. $output=str_replace('<###end###>',$html,$output);
  6510. else
  6511. $output=$output.$html;
  6512. }
  6513. public function getCoreScriptUrl()
  6514. {
  6515. if($this->_baseUrl!==null)
  6516. return $this->_baseUrl;
  6517. else
  6518. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  6519. }
  6520. public function setCoreScriptUrl($value)
  6521. {
  6522. $this->_baseUrl=$value;
  6523. }
  6524. public function getPackageBaseUrl($name)
  6525. {
  6526. if(!isset($this->coreScripts[$name]))
  6527. return false;
  6528. $package=$this->coreScripts[$name];
  6529. if(isset($package['baseUrl']))
  6530. {
  6531. $baseUrl=$package['baseUrl'];
  6532. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  6533. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  6534. $baseUrl=rtrim($baseUrl,'/');
  6535. }
  6536. elseif(isset($package['basePath']))
  6537. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  6538. else
  6539. $baseUrl=$this->getCoreScriptUrl();
  6540. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  6541. }
  6542. public function registerPackage($name)
  6543. {
  6544. return $this->registerCoreScript($name);
  6545. }
  6546. public function registerCoreScript($name)
  6547. {
  6548. if(isset($this->coreScripts[$name]))
  6549. return $this;
  6550. if(isset($this->packages[$name]))
  6551. $package=$this->packages[$name];
  6552. else
  6553. {
  6554. if($this->corePackages===null)
  6555. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  6556. if(isset($this->corePackages[$name]))
  6557. $package=$this->corePackages[$name];
  6558. }
  6559. if(isset($package))
  6560. {
  6561. if(!empty($package['depends']))
  6562. {
  6563. foreach($package['depends'] as $p)
  6564. $this->registerCoreScript($p);
  6565. }
  6566. $this->coreScripts[$name]=$package;
  6567. $this->hasScripts=true;
  6568. $params=func_get_args();
  6569. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  6570. }
  6571. elseif(YII_DEBUG)
  6572. throw new CException('There is no CClientScript package: '.$name);
  6573. else
  6574. Yii::log('There is no CClientScript package: '.$name,CLogger::LEVEL_WARNING,'system.web.CClientScript');
  6575. return $this;
  6576. }
  6577. public function registerCssFile($url,$media='')
  6578. {
  6579. $this->hasScripts=true;
  6580. $this->cssFiles[$url]=$media;
  6581. $params=func_get_args();
  6582. $this->recordCachingAction('clientScript','registerCssFile',$params);
  6583. return $this;
  6584. }
  6585. public function registerCss($id,$css,$media='')
  6586. {
  6587. $this->hasScripts=true;
  6588. $this->css[$id]=array($css,$media);
  6589. $params=func_get_args();
  6590. $this->recordCachingAction('clientScript','registerCss',$params);
  6591. return $this;
  6592. }
  6593. public function registerScriptFile($url,$position=null,array $htmlOptions=array())
  6594. {
  6595. if($position===null)
  6596. $position=$this->defaultScriptFilePosition;
  6597. $this->hasScripts=true;
  6598. if(empty($htmlOptions))
  6599. $value=$url;
  6600. else
  6601. {
  6602. $value=$htmlOptions;
  6603. $value['src']=$url;
  6604. }
  6605. $this->scriptFiles[$position][$url]=$value;
  6606. $params=func_get_args();
  6607. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  6608. return $this;
  6609. }
  6610. public function registerScript($id,$script,$position=null,array $htmlOptions=array())
  6611. {
  6612. if($position===null)
  6613. $position=$this->defaultScriptPosition;
  6614. $this->hasScripts=true;
  6615. if(empty($htmlOptions))
  6616. $scriptValue=$script;
  6617. else
  6618. {
  6619. if($position==self::POS_LOAD || $position==self::POS_READY)
  6620. throw new CException(Yii::t('yii','Script HTML options are not allowed for "CClientScript::POS_LOAD" and "CClientScript::POS_READY".'));
  6621. $scriptValue=$htmlOptions;
  6622. $scriptValue['content']=$script;
  6623. }
  6624. $this->scripts[$position][$id]=$scriptValue;
  6625. if($position===self::POS_READY || $position===self::POS_LOAD)
  6626. $this->registerCoreScript('jquery');
  6627. $params=func_get_args();
  6628. $this->recordCachingAction('clientScript','registerScript',$params);
  6629. return $this;
  6630. }
  6631. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array(),$id=null)
  6632. {
  6633. $this->hasScripts=true;
  6634. if($name!==null)
  6635. $options['name']=$name;
  6636. if($httpEquiv!==null)
  6637. $options['http-equiv']=$httpEquiv;
  6638. $options['content']=$content;
  6639. $this->metaTags[null===$id?count($this->metaTags):$id]=$options;
  6640. $params=func_get_args();
  6641. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  6642. return $this;
  6643. }
  6644. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  6645. {
  6646. $this->hasScripts=true;
  6647. if($relation!==null)
  6648. $options['rel']=$relation;
  6649. if($type!==null)
  6650. $options['type']=$type;
  6651. if($href!==null)
  6652. $options['href']=$href;
  6653. if($media!==null)
  6654. $options['media']=$media;
  6655. $this->linkTags[serialize($options)]=$options;
  6656. $params=func_get_args();
  6657. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  6658. return $this;
  6659. }
  6660. public function isCssFileRegistered($url)
  6661. {
  6662. return isset($this->cssFiles[$url]);
  6663. }
  6664. public function isCssRegistered($id)
  6665. {
  6666. return isset($this->css[$id]);
  6667. }
  6668. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  6669. {
  6670. return isset($this->scriptFiles[$position][$url]);
  6671. }
  6672. public function isScriptRegistered($id,$position=self::POS_READY)
  6673. {
  6674. return isset($this->scripts[$position][$id]);
  6675. }
  6676. protected function recordCachingAction($context,$method,$params)
  6677. {
  6678. if(($controller=Yii::app()->getController())!==null)
  6679. $controller->recordCachingAction($context,$method,$params);
  6680. }
  6681. public function addPackage($name,$definition)
  6682. {
  6683. $this->packages[$name]=$definition;
  6684. return $this;
  6685. }
  6686. }
  6687. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  6688. {
  6689. private $_d=array();
  6690. private $_c=0;
  6691. private $_r=false;
  6692. public function __construct($data=null,$readOnly=false)
  6693. {
  6694. if($data!==null)
  6695. $this->copyFrom($data);
  6696. $this->setReadOnly($readOnly);
  6697. }
  6698. public function getReadOnly()
  6699. {
  6700. return $this->_r;
  6701. }
  6702. protected function setReadOnly($value)
  6703. {
  6704. $this->_r=$value;
  6705. }
  6706. public function getIterator()
  6707. {
  6708. return new CListIterator($this->_d);
  6709. }
  6710. public function count()
  6711. {
  6712. return $this->getCount();
  6713. }
  6714. public function getCount()
  6715. {
  6716. return $this->_c;
  6717. }
  6718. public function itemAt($index)
  6719. {
  6720. if(isset($this->_d[$index]))
  6721. return $this->_d[$index];
  6722. elseif($index>=0 && $index<$this->_c) // in case the value is null
  6723. return $this->_d[$index];
  6724. else
  6725. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6726. array('{index}'=>$index)));
  6727. }
  6728. public function add($item)
  6729. {
  6730. $this->insertAt($this->_c,$item);
  6731. return $this->_c-1;
  6732. }
  6733. public function insertAt($index,$item)
  6734. {
  6735. if(!$this->_r)
  6736. {
  6737. if($index===$this->_c)
  6738. $this->_d[$this->_c++]=$item;
  6739. elseif($index>=0 && $index<$this->_c)
  6740. {
  6741. array_splice($this->_d,$index,0,array($item));
  6742. $this->_c++;
  6743. }
  6744. else
  6745. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6746. array('{index}'=>$index)));
  6747. }
  6748. else
  6749. throw new CException(Yii::t('yii','The list is read only.'));
  6750. }
  6751. public function remove($item)
  6752. {
  6753. if(($index=$this->indexOf($item))>=0)
  6754. {
  6755. $this->removeAt($index);
  6756. return $index;
  6757. }
  6758. else
  6759. return false;
  6760. }
  6761. public function removeAt($index)
  6762. {
  6763. if(!$this->_r)
  6764. {
  6765. if($index>=0 && $index<$this->_c)
  6766. {
  6767. $this->_c--;
  6768. if($index===$this->_c)
  6769. return array_pop($this->_d);
  6770. else
  6771. {
  6772. $item=$this->_d[$index];
  6773. array_splice($this->_d,$index,1);
  6774. return $item;
  6775. }
  6776. }
  6777. else
  6778. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6779. array('{index}'=>$index)));
  6780. }
  6781. else
  6782. throw new CException(Yii::t('yii','The list is read only.'));
  6783. }
  6784. public function clear()
  6785. {
  6786. for($i=$this->_c-1;$i>=0;--$i)
  6787. $this->removeAt($i);
  6788. }
  6789. public function contains($item)
  6790. {
  6791. return $this->indexOf($item)>=0;
  6792. }
  6793. public function indexOf($item)
  6794. {
  6795. if(($index=array_search($item,$this->_d,true))!==false)
  6796. return $index;
  6797. else
  6798. return -1;
  6799. }
  6800. public function toArray()
  6801. {
  6802. return $this->_d;
  6803. }
  6804. public function copyFrom($data)
  6805. {
  6806. if(is_array($data) || ($data instanceof Traversable))
  6807. {
  6808. if($this->_c>0)
  6809. $this->clear();
  6810. if($data instanceof CList)
  6811. $data=$data->_d;
  6812. foreach($data as $item)
  6813. $this->add($item);
  6814. }
  6815. elseif($data!==null)
  6816. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6817. }
  6818. public function mergeWith($data)
  6819. {
  6820. if(is_array($data) || ($data instanceof Traversable))
  6821. {
  6822. if($data instanceof CList)
  6823. $data=$data->_d;
  6824. foreach($data as $item)
  6825. $this->add($item);
  6826. }
  6827. elseif($data!==null)
  6828. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6829. }
  6830. public function offsetExists($offset)
  6831. {
  6832. return ($offset>=0 && $offset<$this->_c);
  6833. }
  6834. public function offsetGet($offset)
  6835. {
  6836. return $this->itemAt($offset);
  6837. }
  6838. public function offsetSet($offset,$item)
  6839. {
  6840. if($offset===null || $offset===$this->_c)
  6841. $this->insertAt($this->_c,$item);
  6842. else
  6843. {
  6844. $this->removeAt($offset);
  6845. $this->insertAt($offset,$item);
  6846. }
  6847. }
  6848. public function offsetUnset($offset)
  6849. {
  6850. $this->removeAt($offset);
  6851. }
  6852. }
  6853. class CFilterChain extends CList
  6854. {
  6855. public $controller;
  6856. public $action;
  6857. public $filterIndex=0;
  6858. public function __construct($controller,$action)
  6859. {
  6860. $this->controller=$controller;
  6861. $this->action=$action;
  6862. }
  6863. public static function create($controller,$action,$filters)
  6864. {
  6865. $chain=new CFilterChain($controller,$action);
  6866. $actionID=$action->getId();
  6867. foreach($filters as $filter)
  6868. {
  6869. if(is_string($filter)) // filterName [+|- action1 action2]
  6870. {
  6871. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  6872. {
  6873. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  6874. if(($filter[$pos]==='+')===$matched)
  6875. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  6876. }
  6877. else
  6878. $filter=CInlineFilter::create($controller,$filter);
  6879. }
  6880. elseif(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  6881. {
  6882. if(!isset($filter[0]))
  6883. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  6884. $filterClass=$filter[0];
  6885. unset($filter[0]);
  6886. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  6887. {
  6888. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  6889. if(($filterClass[$pos]==='+')===$matched)
  6890. $filterClass=trim(substr($filterClass,0,$pos));
  6891. else
  6892. continue;
  6893. }
  6894. $filter['class']=$filterClass;
  6895. $filter=Yii::createComponent($filter);
  6896. }
  6897. if(is_object($filter))
  6898. {
  6899. $filter->init();
  6900. $chain->add($filter);
  6901. }
  6902. }
  6903. return $chain;
  6904. }
  6905. public function insertAt($index,$item)
  6906. {
  6907. if($item instanceof IFilter)
  6908. parent::insertAt($index,$item);
  6909. else
  6910. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  6911. }
  6912. public function run()
  6913. {
  6914. if($this->offsetExists($this->filterIndex))
  6915. {
  6916. $filter=$this->itemAt($this->filterIndex++);
  6917. $filter->filter($this);
  6918. }
  6919. else
  6920. $this->controller->runAction($this->action);
  6921. }
  6922. }
  6923. class CFilter extends CComponent implements IFilter
  6924. {
  6925. public function filter($filterChain)
  6926. {
  6927. if($this->preFilter($filterChain))
  6928. {
  6929. $filterChain->run();
  6930. $this->postFilter($filterChain);
  6931. }
  6932. }
  6933. public function init()
  6934. {
  6935. }
  6936. protected function preFilter($filterChain)
  6937. {
  6938. return true;
  6939. }
  6940. protected function postFilter($filterChain)
  6941. {
  6942. }
  6943. }
  6944. class CInlineFilter extends CFilter
  6945. {
  6946. public $name;
  6947. public static function create($controller,$filterName)
  6948. {
  6949. if(method_exists($controller,'filter'.$filterName))
  6950. {
  6951. $filter=new CInlineFilter;
  6952. $filter->name=$filterName;
  6953. return $filter;
  6954. }
  6955. else
  6956. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  6957. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  6958. }
  6959. public function filter($filterChain)
  6960. {
  6961. $method='filter'.$this->name;
  6962. $filterChain->controller->$method($filterChain);
  6963. }
  6964. }
  6965. class CAccessControlFilter extends CFilter
  6966. {
  6967. public $message;
  6968. private $_rules=array();
  6969. public function getRules()
  6970. {
  6971. return $this->_rules;
  6972. }
  6973. public function setRules($rules)
  6974. {
  6975. foreach($rules as $rule)
  6976. {
  6977. if(is_array($rule) && isset($rule[0]))
  6978. {
  6979. $r=new CAccessRule;
  6980. $r->allow=$rule[0]==='allow';
  6981. foreach(array_slice($rule,1) as $name=>$value)
  6982. {
  6983. if($name==='expression' || $name==='roles' || $name==='message' || $name==='deniedCallback')
  6984. $r->$name=$value;
  6985. else
  6986. $r->$name=array_map('strtolower',$value);
  6987. }
  6988. $this->_rules[]=$r;
  6989. }
  6990. }
  6991. }
  6992. protected function preFilter($filterChain)
  6993. {
  6994. $app=Yii::app();
  6995. $request=$app->getRequest();
  6996. $user=$app->getUser();
  6997. $verb=$request->getRequestType();
  6998. $ip=$request->getUserHostAddress();
  6999. foreach($this->getRules() as $rule)
  7000. {
  7001. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  7002. break;
  7003. elseif($allow<0) // denied
  7004. {
  7005. if(isset($rule->deniedCallback))
  7006. call_user_func($rule->deniedCallback, $rule);
  7007. else
  7008. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  7009. return false;
  7010. }
  7011. }
  7012. return true;
  7013. }
  7014. protected function resolveErrorMessage($rule)
  7015. {
  7016. if($rule->message!==null)
  7017. return $rule->message;
  7018. elseif($this->message!==null)
  7019. return $this->message;
  7020. else
  7021. return Yii::t('yii','You are not authorized to perform this action.');
  7022. }
  7023. protected function accessDenied($user,$message)
  7024. {
  7025. if($user->getIsGuest())
  7026. $user->loginRequired();
  7027. else
  7028. throw new CHttpException(403,$message);
  7029. }
  7030. }
  7031. class CAccessRule extends CComponent
  7032. {
  7033. public $allow;
  7034. public $actions;
  7035. public $controllers;
  7036. public $users;
  7037. public $roles;
  7038. public $ips;
  7039. public $verbs;
  7040. public $expression;
  7041. public $message;
  7042. public $deniedCallback;
  7043. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  7044. {
  7045. if($this->isActionMatched($action)
  7046. && $this->isUserMatched($user)
  7047. && $this->isRoleMatched($user)
  7048. && $this->isIpMatched($ip)
  7049. && $this->isVerbMatched($verb)
  7050. && $this->isControllerMatched($controller)
  7051. && $this->isExpressionMatched($user))
  7052. return $this->allow ? 1 : -1;
  7053. else
  7054. return 0;
  7055. }
  7056. protected function isActionMatched($action)
  7057. {
  7058. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  7059. }
  7060. protected function isControllerMatched($controller)
  7061. {
  7062. return empty($this->controllers) || in_array(strtolower($controller->getUniqueId()),$this->controllers);
  7063. }
  7064. protected function isUserMatched($user)
  7065. {
  7066. if(empty($this->users))
  7067. return true;
  7068. foreach($this->users as $u)
  7069. {
  7070. if($u==='*')
  7071. return true;
  7072. elseif($u==='?' && $user->getIsGuest())
  7073. return true;
  7074. elseif($u==='@' && !$user->getIsGuest())
  7075. return true;
  7076. elseif(!strcasecmp($u,$user->getName()))
  7077. return true;
  7078. }
  7079. return false;
  7080. }
  7081. protected function isRoleMatched($user)
  7082. {
  7083. if(empty($this->roles))
  7084. return true;
  7085. foreach($this->roles as $key=>$role)
  7086. {
  7087. if(is_numeric($key))
  7088. {
  7089. if($user->checkAccess($role))
  7090. return true;
  7091. }
  7092. else
  7093. {
  7094. if($user->checkAccess($key,$role))
  7095. return true;
  7096. }
  7097. }
  7098. return false;
  7099. }
  7100. protected function isIpMatched($ip)
  7101. {
  7102. if(empty($this->ips))
  7103. return true;
  7104. foreach($this->ips as $rule)
  7105. {
  7106. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  7107. return true;
  7108. }
  7109. return false;
  7110. }
  7111. protected function isVerbMatched($verb)
  7112. {
  7113. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  7114. }
  7115. protected function isExpressionMatched($user)
  7116. {
  7117. if($this->expression===null)
  7118. return true;
  7119. else
  7120. return $this->evaluateExpression($this->expression, array('user'=>$user));
  7121. }
  7122. }
  7123. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  7124. {
  7125. private $_errors=array(); // attribute name => array of errors
  7126. private $_validators; // validators
  7127. private $_scenario=''; // scenario
  7128. abstract public function attributeNames();
  7129. public function rules()
  7130. {
  7131. return array();
  7132. }
  7133. public function behaviors()
  7134. {
  7135. return array();
  7136. }
  7137. public function attributeLabels()
  7138. {
  7139. return array();
  7140. }
  7141. public function validate($attributes=null, $clearErrors=true)
  7142. {
  7143. if($clearErrors)
  7144. $this->clearErrors();
  7145. if($this->beforeValidate())
  7146. {
  7147. foreach($this->getValidators() as $validator)
  7148. $validator->validate($this,$attributes);
  7149. $this->afterValidate();
  7150. return !$this->hasErrors();
  7151. }
  7152. else
  7153. return false;
  7154. }
  7155. protected function afterConstruct()
  7156. {
  7157. if($this->hasEventHandler('onAfterConstruct'))
  7158. $this->onAfterConstruct(new CEvent($this));
  7159. }
  7160. protected function beforeValidate()
  7161. {
  7162. $event=new CModelEvent($this);
  7163. $this->onBeforeValidate($event);
  7164. return $event->isValid;
  7165. }
  7166. protected function afterValidate()
  7167. {
  7168. $this->onAfterValidate(new CEvent($this));
  7169. }
  7170. public function onAfterConstruct($event)
  7171. {
  7172. $this->raiseEvent('onAfterConstruct',$event);
  7173. }
  7174. public function onBeforeValidate($event)
  7175. {
  7176. $this->raiseEvent('onBeforeValidate',$event);
  7177. }
  7178. public function onAfterValidate($event)
  7179. {
  7180. $this->raiseEvent('onAfterValidate',$event);
  7181. }
  7182. public function getValidatorList()
  7183. {
  7184. if($this->_validators===null)
  7185. $this->_validators=$this->createValidators();
  7186. return $this->_validators;
  7187. }
  7188. public function getValidators($attribute=null)
  7189. {
  7190. if($this->_validators===null)
  7191. $this->_validators=$this->createValidators();
  7192. $validators=array();
  7193. $scenario=$this->getScenario();
  7194. foreach($this->_validators as $validator)
  7195. {
  7196. if($validator->applyTo($scenario))
  7197. {
  7198. if($attribute===null || in_array($attribute,$validator->attributes,true))
  7199. $validators[]=$validator;
  7200. }
  7201. }
  7202. return $validators;
  7203. }
  7204. public function createValidators()
  7205. {
  7206. $validators=new CList;
  7207. foreach($this->rules() as $rule)
  7208. {
  7209. if(isset($rule[0],$rule[1])) // attributes, validator name
  7210. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  7211. else
  7212. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  7213. array('{class}'=>get_class($this))));
  7214. }
  7215. return $validators;
  7216. }
  7217. public function isAttributeRequired($attribute)
  7218. {
  7219. foreach($this->getValidators($attribute) as $validator)
  7220. {
  7221. if($validator instanceof CRequiredValidator)
  7222. return true;
  7223. }
  7224. return false;
  7225. }
  7226. public function isAttributeSafe($attribute)
  7227. {
  7228. $attributes=$this->getSafeAttributeNames();
  7229. return in_array($attribute,$attributes);
  7230. }
  7231. public function getAttributeLabel($attribute)
  7232. {
  7233. $labels=$this->attributeLabels();
  7234. if(isset($labels[$attribute]))
  7235. return $labels[$attribute];
  7236. else
  7237. return $this->generateAttributeLabel($attribute);
  7238. }
  7239. public function hasErrors($attribute=null)
  7240. {
  7241. if($attribute===null)
  7242. return $this->_errors!==array();
  7243. else
  7244. return isset($this->_errors[$attribute]);
  7245. }
  7246. public function getErrors($attribute=null)
  7247. {
  7248. if($attribute===null)
  7249. return $this->_errors;
  7250. else
  7251. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  7252. }
  7253. public function getError($attribute)
  7254. {
  7255. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  7256. }
  7257. public function addError($attribute,$error)
  7258. {
  7259. $this->_errors[$attribute][]=$error;
  7260. }
  7261. public function addErrors($errors)
  7262. {
  7263. foreach($errors as $attribute=>$error)
  7264. {
  7265. if(is_array($error))
  7266. {
  7267. foreach($error as $e)
  7268. $this->addError($attribute, $e);
  7269. }
  7270. else
  7271. $this->addError($attribute, $error);
  7272. }
  7273. }
  7274. public function clearErrors($attribute=null)
  7275. {
  7276. if($attribute===null)
  7277. $this->_errors=array();
  7278. else
  7279. unset($this->_errors[$attribute]);
  7280. }
  7281. public function generateAttributeLabel($name)
  7282. {
  7283. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  7284. }
  7285. public function getAttributes($names=null)
  7286. {
  7287. $values=array();
  7288. foreach($this->attributeNames() as $name)
  7289. $values[$name]=$this->$name;
  7290. if(is_array($names))
  7291. {
  7292. $values2=array();
  7293. foreach($names as $name)
  7294. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  7295. return $values2;
  7296. }
  7297. else
  7298. return $values;
  7299. }
  7300. public function setAttributes($values,$safeOnly=true)
  7301. {
  7302. if(!is_array($values))
  7303. return;
  7304. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  7305. foreach($values as $name=>$value)
  7306. {
  7307. if(isset($attributes[$name]))
  7308. $this->$name=$value;
  7309. elseif($safeOnly)
  7310. $this->onUnsafeAttribute($name,$value);
  7311. }
  7312. }
  7313. public function unsetAttributes($names=null)
  7314. {
  7315. if($names===null)
  7316. $names=$this->attributeNames();
  7317. foreach($names as $name)
  7318. $this->$name=null;
  7319. }
  7320. public function onUnsafeAttribute($name,$value)
  7321. {
  7322. if(YII_DEBUG)
  7323. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  7324. }
  7325. public function getScenario()
  7326. {
  7327. return $this->_scenario;
  7328. }
  7329. public function setScenario($value)
  7330. {
  7331. $this->_scenario=$value;
  7332. }
  7333. public function getSafeAttributeNames()
  7334. {
  7335. $attributes=array();
  7336. $unsafe=array();
  7337. foreach($this->getValidators() as $validator)
  7338. {
  7339. if(!$validator->safe)
  7340. {
  7341. foreach($validator->attributes as $name)
  7342. $unsafe[]=$name;
  7343. }
  7344. else
  7345. {
  7346. foreach($validator->attributes as $name)
  7347. $attributes[$name]=true;
  7348. }
  7349. }
  7350. foreach($unsafe as $name)
  7351. unset($attributes[$name]);
  7352. return array_keys($attributes);
  7353. }
  7354. public function getIterator()
  7355. {
  7356. $attributes=$this->getAttributes();
  7357. return new CMapIterator($attributes);
  7358. }
  7359. public function offsetExists($offset)
  7360. {
  7361. return property_exists($this,$offset);
  7362. }
  7363. public function offsetGet($offset)
  7364. {
  7365. return $this->$offset;
  7366. }
  7367. public function offsetSet($offset,$item)
  7368. {
  7369. $this->$offset=$item;
  7370. }
  7371. public function offsetUnset($offset)
  7372. {
  7373. unset($this->$offset);
  7374. }
  7375. }
  7376. abstract class CActiveRecord extends CModel
  7377. {
  7378. const BELONGS_TO='CBelongsToRelation';
  7379. const HAS_ONE='CHasOneRelation';
  7380. const HAS_MANY='CHasManyRelation';
  7381. const MANY_MANY='CManyManyRelation';
  7382. const STAT='CStatRelation';
  7383. public static $db;
  7384. private static $_models=array(); // class name => model
  7385. private static $_md=array(); // class name => meta data
  7386. private $_new=false; // whether this instance is new or not
  7387. private $_attributes=array(); // attribute name => attribute value
  7388. private $_related=array(); // attribute name => related objects
  7389. private $_c; // query criteria (used by finder only)
  7390. private $_pk; // old primary key value
  7391. private $_alias='t'; // the table alias being used for query
  7392. public function __construct($scenario='insert')
  7393. {
  7394. if($scenario===null) // internally used by populateRecord() and model()
  7395. return;
  7396. $this->setScenario($scenario);
  7397. $this->setIsNewRecord(true);
  7398. $this->_attributes=$this->getMetaData()->attributeDefaults;
  7399. $this->init();
  7400. $this->attachBehaviors($this->behaviors());
  7401. $this->afterConstruct();
  7402. }
  7403. public function init()
  7404. {
  7405. }
  7406. public function cache($duration, $dependency=null, $queryCount=1)
  7407. {
  7408. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  7409. return $this;
  7410. }
  7411. public function __sleep()
  7412. {
  7413. return array_keys((array)$this);
  7414. }
  7415. public function __get($name)
  7416. {
  7417. if(isset($this->_attributes[$name]))
  7418. return $this->_attributes[$name];
  7419. elseif(isset($this->getMetaData()->columns[$name]))
  7420. return null;
  7421. elseif(isset($this->_related[$name]))
  7422. return $this->_related[$name];
  7423. elseif(isset($this->getMetaData()->relations[$name]))
  7424. return $this->getRelated($name);
  7425. else
  7426. return parent::__get($name);
  7427. }
  7428. public function __set($name,$value)
  7429. {
  7430. if($this->setAttribute($name,$value)===false)
  7431. {
  7432. if(isset($this->getMetaData()->relations[$name]))
  7433. $this->_related[$name]=$value;
  7434. else
  7435. parent::__set($name,$value);
  7436. }
  7437. }
  7438. public function __isset($name)
  7439. {
  7440. if(isset($this->_attributes[$name]))
  7441. return true;
  7442. elseif(isset($this->getMetaData()->columns[$name]))
  7443. return false;
  7444. elseif(isset($this->_related[$name]))
  7445. return true;
  7446. elseif(isset($this->getMetaData()->relations[$name]))
  7447. return $this->getRelated($name)!==null;
  7448. else
  7449. return parent::__isset($name);
  7450. }
  7451. public function __unset($name)
  7452. {
  7453. if(isset($this->getMetaData()->columns[$name]))
  7454. unset($this->_attributes[$name]);
  7455. elseif(isset($this->getMetaData()->relations[$name]))
  7456. unset($this->_related[$name]);
  7457. else
  7458. parent::__unset($name);
  7459. }
  7460. public function __call($name,$parameters)
  7461. {
  7462. if(isset($this->getMetaData()->relations[$name]))
  7463. {
  7464. if(empty($parameters))
  7465. return $this->getRelated($name,false);
  7466. else
  7467. return $this->getRelated($name,false,$parameters[0]);
  7468. }
  7469. $scopes=$this->scopes();
  7470. if(isset($scopes[$name]))
  7471. {
  7472. $this->getDbCriteria()->mergeWith($scopes[$name]);
  7473. return $this;
  7474. }
  7475. return parent::__call($name,$parameters);
  7476. }
  7477. public function getRelated($name,$refresh=false,$params=array())
  7478. {
  7479. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  7480. return $this->_related[$name];
  7481. $md=$this->getMetaData();
  7482. if(!isset($md->relations[$name]))
  7483. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  7484. array('{class}'=>get_class($this), '{name}'=>$name)));
  7485. $relation=$md->relations[$name];
  7486. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  7487. return $relation instanceof CHasOneRelation ? null : array();
  7488. if($params!==array()) // dynamic query
  7489. {
  7490. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7491. if($exists)
  7492. $save=$this->_related[$name];
  7493. if($params instanceof CDbCriteria)
  7494. $params = $params->toArray();
  7495. $r=array($name=>$params);
  7496. }
  7497. else
  7498. $r=$name;
  7499. unset($this->_related[$name]);
  7500. $finder=$this->getActiveFinder($r);
  7501. $finder->lazyFind($this);
  7502. if(!isset($this->_related[$name]))
  7503. {
  7504. if($relation instanceof CHasManyRelation)
  7505. $this->_related[$name]=array();
  7506. elseif($relation instanceof CStatRelation)
  7507. $this->_related[$name]=$relation->defaultValue;
  7508. else
  7509. $this->_related[$name]=null;
  7510. }
  7511. if($params!==array())
  7512. {
  7513. $results=$this->_related[$name];
  7514. if($exists)
  7515. $this->_related[$name]=$save;
  7516. else
  7517. unset($this->_related[$name]);
  7518. return $results;
  7519. }
  7520. else
  7521. return $this->_related[$name];
  7522. }
  7523. public function hasRelated($name)
  7524. {
  7525. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7526. }
  7527. public function getDbCriteria($createIfNull=true)
  7528. {
  7529. if($this->_c===null)
  7530. {
  7531. if(($c=$this->defaultScope())!==array() || $createIfNull)
  7532. $this->_c=new CDbCriteria($c);
  7533. }
  7534. return $this->_c;
  7535. }
  7536. public function setDbCriteria($criteria)
  7537. {
  7538. $this->_c=$criteria;
  7539. }
  7540. public function defaultScope()
  7541. {
  7542. return array();
  7543. }
  7544. public function resetScope($resetDefault=true)
  7545. {
  7546. if($resetDefault)
  7547. $this->_c=new CDbCriteria();
  7548. else
  7549. $this->_c=null;
  7550. return $this;
  7551. }
  7552. public static function model($className=__CLASS__)
  7553. {
  7554. if(isset(self::$_models[$className]))
  7555. return self::$_models[$className];
  7556. else
  7557. {
  7558. $model=self::$_models[$className]=new $className(null);
  7559. $model->attachBehaviors($model->behaviors());
  7560. return $model;
  7561. }
  7562. }
  7563. public function getMetaData()
  7564. {
  7565. $className=get_class($this);
  7566. if(!array_key_exists($className,self::$_md))
  7567. {
  7568. self::$_md[$className]=null; // preventing recursive invokes of {@link getMetaData()} via {@link __get()}
  7569. self::$_md[$className]=new CActiveRecordMetaData($this);
  7570. }
  7571. return self::$_md[$className];
  7572. }
  7573. public function refreshMetaData()
  7574. {
  7575. $className=get_class($this);
  7576. if(array_key_exists($className,self::$_md))
  7577. unset(self::$_md[$className]);
  7578. }
  7579. public function tableName()
  7580. {
  7581. $tableName = get_class($this);
  7582. if(($pos=strrpos($tableName,'\\')) !== false)
  7583. return substr($tableName,$pos+1);
  7584. return $tableName;
  7585. }
  7586. public function primaryKey()
  7587. {
  7588. }
  7589. public function relations()
  7590. {
  7591. return array();
  7592. }
  7593. public function scopes()
  7594. {
  7595. return array();
  7596. }
  7597. public function attributeNames()
  7598. {
  7599. return array_keys($this->getMetaData()->columns);
  7600. }
  7601. public function getAttributeLabel($attribute)
  7602. {
  7603. $labels=$this->attributeLabels();
  7604. if(isset($labels[$attribute]))
  7605. return $labels[$attribute];
  7606. elseif(strpos($attribute,'.')!==false)
  7607. {
  7608. $segs=explode('.',$attribute);
  7609. $name=array_pop($segs);
  7610. $model=$this;
  7611. foreach($segs as $seg)
  7612. {
  7613. $relations=$model->getMetaData()->relations;
  7614. if(isset($relations[$seg]))
  7615. $model=CActiveRecord::model($relations[$seg]->className);
  7616. else
  7617. break;
  7618. }
  7619. return $model->getAttributeLabel($name);
  7620. }
  7621. else
  7622. return $this->generateAttributeLabel($attribute);
  7623. }
  7624. public function getDbConnection()
  7625. {
  7626. if(self::$db!==null)
  7627. return self::$db;
  7628. else
  7629. {
  7630. self::$db=Yii::app()->getDb();
  7631. if(self::$db instanceof CDbConnection)
  7632. return self::$db;
  7633. else
  7634. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  7635. }
  7636. }
  7637. public function getActiveRelation($name)
  7638. {
  7639. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  7640. }
  7641. public function getTableSchema()
  7642. {
  7643. return $this->getMetaData()->tableSchema;
  7644. }
  7645. public function getCommandBuilder()
  7646. {
  7647. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  7648. }
  7649. public function hasAttribute($name)
  7650. {
  7651. return isset($this->getMetaData()->columns[$name]);
  7652. }
  7653. public function getAttribute($name)
  7654. {
  7655. if(property_exists($this,$name))
  7656. return $this->$name;
  7657. elseif(isset($this->_attributes[$name]))
  7658. return $this->_attributes[$name];
  7659. }
  7660. public function setAttribute($name,$value)
  7661. {
  7662. if(property_exists($this,$name))
  7663. $this->$name=$value;
  7664. elseif(isset($this->getMetaData()->columns[$name]))
  7665. $this->_attributes[$name]=$value;
  7666. else
  7667. return false;
  7668. return true;
  7669. }
  7670. public function addRelatedRecord($name,$record,$index)
  7671. {
  7672. if($index!==false)
  7673. {
  7674. if(!isset($this->_related[$name]))
  7675. $this->_related[$name]=array();
  7676. if($record instanceof CActiveRecord)
  7677. {
  7678. if($index===true)
  7679. $this->_related[$name][]=$record;
  7680. else
  7681. $this->_related[$name][$index]=$record;
  7682. }
  7683. }
  7684. elseif(!isset($this->_related[$name]))
  7685. $this->_related[$name]=$record;
  7686. }
  7687. public function getAttributes($names=true)
  7688. {
  7689. $attributes=$this->_attributes;
  7690. foreach($this->getMetaData()->columns as $name=>$column)
  7691. {
  7692. if(property_exists($this,$name))
  7693. $attributes[$name]=$this->$name;
  7694. elseif($names===true && !isset($attributes[$name]))
  7695. $attributes[$name]=null;
  7696. }
  7697. if(is_array($names))
  7698. {
  7699. $attrs=array();
  7700. foreach($names as $name)
  7701. {
  7702. if(property_exists($this,$name))
  7703. $attrs[$name]=$this->$name;
  7704. else
  7705. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  7706. }
  7707. return $attrs;
  7708. }
  7709. else
  7710. return $attributes;
  7711. }
  7712. public function save($runValidation=true,$attributes=null)
  7713. {
  7714. if(!$runValidation || $this->validate($attributes))
  7715. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  7716. else
  7717. return false;
  7718. }
  7719. public function getIsNewRecord()
  7720. {
  7721. return $this->_new;
  7722. }
  7723. public function setIsNewRecord($value)
  7724. {
  7725. $this->_new=$value;
  7726. }
  7727. public function onBeforeSave($event)
  7728. {
  7729. $this->raiseEvent('onBeforeSave',$event);
  7730. }
  7731. public function onAfterSave($event)
  7732. {
  7733. $this->raiseEvent('onAfterSave',$event);
  7734. }
  7735. public function onBeforeDelete($event)
  7736. {
  7737. $this->raiseEvent('onBeforeDelete',$event);
  7738. }
  7739. public function onAfterDelete($event)
  7740. {
  7741. $this->raiseEvent('onAfterDelete',$event);
  7742. }
  7743. public function onBeforeFind($event)
  7744. {
  7745. $this->raiseEvent('onBeforeFind',$event);
  7746. }
  7747. public function onAfterFind($event)
  7748. {
  7749. $this->raiseEvent('onAfterFind',$event);
  7750. }
  7751. public function getActiveFinder($with)
  7752. {
  7753. return new CActiveFinder($this,$with);
  7754. }
  7755. public function onBeforeCount($event)
  7756. {
  7757. $this->raiseEvent('onBeforeCount',$event);
  7758. }
  7759. protected function beforeSave()
  7760. {
  7761. if($this->hasEventHandler('onBeforeSave'))
  7762. {
  7763. $event=new CModelEvent($this);
  7764. $this->onBeforeSave($event);
  7765. return $event->isValid;
  7766. }
  7767. else
  7768. return true;
  7769. }
  7770. protected function afterSave()
  7771. {
  7772. if($this->hasEventHandler('onAfterSave'))
  7773. $this->onAfterSave(new CEvent($this));
  7774. }
  7775. protected function beforeDelete()
  7776. {
  7777. if($this->hasEventHandler('onBeforeDelete'))
  7778. {
  7779. $event=new CModelEvent($this);
  7780. $this->onBeforeDelete($event);
  7781. return $event->isValid;
  7782. }
  7783. else
  7784. return true;
  7785. }
  7786. protected function afterDelete()
  7787. {
  7788. if($this->hasEventHandler('onAfterDelete'))
  7789. $this->onAfterDelete(new CEvent($this));
  7790. }
  7791. protected function beforeFind()
  7792. {
  7793. if($this->hasEventHandler('onBeforeFind'))
  7794. {
  7795. $event=new CModelEvent($this);
  7796. $this->onBeforeFind($event);
  7797. }
  7798. }
  7799. protected function beforeCount()
  7800. {
  7801. if($this->hasEventHandler('onBeforeCount'))
  7802. $this->onBeforeCount(new CEvent($this));
  7803. }
  7804. protected function afterFind()
  7805. {
  7806. if($this->hasEventHandler('onAfterFind'))
  7807. $this->onAfterFind(new CEvent($this));
  7808. }
  7809. public function beforeFindInternal()
  7810. {
  7811. $this->beforeFind();
  7812. }
  7813. public function afterFindInternal()
  7814. {
  7815. $this->afterFind();
  7816. }
  7817. public function insert($attributes=null)
  7818. {
  7819. if(!$this->getIsNewRecord())
  7820. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  7821. if($this->beforeSave())
  7822. {
  7823. $builder=$this->getCommandBuilder();
  7824. $table=$this->getTableSchema();
  7825. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  7826. if($command->execute())
  7827. {
  7828. $primaryKey=$table->primaryKey;
  7829. if($table->sequenceName!==null)
  7830. {
  7831. if(is_string($primaryKey) && $this->$primaryKey===null)
  7832. $this->$primaryKey=$builder->getLastInsertID($table);
  7833. elseif(is_array($primaryKey))
  7834. {
  7835. foreach($primaryKey as $pk)
  7836. {
  7837. if($this->$pk===null)
  7838. {
  7839. $this->$pk=$builder->getLastInsertID($table);
  7840. break;
  7841. }
  7842. }
  7843. }
  7844. }
  7845. $this->_pk=$this->getPrimaryKey();
  7846. $this->afterSave();
  7847. $this->setIsNewRecord(false);
  7848. $this->setScenario('update');
  7849. return true;
  7850. }
  7851. }
  7852. return false;
  7853. }
  7854. public function update($attributes=null)
  7855. {
  7856. if($this->getIsNewRecord())
  7857. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7858. if($this->beforeSave())
  7859. {
  7860. if($this->_pk===null)
  7861. $this->_pk=$this->getPrimaryKey();
  7862. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  7863. $this->_pk=$this->getPrimaryKey();
  7864. $this->afterSave();
  7865. return true;
  7866. }
  7867. else
  7868. return false;
  7869. }
  7870. public function saveAttributes($attributes)
  7871. {
  7872. if(!$this->getIsNewRecord())
  7873. {
  7874. $values=array();
  7875. foreach($attributes as $name=>$value)
  7876. {
  7877. if(is_integer($name))
  7878. $values[$value]=$this->$value;
  7879. else
  7880. $values[$name]=$this->$name=$value;
  7881. }
  7882. if($this->_pk===null)
  7883. $this->_pk=$this->getPrimaryKey();
  7884. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  7885. {
  7886. $this->_pk=$this->getPrimaryKey();
  7887. return true;
  7888. }
  7889. else
  7890. return false;
  7891. }
  7892. else
  7893. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7894. }
  7895. public function saveCounters($counters)
  7896. {
  7897. $builder=$this->getCommandBuilder();
  7898. $table=$this->getTableSchema();
  7899. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  7900. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7901. if($command->execute())
  7902. {
  7903. foreach($counters as $name=>$value)
  7904. $this->$name=$this->$name+$value;
  7905. return true;
  7906. }
  7907. else
  7908. return false;
  7909. }
  7910. public function delete()
  7911. {
  7912. if(!$this->getIsNewRecord())
  7913. {
  7914. if($this->beforeDelete())
  7915. {
  7916. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  7917. $this->afterDelete();
  7918. return $result;
  7919. }
  7920. else
  7921. return false;
  7922. }
  7923. else
  7924. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  7925. }
  7926. public function refresh()
  7927. {
  7928. if(($record=$this->findByPk($this->getPrimaryKey()))!==null)
  7929. {
  7930. $this->_attributes=array();
  7931. $this->_related=array();
  7932. foreach($this->getMetaData()->columns as $name=>$column)
  7933. {
  7934. if(property_exists($this,$name))
  7935. $this->$name=$record->$name;
  7936. else
  7937. $this->_attributes[$name]=$record->$name;
  7938. }
  7939. return true;
  7940. }
  7941. else
  7942. return false;
  7943. }
  7944. public function equals($record)
  7945. {
  7946. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  7947. }
  7948. public function getPrimaryKey()
  7949. {
  7950. $table=$this->getTableSchema();
  7951. if(is_string($table->primaryKey))
  7952. return $this->{$table->primaryKey};
  7953. elseif(is_array($table->primaryKey))
  7954. {
  7955. $values=array();
  7956. foreach($table->primaryKey as $name)
  7957. $values[$name]=$this->$name;
  7958. return $values;
  7959. }
  7960. else
  7961. return null;
  7962. }
  7963. public function setPrimaryKey($value)
  7964. {
  7965. $this->_pk=$this->getPrimaryKey();
  7966. $table=$this->getTableSchema();
  7967. if(is_string($table->primaryKey))
  7968. $this->{$table->primaryKey}=$value;
  7969. elseif(is_array($table->primaryKey))
  7970. {
  7971. foreach($table->primaryKey as $name)
  7972. $this->$name=$value[$name];
  7973. }
  7974. }
  7975. public function getOldPrimaryKey()
  7976. {
  7977. return $this->_pk;
  7978. }
  7979. public function setOldPrimaryKey($value)
  7980. {
  7981. $this->_pk=$value;
  7982. }
  7983. protected function query($criteria,$all=false)
  7984. {
  7985. $this->beforeFind();
  7986. $this->applyScopes($criteria);
  7987. if(empty($criteria->with))
  7988. {
  7989. if(!$all)
  7990. $criteria->limit=1;
  7991. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  7992. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  7993. }
  7994. else
  7995. {
  7996. $finder=$this->getActiveFinder($criteria->with);
  7997. return $finder->query($criteria,$all);
  7998. }
  7999. }
  8000. public function applyScopes(&$criteria)
  8001. {
  8002. if(!empty($criteria->scopes))
  8003. {
  8004. $scs=$this->scopes();
  8005. $c=$this->getDbCriteria();
  8006. foreach((array)$criteria->scopes as $k=>$v)
  8007. {
  8008. if(is_integer($k))
  8009. {
  8010. if(is_string($v))
  8011. {
  8012. if(isset($scs[$v]))
  8013. {
  8014. $c->mergeWith($scs[$v],true);
  8015. continue;
  8016. }
  8017. $scope=$v;
  8018. $params=array();
  8019. }
  8020. elseif(is_array($v))
  8021. {
  8022. $scope=key($v);
  8023. $params=current($v);
  8024. }
  8025. }
  8026. elseif(is_string($k))
  8027. {
  8028. $scope=$k;
  8029. $params=$v;
  8030. }
  8031. call_user_func_array(array($this,$scope),(array)$params);
  8032. }
  8033. }
  8034. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  8035. {
  8036. $c->mergeWith($criteria);
  8037. $criteria=$c;
  8038. $this->resetScope(false);
  8039. }
  8040. }
  8041. public function getTableAlias($quote=false, $checkScopes=true)
  8042. {
  8043. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  8044. $alias=$criteria->alias;
  8045. else
  8046. $alias=$this->_alias;
  8047. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  8048. }
  8049. public function setTableAlias($alias)
  8050. {
  8051. $this->_alias=$alias;
  8052. }
  8053. public function find($condition='',$params=array())
  8054. {
  8055. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  8056. return $this->query($criteria);
  8057. }
  8058. public function findAll($condition='',$params=array())
  8059. {
  8060. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  8061. return $this->query($criteria,true);
  8062. }
  8063. public function findByPk($pk,$condition='',$params=array())
  8064. {
  8065. $prefix=$this->getTableAlias(true).'.';
  8066. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  8067. return $this->query($criteria);
  8068. }
  8069. public function findAllByPk($pk,$condition='',$params=array())
  8070. {
  8071. $prefix=$this->getTableAlias(true).'.';
  8072. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  8073. return $this->query($criteria,true);
  8074. }
  8075. public function findByAttributes($attributes,$condition='',$params=array())
  8076. {
  8077. $prefix=$this->getTableAlias(true).'.';
  8078. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8079. return $this->query($criteria);
  8080. }
  8081. public function findAllByAttributes($attributes,$condition='',$params=array())
  8082. {
  8083. $prefix=$this->getTableAlias(true).'.';
  8084. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8085. return $this->query($criteria,true);
  8086. }
  8087. public function findBySql($sql,$params=array())
  8088. {
  8089. $this->beforeFind();
  8090. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  8091. {
  8092. $this->resetScope(false);
  8093. $finder=$this->getActiveFinder($criteria->with);
  8094. return $finder->findBySql($sql,$params);
  8095. }
  8096. else
  8097. {
  8098. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  8099. return $this->populateRecord($command->queryRow());
  8100. }
  8101. }
  8102. public function findAllBySql($sql,$params=array())
  8103. {
  8104. $this->beforeFind();
  8105. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  8106. {
  8107. $this->resetScope(false);
  8108. $finder=$this->getActiveFinder($criteria->with);
  8109. return $finder->findAllBySql($sql,$params);
  8110. }
  8111. else
  8112. {
  8113. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  8114. return $this->populateRecords($command->queryAll());
  8115. }
  8116. }
  8117. public function count($condition='',$params=array())
  8118. {
  8119. $this->beforeCount();
  8120. $builder=$this->getCommandBuilder();
  8121. $criteria=$builder->createCriteria($condition,$params);
  8122. $this->applyScopes($criteria);
  8123. if(empty($criteria->with))
  8124. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  8125. else
  8126. {
  8127. $finder=$this->getActiveFinder($criteria->with);
  8128. return $finder->count($criteria);
  8129. }
  8130. }
  8131. public function countByAttributes($attributes,$condition='',$params=array())
  8132. {
  8133. $prefix=$this->getTableAlias(true).'.';
  8134. $builder=$this->getCommandBuilder();
  8135. $this->beforeCount();
  8136. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8137. $this->applyScopes($criteria);
  8138. if(empty($criteria->with))
  8139. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  8140. else
  8141. {
  8142. $finder=$this->getActiveFinder($criteria->with);
  8143. return $finder->count($criteria);
  8144. }
  8145. }
  8146. public function countBySql($sql,$params=array())
  8147. {
  8148. $this->beforeCount();
  8149. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  8150. }
  8151. public function exists($condition='',$params=array())
  8152. {
  8153. $builder=$this->getCommandBuilder();
  8154. $criteria=$builder->createCriteria($condition,$params);
  8155. $table=$this->getTableSchema();
  8156. $criteria->select='1';
  8157. $criteria->limit=1;
  8158. $this->applyScopes($criteria);
  8159. if(empty($criteria->with))
  8160. return $builder->createFindCommand($table,$criteria,$this->getTableAlias(false, false))->queryRow()!==false;
  8161. else
  8162. {
  8163. $criteria->select='*';
  8164. $finder=$this->getActiveFinder($criteria->with);
  8165. return $finder->count($criteria)>0;
  8166. }
  8167. }
  8168. public function with()
  8169. {
  8170. if(func_num_args()>0)
  8171. {
  8172. $with=func_get_args();
  8173. if(is_array($with[0])) // the parameter is given as an array
  8174. $with=$with[0];
  8175. if(!empty($with))
  8176. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  8177. }
  8178. return $this;
  8179. }
  8180. public function together()
  8181. {
  8182. $this->getDbCriteria()->together=true;
  8183. return $this;
  8184. }
  8185. public function updateByPk($pk,$attributes,$condition='',$params=array())
  8186. {
  8187. $builder=$this->getCommandBuilder();
  8188. $table=$this->getTableSchema();
  8189. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  8190. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  8191. return $command->execute();
  8192. }
  8193. public function updateAll($attributes,$condition='',$params=array())
  8194. {
  8195. $builder=$this->getCommandBuilder();
  8196. $criteria=$builder->createCriteria($condition,$params);
  8197. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  8198. return $command->execute();
  8199. }
  8200. public function updateCounters($counters,$condition='',$params=array())
  8201. {
  8202. $builder=$this->getCommandBuilder();
  8203. $criteria=$builder->createCriteria($condition,$params);
  8204. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  8205. return $command->execute();
  8206. }
  8207. public function deleteByPk($pk,$condition='',$params=array())
  8208. {
  8209. $builder=$this->getCommandBuilder();
  8210. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  8211. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  8212. return $command->execute();
  8213. }
  8214. public function deleteAll($condition='',$params=array())
  8215. {
  8216. $builder=$this->getCommandBuilder();
  8217. $criteria=$builder->createCriteria($condition,$params);
  8218. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  8219. return $command->execute();
  8220. }
  8221. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  8222. {
  8223. $builder=$this->getCommandBuilder();
  8224. $table=$this->getTableSchema();
  8225. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  8226. $command=$builder->createDeleteCommand($table,$criteria);
  8227. return $command->execute();
  8228. }
  8229. public function populateRecord($attributes,$callAfterFind=true)
  8230. {
  8231. if($attributes!==false)
  8232. {
  8233. $record=$this->instantiate($attributes);
  8234. $record->setScenario('update');
  8235. $record->init();
  8236. $md=$record->getMetaData();
  8237. foreach($attributes as $name=>$value)
  8238. {
  8239. if(property_exists($record,$name))
  8240. $record->$name=$value;
  8241. elseif(isset($md->columns[$name]))
  8242. $record->_attributes[$name]=$value;
  8243. }
  8244. $record->_pk=$record->getPrimaryKey();
  8245. $record->attachBehaviors($record->behaviors());
  8246. if($callAfterFind)
  8247. $record->afterFind();
  8248. return $record;
  8249. }
  8250. else
  8251. return null;
  8252. }
  8253. public function populateRecords($data,$callAfterFind=true,$index=null)
  8254. {
  8255. $records=array();
  8256. foreach($data as $attributes)
  8257. {
  8258. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  8259. {
  8260. if($index===null)
  8261. $records[]=$record;
  8262. else
  8263. $records[$record->$index]=$record;
  8264. }
  8265. }
  8266. return $records;
  8267. }
  8268. protected function instantiate($attributes)
  8269. {
  8270. $class=get_class($this);
  8271. $model=new $class(null);
  8272. return $model;
  8273. }
  8274. public function offsetExists($offset)
  8275. {
  8276. return $this->__isset($offset);
  8277. }
  8278. }
  8279. class CBaseActiveRelation extends CComponent
  8280. {
  8281. public $name;
  8282. public $className;
  8283. public $foreignKey;
  8284. public $select='*';
  8285. public $condition='';
  8286. public $params=array();
  8287. public $group='';
  8288. public $join='';
  8289. public $joinOptions='';
  8290. public $having='';
  8291. public $order='';
  8292. public function __construct($name,$className,$foreignKey,$options=array())
  8293. {
  8294. $this->name=$name;
  8295. $this->className=$className;
  8296. $this->foreignKey=$foreignKey;
  8297. foreach($options as $name=>$value)
  8298. $this->$name=$value;
  8299. }
  8300. public function mergeWith($criteria,$fromScope=false)
  8301. {
  8302. if($criteria instanceof CDbCriteria)
  8303. $criteria=$criteria->toArray();
  8304. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  8305. {
  8306. if($this->select==='*'||$this->select===false)
  8307. $this->select=$criteria['select'];
  8308. elseif($criteria['select']===false)
  8309. $this->select=false;
  8310. elseif($criteria['select']!=='*')
  8311. {
  8312. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  8313. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  8314. $this->select=array_merge($select1,array_diff($select2,$select1));
  8315. }
  8316. }
  8317. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  8318. {
  8319. if($this->condition==='')
  8320. $this->condition=$criteria['condition'];
  8321. elseif($criteria['condition']!=='')
  8322. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  8323. }
  8324. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  8325. $this->params=array_merge($this->params,$criteria['params']);
  8326. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  8327. {
  8328. if($this->order==='')
  8329. $this->order=$criteria['order'];
  8330. elseif($criteria['order']!=='')
  8331. $this->order=$criteria['order'].', '.$this->order;
  8332. }
  8333. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  8334. {
  8335. if($this->group==='')
  8336. $this->group=$criteria['group'];
  8337. elseif($criteria['group']!=='')
  8338. $this->group.=', '.$criteria['group'];
  8339. }
  8340. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  8341. {
  8342. if($this->join==='')
  8343. $this->join=$criteria['join'];
  8344. elseif($criteria['join']!=='')
  8345. $this->join.=' '.$criteria['join'];
  8346. }
  8347. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  8348. {
  8349. if($this->having==='')
  8350. $this->having=$criteria['having'];
  8351. elseif($criteria['having']!=='')
  8352. $this->having="({$this->having}) AND ({$criteria['having']})";
  8353. }
  8354. }
  8355. }
  8356. class CStatRelation extends CBaseActiveRelation
  8357. {
  8358. public $select='COUNT(*)';
  8359. public $defaultValue=0;
  8360. public $scopes;
  8361. public function mergeWith($criteria,$fromScope=false)
  8362. {
  8363. if($criteria instanceof CDbCriteria)
  8364. $criteria=$criteria->toArray();
  8365. parent::mergeWith($criteria,$fromScope);
  8366. if(isset($criteria['defaultValue']))
  8367. $this->defaultValue=$criteria['defaultValue'];
  8368. }
  8369. }
  8370. class CActiveRelation extends CBaseActiveRelation
  8371. {
  8372. public $joinType='LEFT OUTER JOIN';
  8373. public $on='';
  8374. public $alias;
  8375. public $with=array();
  8376. public $together;
  8377. public $scopes;
  8378. public $through;
  8379. public function mergeWith($criteria,$fromScope=false)
  8380. {
  8381. if($criteria instanceof CDbCriteria)
  8382. $criteria=$criteria->toArray();
  8383. if($fromScope)
  8384. {
  8385. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  8386. {
  8387. if($this->on==='')
  8388. $this->on=$criteria['condition'];
  8389. elseif($criteria['condition']!=='')
  8390. $this->on="({$this->on}) AND ({$criteria['condition']})";
  8391. }
  8392. unset($criteria['condition']);
  8393. }
  8394. parent::mergeWith($criteria);
  8395. if(isset($criteria['joinType']))
  8396. $this->joinType=$criteria['joinType'];
  8397. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  8398. {
  8399. if($this->on==='')
  8400. $this->on=$criteria['on'];
  8401. elseif($criteria['on']!=='')
  8402. $this->on="({$this->on}) AND ({$criteria['on']})";
  8403. }
  8404. if(isset($criteria['with']))
  8405. $this->with=$criteria['with'];
  8406. if(isset($criteria['alias']))
  8407. $this->alias=$criteria['alias'];
  8408. if(isset($criteria['together']))
  8409. $this->together=$criteria['together'];
  8410. }
  8411. }
  8412. class CBelongsToRelation extends CActiveRelation
  8413. {
  8414. }
  8415. class CHasOneRelation extends CActiveRelation
  8416. {
  8417. }
  8418. class CHasManyRelation extends CActiveRelation
  8419. {
  8420. public $limit=-1;
  8421. public $offset=-1;
  8422. public $index;
  8423. public function mergeWith($criteria,$fromScope=false)
  8424. {
  8425. if($criteria instanceof CDbCriteria)
  8426. $criteria=$criteria->toArray();
  8427. parent::mergeWith($criteria,$fromScope);
  8428. if(isset($criteria['limit']) && $criteria['limit']>0)
  8429. $this->limit=$criteria['limit'];
  8430. if(isset($criteria['offset']) && $criteria['offset']>=0)
  8431. $this->offset=$criteria['offset'];
  8432. if(isset($criteria['index']))
  8433. $this->index=$criteria['index'];
  8434. }
  8435. }
  8436. class CManyManyRelation extends CHasManyRelation
  8437. {
  8438. private $_junctionTableName=null;
  8439. private $_junctionForeignKeys=null;
  8440. public function getJunctionTableName()
  8441. {
  8442. if ($this->_junctionTableName===null)
  8443. $this->initJunctionData();
  8444. return $this->_junctionTableName;
  8445. }
  8446. public function getJunctionForeignKeys()
  8447. {
  8448. if ($this->_junctionForeignKeys===null)
  8449. $this->initJunctionData();
  8450. return $this->_junctionForeignKeys;
  8451. }
  8452. private function initJunctionData()
  8453. {
  8454. if(!preg_match('/^\s*(.*?)\((.*)\)\s*$/',$this->foreignKey,$matches))
  8455. 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,...)".',
  8456. array('{class}'=>$this->className,'{relation}'=>$this->name)));
  8457. $this->_junctionTableName=$matches[1];
  8458. $this->_junctionForeignKeys=preg_split('/\s*,\s*/',$matches[2],-1,PREG_SPLIT_NO_EMPTY);
  8459. }
  8460. }
  8461. class CActiveRecordMetaData
  8462. {
  8463. public $tableSchema;
  8464. public $columns;
  8465. public $relations=array();
  8466. public $attributeDefaults=array();
  8467. private $_modelClassName;
  8468. public function __construct($model)
  8469. {
  8470. $this->_modelClassName=get_class($model);
  8471. $tableName=$model->tableName();
  8472. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  8473. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  8474. array('{class}'=>$this->_modelClassName,'{table}'=>$tableName)));
  8475. if(($modelPk=$model->primaryKey())!==null || $table->primaryKey===null)
  8476. {
  8477. $table->primaryKey=$modelPk;
  8478. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  8479. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  8480. elseif(is_array($table->primaryKey))
  8481. {
  8482. foreach($table->primaryKey as $name)
  8483. {
  8484. if(isset($table->columns[$name]))
  8485. $table->columns[$name]->isPrimaryKey=true;
  8486. }
  8487. }
  8488. }
  8489. $this->tableSchema=$table;
  8490. $this->columns=$table->columns;
  8491. foreach($table->columns as $name=>$column)
  8492. {
  8493. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  8494. $this->attributeDefaults[$name]=$column->defaultValue;
  8495. }
  8496. foreach($model->relations() as $name=>$config)
  8497. {
  8498. $this->addRelation($name,$config);
  8499. }
  8500. }
  8501. public function addRelation($name,$config)
  8502. {
  8503. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  8504. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  8505. else
  8506. throw new CDbException(Yii::t('yii','Active record "{class}" has an invalid configuration for relation "{relation}". It must specify the relation type, the related active record class and the foreign key.', array('{class}'=>$this->_modelClassName,'{relation}'=>$name)));
  8507. }
  8508. public function hasRelation($name)
  8509. {
  8510. return isset($this->relations[$name]);
  8511. }
  8512. public function removeRelation($name)
  8513. {
  8514. unset($this->relations[$name]);
  8515. }
  8516. }
  8517. class CDbConnection extends CApplicationComponent
  8518. {
  8519. public $connectionString;
  8520. public $username='';
  8521. public $password='';
  8522. public $schemaCachingDuration=0;
  8523. public $schemaCachingExclude=array();
  8524. public $schemaCacheID='cache';
  8525. public $queryCachingDuration=0;
  8526. public $queryCachingDependency;
  8527. public $queryCachingCount=0;
  8528. public $queryCacheID='cache';
  8529. public $autoConnect=true;
  8530. public $charset;
  8531. public $emulatePrepare;
  8532. public $enableParamLogging=false;
  8533. public $enableProfiling=false;
  8534. public $tablePrefix;
  8535. public $initSQLs;
  8536. public $driverMap=array(
  8537. 'cubrid'=>'CCubridSchema', // CUBRID
  8538. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  8539. 'mysqli'=>'CMysqlSchema', // MySQL
  8540. 'mysql'=>'CMysqlSchema', // MySQL,MariaDB
  8541. 'sqlite'=>'CSqliteSchema', // sqlite 3
  8542. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  8543. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  8544. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  8545. 'sqlsrv'=>'CMssqlSchema', // Mssql
  8546. 'oci'=>'COciSchema', // Oracle driver
  8547. );
  8548. public $pdoClass = 'PDO';
  8549. private $_driverName;
  8550. private $_attributes=array();
  8551. private $_active=false;
  8552. private $_pdo;
  8553. private $_transaction;
  8554. private $_schema;
  8555. public function __construct($dsn='',$username='',$password='')
  8556. {
  8557. $this->connectionString=$dsn;
  8558. $this->username=$username;
  8559. $this->password=$password;
  8560. }
  8561. public function __sleep()
  8562. {
  8563. $this->close();
  8564. return array_keys(get_object_vars($this));
  8565. }
  8566. public static function getAvailableDrivers()
  8567. {
  8568. return PDO::getAvailableDrivers();
  8569. }
  8570. public function init()
  8571. {
  8572. parent::init();
  8573. if($this->autoConnect)
  8574. $this->setActive(true);
  8575. }
  8576. public function getActive()
  8577. {
  8578. return $this->_active;
  8579. }
  8580. public function setActive($value)
  8581. {
  8582. if($value!=$this->_active)
  8583. {
  8584. if($value)
  8585. $this->open();
  8586. else
  8587. $this->close();
  8588. }
  8589. }
  8590. public function cache($duration, $dependency=null, $queryCount=1)
  8591. {
  8592. $this->queryCachingDuration=$duration;
  8593. $this->queryCachingDependency=$dependency;
  8594. $this->queryCachingCount=$queryCount;
  8595. return $this;
  8596. }
  8597. protected function open()
  8598. {
  8599. if($this->_pdo===null)
  8600. {
  8601. if(empty($this->connectionString))
  8602. throw new CDbException('CDbConnection.connectionString cannot be empty.');
  8603. try
  8604. {
  8605. $this->_pdo=$this->createPdoInstance();
  8606. $this->initConnection($this->_pdo);
  8607. $this->_active=true;
  8608. }
  8609. catch(PDOException $e)
  8610. {
  8611. if(YII_DEBUG)
  8612. {
  8613. throw new CDbException('CDbConnection failed to open the DB connection: '.
  8614. $e->getMessage(),(int)$e->getCode(),$e->errorInfo);
  8615. }
  8616. else
  8617. {
  8618. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  8619. throw new CDbException('CDbConnection failed to open the DB connection.',(int)$e->getCode(),$e->errorInfo);
  8620. }
  8621. }
  8622. }
  8623. }
  8624. protected function close()
  8625. {
  8626. $this->_pdo=null;
  8627. $this->_active=false;
  8628. $this->_schema=null;
  8629. }
  8630. protected function createPdoInstance()
  8631. {
  8632. $pdoClass=$this->pdoClass;
  8633. if(($driver=$this->getDriverName())!==null)
  8634. {
  8635. if($driver==='mssql' || $driver==='dblib')
  8636. $pdoClass='CMssqlPdoAdapter';
  8637. elseif($driver==='sqlsrv')
  8638. $pdoClass='CMssqlSqlsrvPdoAdapter';
  8639. }
  8640. if(!class_exists($pdoClass))
  8641. throw new CDbException(Yii::t('yii','CDbConnection is unable to find PDO class "{className}". Make sure PDO is installed correctly.',
  8642. array('{className}'=>$pdoClass)));
  8643. @$instance=new $pdoClass($this->connectionString,$this->username,$this->password,$this->_attributes);
  8644. if(!$instance)
  8645. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'));
  8646. return $instance;
  8647. }
  8648. protected function initConnection($pdo)
  8649. {
  8650. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  8651. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  8652. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  8653. if($this->charset!==null)
  8654. {
  8655. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  8656. if(in_array($driver,array('pgsql','mysql','mysqli')))
  8657. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  8658. }
  8659. if($this->initSQLs!==null)
  8660. {
  8661. foreach($this->initSQLs as $sql)
  8662. $pdo->exec($sql);
  8663. }
  8664. }
  8665. public function getPdoInstance()
  8666. {
  8667. return $this->_pdo;
  8668. }
  8669. public function createCommand($query=null)
  8670. {
  8671. $this->setActive(true);
  8672. return new CDbCommand($this,$query);
  8673. }
  8674. public function getCurrentTransaction()
  8675. {
  8676. if($this->_transaction!==null)
  8677. {
  8678. if($this->_transaction->getActive())
  8679. return $this->_transaction;
  8680. }
  8681. return null;
  8682. }
  8683. public function beginTransaction()
  8684. {
  8685. $this->setActive(true);
  8686. $this->_pdo->beginTransaction();
  8687. return $this->_transaction=new CDbTransaction($this);
  8688. }
  8689. public function getSchema()
  8690. {
  8691. if($this->_schema!==null)
  8692. return $this->_schema;
  8693. else
  8694. {
  8695. $driver=$this->getDriverName();
  8696. if(isset($this->driverMap[$driver]))
  8697. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  8698. else
  8699. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  8700. array('{driver}'=>$driver)));
  8701. }
  8702. }
  8703. public function getCommandBuilder()
  8704. {
  8705. return $this->getSchema()->getCommandBuilder();
  8706. }
  8707. public function getLastInsertID($sequenceName='')
  8708. {
  8709. $this->setActive(true);
  8710. return $this->_pdo->lastInsertId($sequenceName);
  8711. }
  8712. public function quoteValue($str)
  8713. {
  8714. if(is_int($str) || is_float($str))
  8715. return $str;
  8716. $this->setActive(true);
  8717. if(($value=$this->_pdo->quote($str))!==false)
  8718. return $value;
  8719. else // the driver doesn't support quote (e.g. oci)
  8720. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  8721. }
  8722. public function quoteTableName($name)
  8723. {
  8724. return $this->getSchema()->quoteTableName($name);
  8725. }
  8726. public function quoteColumnName($name)
  8727. {
  8728. return $this->getSchema()->quoteColumnName($name);
  8729. }
  8730. public function getPdoType($type)
  8731. {
  8732. static $map=array
  8733. (
  8734. 'boolean'=>PDO::PARAM_BOOL,
  8735. 'integer'=>PDO::PARAM_INT,
  8736. 'string'=>PDO::PARAM_STR,
  8737. 'resource'=>PDO::PARAM_LOB,
  8738. 'NULL'=>PDO::PARAM_NULL,
  8739. );
  8740. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  8741. }
  8742. public function getColumnCase()
  8743. {
  8744. return $this->getAttribute(PDO::ATTR_CASE);
  8745. }
  8746. public function setColumnCase($value)
  8747. {
  8748. $this->setAttribute(PDO::ATTR_CASE,$value);
  8749. }
  8750. public function getNullConversion()
  8751. {
  8752. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  8753. }
  8754. public function setNullConversion($value)
  8755. {
  8756. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  8757. }
  8758. public function getAutoCommit()
  8759. {
  8760. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  8761. }
  8762. public function setAutoCommit($value)
  8763. {
  8764. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  8765. }
  8766. public function getPersistent()
  8767. {
  8768. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  8769. }
  8770. public function setPersistent($value)
  8771. {
  8772. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  8773. }
  8774. public function getDriverName()
  8775. {
  8776. if($this->_driverName!==null)
  8777. return $this->_driverName;
  8778. elseif(($pos=strpos($this->connectionString,':'))!==false)
  8779. return $this->_driverName=strtolower(substr($this->connectionString,0,$pos));
  8780. //return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  8781. }
  8782. public function setDriverName($driverName)
  8783. {
  8784. $this->_driverName=strtolower($driverName);
  8785. }
  8786. public function getClientVersion()
  8787. {
  8788. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  8789. }
  8790. public function getConnectionStatus()
  8791. {
  8792. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  8793. }
  8794. public function getPrefetch()
  8795. {
  8796. return $this->getAttribute(PDO::ATTR_PREFETCH);
  8797. }
  8798. public function getServerInfo()
  8799. {
  8800. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  8801. }
  8802. public function getServerVersion()
  8803. {
  8804. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  8805. }
  8806. public function getTimeout()
  8807. {
  8808. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  8809. }
  8810. public function getAttribute($name)
  8811. {
  8812. $this->setActive(true);
  8813. return $this->_pdo->getAttribute($name);
  8814. }
  8815. public function setAttribute($name,$value)
  8816. {
  8817. if($this->_pdo instanceof PDO)
  8818. $this->_pdo->setAttribute($name,$value);
  8819. else
  8820. $this->_attributes[$name]=$value;
  8821. }
  8822. public function getAttributes()
  8823. {
  8824. return $this->_attributes;
  8825. }
  8826. public function setAttributes($values)
  8827. {
  8828. foreach($values as $name=>$value)
  8829. $this->_attributes[$name]=$value;
  8830. }
  8831. public function getStats()
  8832. {
  8833. $logger=Yii::getLogger();
  8834. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  8835. $count=count($timings);
  8836. $time=array_sum($timings);
  8837. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  8838. $count+=count($timings);
  8839. $time+=array_sum($timings);
  8840. return array($count,$time);
  8841. }
  8842. }
  8843. abstract class CDbSchema extends CComponent
  8844. {
  8845. public $columnTypes=array();
  8846. private $_tableNames=array();
  8847. private $_tables=array();
  8848. private $_connection;
  8849. private $_builder;
  8850. private $_cacheExclude=array();
  8851. abstract protected function loadTable($name);
  8852. public function __construct($conn)
  8853. {
  8854. $this->_connection=$conn;
  8855. foreach($conn->schemaCachingExclude as $name)
  8856. $this->_cacheExclude[$name]=true;
  8857. }
  8858. public function getDbConnection()
  8859. {
  8860. return $this->_connection;
  8861. }
  8862. public function getTable($name,$refresh=false)
  8863. {
  8864. if($refresh===false && isset($this->_tables[$name]))
  8865. return $this->_tables[$name];
  8866. else
  8867. {
  8868. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  8869. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  8870. else
  8871. $realName=$name;
  8872. // temporarily disable query caching
  8873. if($this->_connection->queryCachingDuration>0)
  8874. {
  8875. $qcDuration=$this->_connection->queryCachingDuration;
  8876. $this->_connection->queryCachingDuration=0;
  8877. }
  8878. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8879. {
  8880. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8881. $table=$cache->get($key);
  8882. if($refresh===true || $table===false)
  8883. {
  8884. $table=$this->loadTable($realName);
  8885. if($table!==null)
  8886. $cache->set($key,$table,$duration);
  8887. }
  8888. $this->_tables[$name]=$table;
  8889. }
  8890. else
  8891. $this->_tables[$name]=$table=$this->loadTable($realName);
  8892. if(isset($qcDuration)) // re-enable query caching
  8893. $this->_connection->queryCachingDuration=$qcDuration;
  8894. return $table;
  8895. }
  8896. }
  8897. public function getTables($schema='')
  8898. {
  8899. $tables=array();
  8900. foreach($this->getTableNames($schema) as $name)
  8901. {
  8902. if(($table=$this->getTable($name))!==null)
  8903. $tables[$name]=$table;
  8904. }
  8905. return $tables;
  8906. }
  8907. public function getTableNames($schema='')
  8908. {
  8909. if(!isset($this->_tableNames[$schema]))
  8910. $this->_tableNames[$schema]=$this->findTableNames($schema);
  8911. return $this->_tableNames[$schema];
  8912. }
  8913. public function getCommandBuilder()
  8914. {
  8915. if($this->_builder!==null)
  8916. return $this->_builder;
  8917. else
  8918. return $this->_builder=$this->createCommandBuilder();
  8919. }
  8920. public function refresh()
  8921. {
  8922. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8923. {
  8924. foreach(array_keys($this->_tables) as $name)
  8925. {
  8926. if(!isset($this->_cacheExclude[$name]))
  8927. {
  8928. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8929. $cache->delete($key);
  8930. }
  8931. }
  8932. }
  8933. $this->_tables=array();
  8934. $this->_tableNames=array();
  8935. $this->_builder=null;
  8936. }
  8937. public function quoteTableName($name)
  8938. {
  8939. if(strpos($name,'.')===false)
  8940. return $this->quoteSimpleTableName($name);
  8941. $parts=explode('.',$name);
  8942. foreach($parts as $i=>$part)
  8943. $parts[$i]=$this->quoteSimpleTableName($part);
  8944. return implode('.',$parts);
  8945. }
  8946. public function quoteSimpleTableName($name)
  8947. {
  8948. return "'".$name."'";
  8949. }
  8950. public function quoteColumnName($name)
  8951. {
  8952. if(($pos=strrpos($name,'.'))!==false)
  8953. {
  8954. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  8955. $name=substr($name,$pos+1);
  8956. }
  8957. else
  8958. $prefix='';
  8959. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  8960. }
  8961. public function quoteSimpleColumnName($name)
  8962. {
  8963. return '"'.$name.'"';
  8964. }
  8965. public function compareTableNames($name1,$name2)
  8966. {
  8967. $name1=str_replace(array('"','`',"'"),'',$name1);
  8968. $name2=str_replace(array('"','`',"'"),'',$name2);
  8969. if(($pos=strrpos($name1,'.'))!==false)
  8970. $name1=substr($name1,$pos+1);
  8971. if(($pos=strrpos($name2,'.'))!==false)
  8972. $name2=substr($name2,$pos+1);
  8973. if($this->_connection->tablePrefix!==null)
  8974. {
  8975. if(strpos($name1,'{')!==false)
  8976. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  8977. if(strpos($name2,'{')!==false)
  8978. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  8979. }
  8980. return $name1===$name2;
  8981. }
  8982. public function resetSequence($table,$value=null)
  8983. {
  8984. }
  8985. public function checkIntegrity($check=true,$schema='')
  8986. {
  8987. }
  8988. protected function createCommandBuilder()
  8989. {
  8990. return new CDbCommandBuilder($this);
  8991. }
  8992. protected function findTableNames($schema='')
  8993. {
  8994. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  8995. array('{class}'=>get_class($this))));
  8996. }
  8997. public function getColumnType($type)
  8998. {
  8999. if(isset($this->columnTypes[$type]))
  9000. return $this->columnTypes[$type];
  9001. elseif(($pos=strpos($type,' '))!==false)
  9002. {
  9003. $t=substr($type,0,$pos);
  9004. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  9005. }
  9006. else
  9007. return $type;
  9008. }
  9009. public function createTable($table,$columns,$options=null)
  9010. {
  9011. $cols=array();
  9012. foreach($columns as $name=>$type)
  9013. {
  9014. if(is_string($name))
  9015. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  9016. else
  9017. $cols[]="\t".$type;
  9018. }
  9019. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  9020. return $options===null ? $sql : $sql.' '.$options;
  9021. }
  9022. public function renameTable($table,$newName)
  9023. {
  9024. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  9025. }
  9026. public function dropTable($table)
  9027. {
  9028. return "DROP TABLE ".$this->quoteTableName($table);
  9029. }
  9030. public function truncateTable($table)
  9031. {
  9032. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  9033. }
  9034. public function addColumn($table,$column,$type)
  9035. {
  9036. return 'ALTER TABLE ' . $this->quoteTableName($table)
  9037. . ' ADD ' . $this->quoteColumnName($column) . ' '
  9038. . $this->getColumnType($type);
  9039. }
  9040. public function dropColumn($table,$column)
  9041. {
  9042. return "ALTER TABLE ".$this->quoteTableName($table)
  9043. ." DROP COLUMN ".$this->quoteColumnName($column);
  9044. }
  9045. public function renameColumn($table,$name,$newName)
  9046. {
  9047. return "ALTER TABLE ".$this->quoteTableName($table)
  9048. . " RENAME COLUMN ".$this->quoteColumnName($name)
  9049. . " TO ".$this->quoteColumnName($newName);
  9050. }
  9051. public function alterColumn($table,$column,$type)
  9052. {
  9053. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  9054. . $this->quoteColumnName($column) . ' '
  9055. . $this->quoteColumnName($column) . ' '
  9056. . $this->getColumnType($type);
  9057. }
  9058. public function addForeignKey($name,$table,$columns,$refTable,$refColumns,$delete=null,$update=null)
  9059. {
  9060. if(is_string($columns))
  9061. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9062. foreach($columns as $i=>$col)
  9063. $columns[$i]=$this->quoteColumnName($col);
  9064. if(is_string($refColumns))
  9065. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  9066. foreach($refColumns as $i=>$col)
  9067. $refColumns[$i]=$this->quoteColumnName($col);
  9068. $sql='ALTER TABLE '.$this->quoteTableName($table)
  9069. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  9070. .' FOREIGN KEY ('.implode(', ',$columns).')'
  9071. .' REFERENCES '.$this->quoteTableName($refTable)
  9072. .' ('.implode(', ',$refColumns).')';
  9073. if($delete!==null)
  9074. $sql.=' ON DELETE '.$delete;
  9075. if($update!==null)
  9076. $sql.=' ON UPDATE '.$update;
  9077. return $sql;
  9078. }
  9079. public function dropForeignKey($name,$table)
  9080. {
  9081. return 'ALTER TABLE '.$this->quoteTableName($table)
  9082. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  9083. }
  9084. public function createIndex($name,$table,$columns,$unique=false)
  9085. {
  9086. $cols=array();
  9087. if(is_string($columns))
  9088. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9089. foreach($columns as $col)
  9090. {
  9091. if(strpos($col,'(')!==false)
  9092. $cols[]=$col;
  9093. else
  9094. $cols[]=$this->quoteColumnName($col);
  9095. }
  9096. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  9097. . $this->quoteTableName($name).' ON '
  9098. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  9099. }
  9100. public function dropIndex($name,$table)
  9101. {
  9102. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  9103. }
  9104. public function addPrimaryKey($name,$table,$columns)
  9105. {
  9106. if(is_string($columns))
  9107. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9108. foreach($columns as $i=>$col)
  9109. $columns[$i]=$this->quoteColumnName($col);
  9110. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' ADD CONSTRAINT '
  9111. . $this->quoteColumnName($name) . ' PRIMARY KEY ('
  9112. . implode(', ',$columns). ' )';
  9113. }
  9114. public function dropPrimaryKey($name,$table)
  9115. {
  9116. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' DROP CONSTRAINT '
  9117. . $this->quoteColumnName($name);
  9118. }
  9119. }
  9120. class CSqliteSchema extends CDbSchema
  9121. {
  9122. public $columnTypes=array(
  9123. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  9124. 'bigpk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  9125. 'string' => 'varchar(255)',
  9126. 'text' => 'text',
  9127. 'integer' => 'integer',
  9128. 'bigint' => 'integer',
  9129. 'float' => 'float',
  9130. 'decimal' => 'decimal',
  9131. 'datetime' => 'datetime',
  9132. 'timestamp' => 'timestamp',
  9133. 'time' => 'time',
  9134. 'date' => 'date',
  9135. 'binary' => 'blob',
  9136. 'boolean' => 'tinyint(1)',
  9137. 'money' => 'decimal(19,4)',
  9138. );
  9139. public function resetSequence($table,$value=null)
  9140. {
  9141. if($table->sequenceName===null)
  9142. return;
  9143. if($value!==null)
  9144. $value=(int)($value)-1;
  9145. else
  9146. $value=(int)$this->getDbConnection()
  9147. ->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")
  9148. ->queryScalar();
  9149. try
  9150. {
  9151. // it's possible that 'sqlite_sequence' does not exist
  9152. $this->getDbConnection()
  9153. ->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")
  9154. ->execute();
  9155. }
  9156. catch(Exception $e)
  9157. {
  9158. }
  9159. }
  9160. public function checkIntegrity($check=true,$schema='')
  9161. {
  9162. $this->getDbConnection()->createCommand('PRAGMA foreign_keys='.(int)$check)->execute();
  9163. }
  9164. protected function findTableNames($schema='')
  9165. {
  9166. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  9167. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  9168. }
  9169. protected function createCommandBuilder()
  9170. {
  9171. return new CSqliteCommandBuilder($this);
  9172. }
  9173. protected function loadTable($name)
  9174. {
  9175. $table=new CDbTableSchema;
  9176. $table->name=$name;
  9177. $table->rawName=$this->quoteTableName($name);
  9178. if($this->findColumns($table))
  9179. {
  9180. $this->findConstraints($table);
  9181. return $table;
  9182. }
  9183. else
  9184. return null;
  9185. }
  9186. protected function findColumns($table)
  9187. {
  9188. $sql="PRAGMA table_info({$table->rawName})";
  9189. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  9190. if(empty($columns))
  9191. return false;
  9192. foreach($columns as $column)
  9193. {
  9194. $c=$this->createColumn($column);
  9195. $table->columns[$c->name]=$c;
  9196. if($c->isPrimaryKey)
  9197. {
  9198. if($table->primaryKey===null)
  9199. $table->primaryKey=$c->name;
  9200. elseif(is_string($table->primaryKey))
  9201. $table->primaryKey=array($table->primaryKey,$c->name);
  9202. else
  9203. $table->primaryKey[]=$c->name;
  9204. }
  9205. }
  9206. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  9207. {
  9208. $table->sequenceName='';
  9209. $table->columns[$table->primaryKey]->autoIncrement=true;
  9210. }
  9211. return true;
  9212. }
  9213. protected function findConstraints($table)
  9214. {
  9215. $foreignKeys=array();
  9216. $sql="PRAGMA foreign_key_list({$table->rawName})";
  9217. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  9218. foreach($keys as $key)
  9219. {
  9220. $column=$table->columns[$key['from']];
  9221. $column->isForeignKey=true;
  9222. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  9223. }
  9224. $table->foreignKeys=$foreignKeys;
  9225. }
  9226. protected function createColumn($column)
  9227. {
  9228. $c=new CSqliteColumnSchema;
  9229. $c->name=$column['name'];
  9230. $c->rawName=$this->quoteColumnName($c->name);
  9231. $c->allowNull=!$column['notnull'];
  9232. $c->isPrimaryKey=$column['pk']!=0;
  9233. $c->isForeignKey=false;
  9234. $c->comment=null; // SQLite does not support column comments at all
  9235. $c->init(strtolower($column['type']),$column['dflt_value']);
  9236. return $c;
  9237. }
  9238. public function renameTable($table, $newName)
  9239. {
  9240. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' RENAME TO ' . $this->quoteTableName($newName);
  9241. }
  9242. public function truncateTable($table)
  9243. {
  9244. return "DELETE FROM ".$this->quoteTableName($table);
  9245. }
  9246. public function dropColumn($table, $column)
  9247. {
  9248. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  9249. }
  9250. public function renameColumn($table, $name, $newName)
  9251. {
  9252. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  9253. }
  9254. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9255. {
  9256. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  9257. }
  9258. public function dropForeignKey($name, $table)
  9259. {
  9260. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  9261. }
  9262. public function alterColumn($table, $column, $type)
  9263. {
  9264. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  9265. }
  9266. public function dropIndex($name, $table)
  9267. {
  9268. return 'DROP INDEX '.$this->quoteTableName($name);
  9269. }
  9270. public function addPrimaryKey($name,$table,$columns)
  9271. {
  9272. throw new CDbException(Yii::t('yii', 'Adding a primary key after table has been created is not supported by SQLite.'));
  9273. }
  9274. public function dropPrimaryKey($name,$table)
  9275. {
  9276. throw new CDbException(Yii::t('yii', 'Removing a primary key after table has been created is not supported by SQLite.'));
  9277. }
  9278. }
  9279. class CDbTableSchema extends CComponent
  9280. {
  9281. public $name;
  9282. public $rawName;
  9283. public $primaryKey;
  9284. public $sequenceName;
  9285. public $foreignKeys=array();
  9286. public $columns=array();
  9287. public function getColumn($name)
  9288. {
  9289. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  9290. }
  9291. public function getColumnNames()
  9292. {
  9293. return array_keys($this->columns);
  9294. }
  9295. }
  9296. class CDbCommand extends CComponent
  9297. {
  9298. public $params=array();
  9299. private $_connection;
  9300. private $_text;
  9301. private $_statement;
  9302. private $_paramLog=array();
  9303. private $_query;
  9304. private $_fetchMode = array(PDO::FETCH_ASSOC);
  9305. public function __construct(CDbConnection $connection,$query=null)
  9306. {
  9307. $this->_connection=$connection;
  9308. if(is_array($query))
  9309. {
  9310. foreach($query as $name=>$value)
  9311. $this->$name=$value;
  9312. }
  9313. else
  9314. $this->setText($query);
  9315. }
  9316. public function __sleep()
  9317. {
  9318. $this->_statement=null;
  9319. return array_keys(get_object_vars($this));
  9320. }
  9321. public function setFetchMode($mode)
  9322. {
  9323. $params=func_get_args();
  9324. $this->_fetchMode = $params;
  9325. return $this;
  9326. }
  9327. public function reset()
  9328. {
  9329. $this->_text=null;
  9330. $this->_query=null;
  9331. $this->_statement=null;
  9332. $this->_paramLog=array();
  9333. $this->params=array();
  9334. return $this;
  9335. }
  9336. public function getText()
  9337. {
  9338. if($this->_text=='' && !empty($this->_query))
  9339. $this->setText($this->buildQuery($this->_query));
  9340. return $this->_text;
  9341. }
  9342. public function setText($value)
  9343. {
  9344. if($this->_connection->tablePrefix!==null && $value!='')
  9345. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  9346. else
  9347. $this->_text=$value;
  9348. $this->cancel();
  9349. return $this;
  9350. }
  9351. public function getConnection()
  9352. {
  9353. return $this->_connection;
  9354. }
  9355. public function getPdoStatement()
  9356. {
  9357. return $this->_statement;
  9358. }
  9359. public function prepare()
  9360. {
  9361. if($this->_statement==null)
  9362. {
  9363. try
  9364. {
  9365. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  9366. $this->_paramLog=array();
  9367. }
  9368. catch(Exception $e)
  9369. {
  9370. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9371. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9372. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  9373. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  9374. }
  9375. }
  9376. }
  9377. public function cancel()
  9378. {
  9379. $this->_statement=null;
  9380. }
  9381. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  9382. {
  9383. $this->prepare();
  9384. if($dataType===null)
  9385. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  9386. elseif($length===null)
  9387. $this->_statement->bindParam($name,$value,$dataType);
  9388. elseif($driverOptions===null)
  9389. $this->_statement->bindParam($name,$value,$dataType,$length);
  9390. else
  9391. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  9392. $this->_paramLog[$name]=&$value;
  9393. return $this;
  9394. }
  9395. public function bindValue($name, $value, $dataType=null)
  9396. {
  9397. $this->prepare();
  9398. if($dataType===null)
  9399. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  9400. else
  9401. $this->_statement->bindValue($name,$value,$dataType);
  9402. $this->_paramLog[$name]=$value;
  9403. return $this;
  9404. }
  9405. public function bindValues($values)
  9406. {
  9407. $this->prepare();
  9408. foreach($values as $name=>$value)
  9409. {
  9410. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  9411. $this->_paramLog[$name]=$value;
  9412. }
  9413. return $this;
  9414. }
  9415. public function execute($params=array())
  9416. {
  9417. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  9418. {
  9419. $p=array();
  9420. foreach($pars as $name=>$value)
  9421. $p[$name]=$name.'='.var_export($value,true);
  9422. $par='. Bound with ' .implode(', ',$p);
  9423. }
  9424. else
  9425. $par='';
  9426. try
  9427. {
  9428. if($this->_connection->enableProfiling)
  9429. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9430. $this->prepare();
  9431. if($params===array())
  9432. $this->_statement->execute();
  9433. else
  9434. $this->_statement->execute($params);
  9435. $n=$this->_statement->rowCount();
  9436. if($this->_connection->enableProfiling)
  9437. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9438. return $n;
  9439. }
  9440. catch(Exception $e)
  9441. {
  9442. if($this->_connection->enableProfiling)
  9443. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9444. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9445. $message=$e->getMessage();
  9446. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  9447. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9448. if(YII_DEBUG)
  9449. $message.='. The SQL statement executed was: '.$this->getText().$par;
  9450. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  9451. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  9452. }
  9453. }
  9454. public function query($params=array())
  9455. {
  9456. return $this->queryInternal('',0,$params);
  9457. }
  9458. public function queryAll($fetchAssociative=true,$params=array())
  9459. {
  9460. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  9461. }
  9462. public function queryRow($fetchAssociative=true,$params=array())
  9463. {
  9464. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  9465. }
  9466. public function queryScalar($params=array())
  9467. {
  9468. $result=$this->queryInternal('fetchColumn',0,$params);
  9469. if(is_resource($result) && get_resource_type($result)==='stream')
  9470. return stream_get_contents($result);
  9471. else
  9472. return $result;
  9473. }
  9474. public function queryColumn($params=array())
  9475. {
  9476. return $this->queryInternal('fetchAll',array(PDO::FETCH_COLUMN, 0),$params);
  9477. }
  9478. private function queryInternal($method,$mode,$params=array())
  9479. {
  9480. $params=array_merge($this->params,$params);
  9481. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  9482. {
  9483. $p=array();
  9484. foreach($pars as $name=>$value)
  9485. $p[$name]=$name.'='.var_export($value,true);
  9486. $par='. Bound with '.implode(', ',$p);
  9487. }
  9488. else
  9489. $par='';
  9490. if($this->_connection->queryCachingCount>0 && $method!==''
  9491. && $this->_connection->queryCachingDuration>0
  9492. && $this->_connection->queryCacheID!==false
  9493. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  9494. {
  9495. $this->_connection->queryCachingCount--;
  9496. $cacheKey='yii:dbquery'.':'.$method.':'.$this->_connection->connectionString.':'.$this->_connection->username;
  9497. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  9498. if(($result=$cache->get($cacheKey))!==false)
  9499. {
  9500. return $result[0];
  9501. }
  9502. }
  9503. try
  9504. {
  9505. if($this->_connection->enableProfiling)
  9506. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9507. $this->prepare();
  9508. if($params===array())
  9509. $this->_statement->execute();
  9510. else
  9511. $this->_statement->execute($params);
  9512. if($method==='')
  9513. $result=new CDbDataReader($this);
  9514. else
  9515. {
  9516. $mode=(array)$mode;
  9517. call_user_func_array(array($this->_statement, 'setFetchMode'), $mode);
  9518. $result=$this->_statement->$method();
  9519. $this->_statement->closeCursor();
  9520. }
  9521. if($this->_connection->enableProfiling)
  9522. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9523. if(isset($cache,$cacheKey))
  9524. $cache->set($cacheKey, array($result), $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  9525. return $result;
  9526. }
  9527. catch(Exception $e)
  9528. {
  9529. if($this->_connection->enableProfiling)
  9530. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9531. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9532. $message=$e->getMessage();
  9533. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  9534. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9535. if(YII_DEBUG)
  9536. $message.='. The SQL statement executed was: '.$this->getText().$par;
  9537. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  9538. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  9539. }
  9540. }
  9541. public function buildQuery($query)
  9542. {
  9543. $sql=!empty($query['distinct']) ? 'SELECT DISTINCT' : 'SELECT';
  9544. $sql.=' '.(!empty($query['select']) ? $query['select'] : '*');
  9545. if(!empty($query['from']))
  9546. $sql.="\nFROM ".$query['from'];
  9547. if(!empty($query['join']))
  9548. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  9549. if(!empty($query['where']))
  9550. $sql.="\nWHERE ".$query['where'];
  9551. if(!empty($query['group']))
  9552. $sql.="\nGROUP BY ".$query['group'];
  9553. if(!empty($query['having']))
  9554. $sql.="\nHAVING ".$query['having'];
  9555. if(!empty($query['union']))
  9556. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  9557. if(!empty($query['order']))
  9558. $sql.="\nORDER BY ".$query['order'];
  9559. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  9560. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  9561. if($limit>=0 || $offset>0)
  9562. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  9563. return $sql;
  9564. }
  9565. public function select($columns='*', $option='')
  9566. {
  9567. if(is_string($columns) && strpos($columns,'(')!==false)
  9568. $this->_query['select']=$columns;
  9569. else
  9570. {
  9571. if(!is_array($columns))
  9572. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9573. foreach($columns as $i=>$column)
  9574. {
  9575. if(is_object($column))
  9576. $columns[$i]=(string)$column;
  9577. elseif(strpos($column,'(')===false)
  9578. {
  9579. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  9580. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  9581. else
  9582. $columns[$i]=$this->_connection->quoteColumnName($column);
  9583. }
  9584. }
  9585. $this->_query['select']=implode(', ',$columns);
  9586. }
  9587. if($option!='')
  9588. $this->_query['select']=$option.' '.$this->_query['select'];
  9589. return $this;
  9590. }
  9591. public function getSelect()
  9592. {
  9593. return isset($this->_query['select']) ? $this->_query['select'] : '';
  9594. }
  9595. public function setSelect($value)
  9596. {
  9597. $this->select($value);
  9598. }
  9599. public function selectDistinct($columns='*')
  9600. {
  9601. $this->_query['distinct']=true;
  9602. return $this->select($columns);
  9603. }
  9604. public function getDistinct()
  9605. {
  9606. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  9607. }
  9608. public function setDistinct($value)
  9609. {
  9610. $this->_query['distinct']=$value;
  9611. }
  9612. public function from($tables)
  9613. {
  9614. if(is_string($tables) && strpos($tables,'(')!==false)
  9615. $this->_query['from']=$tables;
  9616. else
  9617. {
  9618. if(!is_array($tables))
  9619. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  9620. foreach($tables as $i=>$table)
  9621. {
  9622. if(strpos($table,'(')===false)
  9623. {
  9624. if(preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/',$table,$matches)) // with alias
  9625. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9626. else
  9627. $tables[$i]=$this->_connection->quoteTableName($table);
  9628. }
  9629. }
  9630. $this->_query['from']=implode(', ',$tables);
  9631. }
  9632. return $this;
  9633. }
  9634. public function getFrom()
  9635. {
  9636. return isset($this->_query['from']) ? $this->_query['from'] : '';
  9637. }
  9638. public function setFrom($value)
  9639. {
  9640. $this->from($value);
  9641. }
  9642. public function where($conditions, $params=array())
  9643. {
  9644. $this->_query['where']=$this->processConditions($conditions);
  9645. foreach($params as $name=>$value)
  9646. $this->params[$name]=$value;
  9647. return $this;
  9648. }
  9649. public function andWhere($conditions,$params=array())
  9650. {
  9651. if(isset($this->_query['where']))
  9652. $this->_query['where']=$this->processConditions(array('AND',$this->_query['where'],$conditions));
  9653. else
  9654. $this->_query['where']=$this->processConditions($conditions);
  9655. foreach($params as $name=>$value)
  9656. $this->params[$name]=$value;
  9657. return $this;
  9658. }
  9659. public function orWhere($conditions,$params=array())
  9660. {
  9661. if(isset($this->_query['where']))
  9662. $this->_query['where']=$this->processConditions(array('OR',$this->_query['where'],$conditions));
  9663. else
  9664. $this->_query['where']=$this->processConditions($conditions);
  9665. foreach($params as $name=>$value)
  9666. $this->params[$name]=$value;
  9667. return $this;
  9668. }
  9669. public function getWhere()
  9670. {
  9671. return isset($this->_query['where']) ? $this->_query['where'] : '';
  9672. }
  9673. public function setWhere($value)
  9674. {
  9675. $this->where($value);
  9676. }
  9677. public function join($table, $conditions, $params=array())
  9678. {
  9679. return $this->joinInternal('join', $table, $conditions, $params);
  9680. }
  9681. public function getJoin()
  9682. {
  9683. return isset($this->_query['join']) ? $this->_query['join'] : '';
  9684. }
  9685. public function setJoin($value)
  9686. {
  9687. $this->_query['join']=$value;
  9688. }
  9689. public function leftJoin($table, $conditions, $params=array())
  9690. {
  9691. return $this->joinInternal('left join', $table, $conditions, $params);
  9692. }
  9693. public function rightJoin($table, $conditions, $params=array())
  9694. {
  9695. return $this->joinInternal('right join', $table, $conditions, $params);
  9696. }
  9697. public function crossJoin($table)
  9698. {
  9699. return $this->joinInternal('cross join', $table);
  9700. }
  9701. public function naturalJoin($table)
  9702. {
  9703. return $this->joinInternal('natural join', $table);
  9704. }
  9705. public function naturalLeftJoin($table)
  9706. {
  9707. return $this->joinInternal('natural left join', $table);
  9708. }
  9709. public function naturalRightJoin($table)
  9710. {
  9711. return $this->joinInternal('natural right join', $table);
  9712. }
  9713. public function group($columns)
  9714. {
  9715. if(is_string($columns) && strpos($columns,'(')!==false)
  9716. $this->_query['group']=$columns;
  9717. else
  9718. {
  9719. if(!is_array($columns))
  9720. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9721. foreach($columns as $i=>$column)
  9722. {
  9723. if(is_object($column))
  9724. $columns[$i]=(string)$column;
  9725. elseif(strpos($column,'(')===false)
  9726. $columns[$i]=$this->_connection->quoteColumnName($column);
  9727. }
  9728. $this->_query['group']=implode(', ',$columns);
  9729. }
  9730. return $this;
  9731. }
  9732. public function getGroup()
  9733. {
  9734. return isset($this->_query['group']) ? $this->_query['group'] : '';
  9735. }
  9736. public function setGroup($value)
  9737. {
  9738. $this->group($value);
  9739. }
  9740. public function having($conditions, $params=array())
  9741. {
  9742. $this->_query['having']=$this->processConditions($conditions);
  9743. foreach($params as $name=>$value)
  9744. $this->params[$name]=$value;
  9745. return $this;
  9746. }
  9747. public function getHaving()
  9748. {
  9749. return isset($this->_query['having']) ? $this->_query['having'] : '';
  9750. }
  9751. public function setHaving($value)
  9752. {
  9753. $this->having($value);
  9754. }
  9755. public function order($columns)
  9756. {
  9757. if(is_string($columns) && strpos($columns,'(')!==false)
  9758. $this->_query['order']=$columns;
  9759. else
  9760. {
  9761. if(!is_array($columns))
  9762. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9763. foreach($columns as $i=>$column)
  9764. {
  9765. if(is_object($column))
  9766. $columns[$i]=(string)$column;
  9767. elseif(strpos($column,'(')===false)
  9768. {
  9769. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  9770. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  9771. else
  9772. $columns[$i]=$this->_connection->quoteColumnName($column);
  9773. }
  9774. }
  9775. $this->_query['order']=implode(', ',$columns);
  9776. }
  9777. return $this;
  9778. }
  9779. public function getOrder()
  9780. {
  9781. return isset($this->_query['order']) ? $this->_query['order'] : '';
  9782. }
  9783. public function setOrder($value)
  9784. {
  9785. $this->order($value);
  9786. }
  9787. public function limit($limit, $offset=null)
  9788. {
  9789. $this->_query['limit']=(int)$limit;
  9790. if($offset!==null)
  9791. $this->offset($offset);
  9792. return $this;
  9793. }
  9794. public function getLimit()
  9795. {
  9796. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  9797. }
  9798. public function setLimit($value)
  9799. {
  9800. $this->limit($value);
  9801. }
  9802. public function offset($offset)
  9803. {
  9804. $this->_query['offset']=(int)$offset;
  9805. return $this;
  9806. }
  9807. public function getOffset()
  9808. {
  9809. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  9810. }
  9811. public function setOffset($value)
  9812. {
  9813. $this->offset($value);
  9814. }
  9815. public function union($sql)
  9816. {
  9817. if(isset($this->_query['union']) && is_string($this->_query['union']))
  9818. $this->_query['union']=array($this->_query['union']);
  9819. $this->_query['union'][]=$sql;
  9820. return $this;
  9821. }
  9822. public function getUnion()
  9823. {
  9824. return isset($this->_query['union']) ? $this->_query['union'] : '';
  9825. }
  9826. public function setUnion($value)
  9827. {
  9828. $this->_query['union']=$value;
  9829. }
  9830. public function insert($table, $columns)
  9831. {
  9832. $params=array();
  9833. $names=array();
  9834. $placeholders=array();
  9835. foreach($columns as $name=>$value)
  9836. {
  9837. $names[]=$this->_connection->quoteColumnName($name);
  9838. if($value instanceof CDbExpression)
  9839. {
  9840. $placeholders[] = $value->expression;
  9841. foreach($value->params as $n => $v)
  9842. $params[$n] = $v;
  9843. }
  9844. else
  9845. {
  9846. $placeholders[] = ':' . $name;
  9847. $params[':' . $name] = $value;
  9848. }
  9849. }
  9850. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  9851. . ' (' . implode(', ',$names) . ') VALUES ('
  9852. . implode(', ', $placeholders) . ')';
  9853. return $this->setText($sql)->execute($params);
  9854. }
  9855. public function update($table, $columns, $conditions='', $params=array())
  9856. {
  9857. $lines=array();
  9858. foreach($columns as $name=>$value)
  9859. {
  9860. if($value instanceof CDbExpression)
  9861. {
  9862. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  9863. foreach($value->params as $n => $v)
  9864. $params[$n] = $v;
  9865. }
  9866. else
  9867. {
  9868. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  9869. $params[':' . $name]=$value;
  9870. }
  9871. }
  9872. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  9873. if(($where=$this->processConditions($conditions))!='')
  9874. $sql.=' WHERE '.$where;
  9875. return $this->setText($sql)->execute($params);
  9876. }
  9877. public function delete($table, $conditions='', $params=array())
  9878. {
  9879. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  9880. if(($where=$this->processConditions($conditions))!='')
  9881. $sql.=' WHERE '.$where;
  9882. return $this->setText($sql)->execute($params);
  9883. }
  9884. public function createTable($table, $columns, $options=null)
  9885. {
  9886. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  9887. }
  9888. public function renameTable($table, $newName)
  9889. {
  9890. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  9891. }
  9892. public function dropTable($table)
  9893. {
  9894. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  9895. }
  9896. public function truncateTable($table)
  9897. {
  9898. $schema=$this->getConnection()->getSchema();
  9899. $n=$this->setText($schema->truncateTable($table))->execute();
  9900. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  9901. $schema->resetSequence($schema->getTable($table));
  9902. return $n;
  9903. }
  9904. public function addColumn($table, $column, $type)
  9905. {
  9906. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  9907. }
  9908. public function dropColumn($table, $column)
  9909. {
  9910. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  9911. }
  9912. public function renameColumn($table, $name, $newName)
  9913. {
  9914. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  9915. }
  9916. public function alterColumn($table, $column, $type)
  9917. {
  9918. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  9919. }
  9920. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9921. {
  9922. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  9923. }
  9924. public function dropForeignKey($name, $table)
  9925. {
  9926. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  9927. }
  9928. public function createIndex($name, $table, $columns, $unique=false)
  9929. {
  9930. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $columns, $unique))->execute();
  9931. }
  9932. public function dropIndex($name, $table)
  9933. {
  9934. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  9935. }
  9936. private function processConditions($conditions)
  9937. {
  9938. if(!is_array($conditions))
  9939. return $conditions;
  9940. elseif($conditions===array())
  9941. return '';
  9942. $n=count($conditions);
  9943. $operator=strtoupper($conditions[0]);
  9944. if($operator==='OR' || $operator==='AND')
  9945. {
  9946. $parts=array();
  9947. for($i=1;$i<$n;++$i)
  9948. {
  9949. $condition=$this->processConditions($conditions[$i]);
  9950. if($condition!=='')
  9951. $parts[]='('.$condition.')';
  9952. }
  9953. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  9954. }
  9955. if(!isset($conditions[1],$conditions[2]))
  9956. return '';
  9957. $column=$conditions[1];
  9958. if(strpos($column,'(')===false)
  9959. $column=$this->_connection->quoteColumnName($column);
  9960. $values=$conditions[2];
  9961. if(!is_array($values))
  9962. $values=array($values);
  9963. if($operator==='IN' || $operator==='NOT IN')
  9964. {
  9965. if($values===array())
  9966. return $operator==='IN' ? '0=1' : '';
  9967. foreach($values as $i=>$value)
  9968. {
  9969. if(is_string($value))
  9970. $values[$i]=$this->_connection->quoteValue($value);
  9971. else
  9972. $values[$i]=(string)$value;
  9973. }
  9974. return $column.' '.$operator.' ('.implode(', ',$values).')';
  9975. }
  9976. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  9977. {
  9978. if($values===array())
  9979. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  9980. if($operator==='LIKE' || $operator==='NOT LIKE')
  9981. $andor=' AND ';
  9982. else
  9983. {
  9984. $andor=' OR ';
  9985. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  9986. }
  9987. $expressions=array();
  9988. foreach($values as $value)
  9989. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  9990. return implode($andor,$expressions);
  9991. }
  9992. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  9993. }
  9994. private function joinInternal($type, $table, $conditions='', $params=array())
  9995. {
  9996. if(strpos($table,'(')===false)
  9997. {
  9998. if(preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/',$table,$matches)) // with alias
  9999. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  10000. else
  10001. $table=$this->_connection->quoteTableName($table);
  10002. }
  10003. $conditions=$this->processConditions($conditions);
  10004. if($conditions!='')
  10005. $conditions=' ON '.$conditions;
  10006. if(isset($this->_query['join']) && is_string($this->_query['join']))
  10007. $this->_query['join']=array($this->_query['join']);
  10008. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  10009. foreach($params as $name=>$value)
  10010. $this->params[$name]=$value;
  10011. return $this;
  10012. }
  10013. public function addPrimaryKey($name,$table,$columns)
  10014. {
  10015. return $this->setText($this->getConnection()->getSchema()->addPrimaryKey($name,$table,$columns))->execute();
  10016. }
  10017. public function dropPrimaryKey($name,$table)
  10018. {
  10019. return $this->setText($this->getConnection()->getSchema()->dropPrimaryKey($name,$table))->execute();
  10020. }
  10021. }
  10022. class CDbColumnSchema extends CComponent
  10023. {
  10024. public $name;
  10025. public $rawName;
  10026. public $allowNull;
  10027. public $dbType;
  10028. public $type;
  10029. public $defaultValue;
  10030. public $size;
  10031. public $precision;
  10032. public $scale;
  10033. public $isPrimaryKey;
  10034. public $isForeignKey;
  10035. public $autoIncrement=false;
  10036. public $comment='';
  10037. public function init($dbType, $defaultValue)
  10038. {
  10039. $this->dbType=$dbType;
  10040. $this->extractType($dbType);
  10041. $this->extractLimit($dbType);
  10042. if($defaultValue!==null)
  10043. $this->extractDefault($defaultValue);
  10044. }
  10045. protected function extractType($dbType)
  10046. {
  10047. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  10048. $this->type='integer';
  10049. elseif(stripos($dbType,'bool')!==false)
  10050. $this->type='boolean';
  10051. elseif(preg_match('/(real|floa|doub)/i',$dbType))
  10052. $this->type='double';
  10053. else
  10054. $this->type='string';
  10055. }
  10056. protected function extractLimit($dbType)
  10057. {
  10058. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  10059. {
  10060. $values=explode(',',$matches[1]);
  10061. $this->size=$this->precision=(int)$values[0];
  10062. if(isset($values[1]))
  10063. $this->scale=(int)$values[1];
  10064. }
  10065. }
  10066. protected function extractDefault($defaultValue)
  10067. {
  10068. $this->defaultValue=$this->typecast($defaultValue);
  10069. }
  10070. public function typecast($value)
  10071. {
  10072. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  10073. return $value;
  10074. if($value==='' && $this->allowNull)
  10075. return $this->type==='string' ? '' : null;
  10076. switch($this->type)
  10077. {
  10078. case 'string': return (string)$value;
  10079. case 'integer': return (integer)$value;
  10080. case 'boolean': return (boolean)$value;
  10081. case 'double':
  10082. default: return $value;
  10083. }
  10084. }
  10085. }
  10086. class CSqliteColumnSchema extends CDbColumnSchema
  10087. {
  10088. protected function extractDefault($defaultValue)
  10089. {
  10090. if($this->dbType==='timestamp' && $defaultValue==='CURRENT_TIMESTAMP')
  10091. $this->defaultValue=null;
  10092. else
  10093. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  10094. if($this->type==='string' && $this->defaultValue!==null) // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  10095. $this->defaultValue=trim($this->defaultValue,"'\"");
  10096. }
  10097. }
  10098. abstract class CValidator extends CComponent
  10099. {
  10100. public static $builtInValidators=array(
  10101. 'required'=>'CRequiredValidator',
  10102. 'filter'=>'CFilterValidator',
  10103. 'match'=>'CRegularExpressionValidator',
  10104. 'email'=>'CEmailValidator',
  10105. 'url'=>'CUrlValidator',
  10106. 'unique'=>'CUniqueValidator',
  10107. 'compare'=>'CCompareValidator',
  10108. 'length'=>'CStringValidator',
  10109. 'in'=>'CRangeValidator',
  10110. 'numerical'=>'CNumberValidator',
  10111. 'captcha'=>'CCaptchaValidator',
  10112. 'type'=>'CTypeValidator',
  10113. 'file'=>'CFileValidator',
  10114. 'default'=>'CDefaultValueValidator',
  10115. 'exist'=>'CExistValidator',
  10116. 'boolean'=>'CBooleanValidator',
  10117. 'safe'=>'CSafeValidator',
  10118. 'unsafe'=>'CUnsafeValidator',
  10119. 'date'=>'CDateValidator',
  10120. );
  10121. public $attributes;
  10122. public $message;
  10123. public $skipOnError=false;
  10124. public $on;
  10125. public $except;
  10126. public $safe=true;
  10127. public $enableClientValidation=true;
  10128. abstract protected function validateAttribute($object,$attribute);
  10129. public static function createValidator($name,$object,$attributes,$params=array())
  10130. {
  10131. if(is_string($attributes))
  10132. $attributes=preg_split('/\s*,\s*/',trim($attributes, " \t\n\r\0\x0B,"),-1,PREG_SPLIT_NO_EMPTY);
  10133. if(isset($params['on']))
  10134. {
  10135. if(is_array($params['on']))
  10136. $on=$params['on'];
  10137. else
  10138. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  10139. }
  10140. else
  10141. $on=array();
  10142. if(isset($params['except']))
  10143. {
  10144. if(is_array($params['except']))
  10145. $except=$params['except'];
  10146. else
  10147. $except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
  10148. }
  10149. else
  10150. $except=array();
  10151. if(method_exists($object,$name))
  10152. {
  10153. $validator=new CInlineValidator;
  10154. $validator->attributes=$attributes;
  10155. $validator->method=$name;
  10156. if(isset($params['clientValidate']))
  10157. {
  10158. $validator->clientValidate=$params['clientValidate'];
  10159. unset($params['clientValidate']);
  10160. }
  10161. $validator->params=$params;
  10162. if(isset($params['skipOnError']))
  10163. $validator->skipOnError=$params['skipOnError'];
  10164. }
  10165. else
  10166. {
  10167. $params['attributes']=$attributes;
  10168. if(isset(self::$builtInValidators[$name]))
  10169. $className=Yii::import(self::$builtInValidators[$name],true);
  10170. else
  10171. $className=Yii::import($name,true);
  10172. $validator=new $className;
  10173. foreach($params as $name=>$value)
  10174. $validator->$name=$value;
  10175. }
  10176. $validator->on=empty($on) ? array() : array_combine($on,$on);
  10177. $validator->except=empty($except) ? array() : array_combine($except,$except);
  10178. return $validator;
  10179. }
  10180. public function validate($object,$attributes=null)
  10181. {
  10182. if(is_array($attributes))
  10183. $attributes=array_intersect($this->attributes,$attributes);
  10184. else
  10185. $attributes=$this->attributes;
  10186. foreach($attributes as $attribute)
  10187. {
  10188. if(!$this->skipOnError || !$object->hasErrors($attribute))
  10189. $this->validateAttribute($object,$attribute);
  10190. }
  10191. }
  10192. public function clientValidateAttribute($object,$attribute)
  10193. {
  10194. }
  10195. public function applyTo($scenario)
  10196. {
  10197. if(isset($this->except[$scenario]))
  10198. return false;
  10199. return empty($this->on) || isset($this->on[$scenario]);
  10200. }
  10201. protected function addError($object,$attribute,$message,$params=array())
  10202. {
  10203. $params['{attribute}']=$object->getAttributeLabel($attribute);
  10204. $object->addError($attribute,strtr($message,$params));
  10205. }
  10206. protected function isEmpty($value,$trim=false)
  10207. {
  10208. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  10209. }
  10210. }
  10211. class CStringValidator extends CValidator
  10212. {
  10213. public $max;
  10214. public $min;
  10215. public $is;
  10216. public $tooShort;
  10217. public $tooLong;
  10218. public $allowEmpty=true;
  10219. public $encoding;
  10220. protected function validateAttribute($object,$attribute)
  10221. {
  10222. $value=$object->$attribute;
  10223. if($this->allowEmpty && $this->isEmpty($value))
  10224. return;
  10225. if(is_array($value))
  10226. {
  10227. // https://github.com/yiisoft/yii/issues/1955
  10228. $this->addError($object,$attribute,Yii::t('yii','{attribute} is invalid.'));
  10229. return;
  10230. }
  10231. if(function_exists('mb_strlen') && $this->encoding!==false)
  10232. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  10233. else
  10234. $length=strlen($value);
  10235. if($this->min!==null && $length<$this->min)
  10236. {
  10237. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  10238. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  10239. }
  10240. if($this->max!==null && $length>$this->max)
  10241. {
  10242. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  10243. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  10244. }
  10245. if($this->is!==null && $length!==$this->is)
  10246. {
  10247. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  10248. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  10249. }
  10250. }
  10251. public function clientValidateAttribute($object,$attribute)
  10252. {
  10253. $label=$object->getAttributeLabel($attribute);
  10254. if(($message=$this->message)===null)
  10255. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  10256. $message=strtr($message, array(
  10257. '{attribute}'=>$label,
  10258. '{length}'=>$this->is,
  10259. ));
  10260. if(($tooShort=$this->tooShort)===null)
  10261. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  10262. $tooShort=strtr($tooShort, array(
  10263. '{attribute}'=>$label,
  10264. '{min}'=>$this->min,
  10265. ));
  10266. if(($tooLong=$this->tooLong)===null)
  10267. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  10268. $tooLong=strtr($tooLong, array(
  10269. '{attribute}'=>$label,
  10270. '{max}'=>$this->max,
  10271. ));
  10272. $js='';
  10273. if($this->min!==null)
  10274. {
  10275. $js.="
  10276. if(value.length<{$this->min}) {
  10277. messages.push(".CJSON::encode($tooShort).");
  10278. }
  10279. ";
  10280. }
  10281. if($this->max!==null)
  10282. {
  10283. $js.="
  10284. if(value.length>{$this->max}) {
  10285. messages.push(".CJSON::encode($tooLong).");
  10286. }
  10287. ";
  10288. }
  10289. if($this->is!==null)
  10290. {
  10291. $js.="
  10292. if(value.length!={$this->is}) {
  10293. messages.push(".CJSON::encode($message).");
  10294. }
  10295. ";
  10296. }
  10297. if($this->allowEmpty)
  10298. {
  10299. $js="
  10300. if(jQuery.trim(value)!='') {
  10301. $js
  10302. }
  10303. ";
  10304. }
  10305. return $js;
  10306. }
  10307. }
  10308. class CRequiredValidator extends CValidator
  10309. {
  10310. public $requiredValue;
  10311. public $strict=false;
  10312. public $trim=true;
  10313. protected function validateAttribute($object,$attribute)
  10314. {
  10315. $value=$object->$attribute;
  10316. if($this->requiredValue!==null)
  10317. {
  10318. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  10319. {
  10320. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  10321. array('{value}'=>$this->requiredValue));
  10322. $this->addError($object,$attribute,$message);
  10323. }
  10324. }
  10325. elseif($this->isEmpty($value,$this->trim))
  10326. {
  10327. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  10328. $this->addError($object,$attribute,$message);
  10329. }
  10330. }
  10331. public function clientValidateAttribute($object,$attribute)
  10332. {
  10333. $message=$this->message;
  10334. if($this->requiredValue!==null)
  10335. {
  10336. if($message===null)
  10337. $message=Yii::t('yii','{attribute} must be {value}.');
  10338. $message=strtr($message, array(
  10339. '{value}'=>$this->requiredValue,
  10340. '{attribute}'=>$object->getAttributeLabel($attribute),
  10341. ));
  10342. return "
  10343. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  10344. messages.push(".CJSON::encode($message).");
  10345. }
  10346. ";
  10347. }
  10348. else
  10349. {
  10350. if($message===null)
  10351. $message=Yii::t('yii','{attribute} cannot be blank.');
  10352. $message=strtr($message, array(
  10353. '{attribute}'=>$object->getAttributeLabel($attribute),
  10354. ));
  10355. if($this->trim)
  10356. $emptyCondition = "jQuery.trim(value)==''";
  10357. else
  10358. $emptyCondition = "value==''";
  10359. return "
  10360. if({$emptyCondition}) {
  10361. messages.push(".CJSON::encode($message).");
  10362. }
  10363. ";
  10364. }
  10365. }
  10366. }
  10367. class CNumberValidator extends CValidator
  10368. {
  10369. public $integerOnly=false;
  10370. public $allowEmpty=true;
  10371. public $max;
  10372. public $min;
  10373. public $tooBig;
  10374. public $tooSmall;
  10375. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  10376. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  10377. protected function validateAttribute($object,$attribute)
  10378. {
  10379. $value=$object->$attribute;
  10380. if($this->allowEmpty && $this->isEmpty($value))
  10381. return;
  10382. if(!is_numeric($value))
  10383. {
  10384. // https://github.com/yiisoft/yii/issues/1955
  10385. // https://github.com/yiisoft/yii/issues/1669
  10386. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  10387. $this->addError($object,$attribute,$message);
  10388. return;
  10389. }
  10390. if($this->integerOnly)
  10391. {
  10392. if(!preg_match($this->integerPattern,"$value"))
  10393. {
  10394. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  10395. $this->addError($object,$attribute,$message);
  10396. }
  10397. }
  10398. else
  10399. {
  10400. if(!preg_match($this->numberPattern,"$value"))
  10401. {
  10402. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  10403. $this->addError($object,$attribute,$message);
  10404. }
  10405. }
  10406. if($this->min!==null && $value<$this->min)
  10407. {
  10408. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  10409. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  10410. }
  10411. if($this->max!==null && $value>$this->max)
  10412. {
  10413. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  10414. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  10415. }
  10416. }
  10417. public function clientValidateAttribute($object,$attribute)
  10418. {
  10419. $label=$object->getAttributeLabel($attribute);
  10420. if(($message=$this->message)===null)
  10421. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  10422. $message=strtr($message, array(
  10423. '{attribute}'=>$label,
  10424. ));
  10425. if(($tooBig=$this->tooBig)===null)
  10426. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  10427. $tooBig=strtr($tooBig, array(
  10428. '{attribute}'=>$label,
  10429. '{max}'=>$this->max,
  10430. ));
  10431. if(($tooSmall=$this->tooSmall)===null)
  10432. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  10433. $tooSmall=strtr($tooSmall, array(
  10434. '{attribute}'=>$label,
  10435. '{min}'=>$this->min,
  10436. ));
  10437. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  10438. $js="
  10439. if(!value.match($pattern)) {
  10440. messages.push(".CJSON::encode($message).");
  10441. }
  10442. ";
  10443. if($this->min!==null)
  10444. {
  10445. $js.="
  10446. if(value<{$this->min}) {
  10447. messages.push(".CJSON::encode($tooSmall).");
  10448. }
  10449. ";
  10450. }
  10451. if($this->max!==null)
  10452. {
  10453. $js.="
  10454. if(value>{$this->max}) {
  10455. messages.push(".CJSON::encode($tooBig).");
  10456. }
  10457. ";
  10458. }
  10459. if($this->allowEmpty)
  10460. {
  10461. $js="
  10462. if(jQuery.trim(value)!='') {
  10463. $js
  10464. }
  10465. ";
  10466. }
  10467. return $js;
  10468. }
  10469. }
  10470. class CListIterator implements Iterator
  10471. {
  10472. private $_d;
  10473. private $_i;
  10474. public function __construct(&$data)
  10475. {
  10476. $this->_d=&$data;
  10477. $this->_i=0;
  10478. }
  10479. public function rewind()
  10480. {
  10481. $this->_i=0;
  10482. }
  10483. public function key()
  10484. {
  10485. return $this->_i;
  10486. }
  10487. public function current()
  10488. {
  10489. return $this->_d[$this->_i];
  10490. }
  10491. public function next()
  10492. {
  10493. $this->_i++;
  10494. }
  10495. public function valid()
  10496. {
  10497. return $this->_i<count($this->_d);
  10498. }
  10499. }
  10500. interface IApplicationComponent
  10501. {
  10502. public function init();
  10503. public function getIsInitialized();
  10504. }
  10505. interface ICache
  10506. {
  10507. public function get($id);
  10508. public function mget($ids);
  10509. public function set($id,$value,$expire=0,$dependency=null);
  10510. public function add($id,$value,$expire=0,$dependency=null);
  10511. public function delete($id);
  10512. public function flush();
  10513. }
  10514. interface ICacheDependency
  10515. {
  10516. public function evaluateDependency();
  10517. public function getHasChanged();
  10518. }
  10519. interface IStatePersister
  10520. {
  10521. public function load();
  10522. public function save($state);
  10523. }
  10524. interface IFilter
  10525. {
  10526. public function filter($filterChain);
  10527. }
  10528. interface IAction
  10529. {
  10530. public function getId();
  10531. public function getController();
  10532. }
  10533. interface IWebServiceProvider
  10534. {
  10535. public function beforeWebMethod($service);
  10536. public function afterWebMethod($service);
  10537. }
  10538. interface IViewRenderer
  10539. {
  10540. public function renderFile($context,$file,$data,$return);
  10541. }
  10542. interface IUserIdentity
  10543. {
  10544. public function authenticate();
  10545. public function getIsAuthenticated();
  10546. public function getId();
  10547. public function getName();
  10548. public function getPersistentStates();
  10549. }
  10550. interface IWebUser
  10551. {
  10552. public function getId();
  10553. public function getName();
  10554. public function getIsGuest();
  10555. public function checkAccess($operation,$params=array());
  10556. public function loginRequired();
  10557. }
  10558. interface IAuthManager
  10559. {
  10560. public function checkAccess($itemName,$userId,$params=array());
  10561. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  10562. public function removeAuthItem($name);
  10563. public function getAuthItems($type=null,$userId=null);
  10564. public function getAuthItem($name);
  10565. public function saveAuthItem($item,$oldName=null);
  10566. public function addItemChild($itemName,$childName);
  10567. public function removeItemChild($itemName,$childName);
  10568. public function hasItemChild($itemName,$childName);
  10569. public function getItemChildren($itemName);
  10570. public function assign($itemName,$userId,$bizRule=null,$data=null);
  10571. public function revoke($itemName,$userId);
  10572. public function isAssigned($itemName,$userId);
  10573. public function getAuthAssignment($itemName,$userId);
  10574. public function getAuthAssignments($userId);
  10575. public function saveAuthAssignment($assignment);
  10576. public function clearAll();
  10577. public function clearAuthAssignments();
  10578. public function save();
  10579. public function executeBizRule($bizRule,$params,$data);
  10580. }
  10581. interface IBehavior
  10582. {
  10583. public function attach($component);
  10584. public function detach($component);
  10585. public function getEnabled();
  10586. public function setEnabled($value);
  10587. }
  10588. interface IWidgetFactory
  10589. {
  10590. public function createWidget($owner,$className,$properties=array());
  10591. }
  10592. interface IDataProvider
  10593. {
  10594. public function getId();
  10595. public function getItemCount($refresh=false);
  10596. public function getTotalItemCount($refresh=false);
  10597. public function getData($refresh=false);
  10598. public function getKeys($refresh=false);
  10599. public function getSort();
  10600. public function getPagination();
  10601. }
  10602. interface ILogFilter
  10603. {
  10604. public function filter(&$logs);
  10605. }
  10606. ?>