PageRenderTime 113ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/framework/yiilite.php

http://github.com/yiisoft/yii
PHP | 10793 lines | 10711 code | 2 blank | 80 comment | 1131 complexity | ff5c6a03b0ed59650e2af416d936dccb MD5 | raw file
Possible License(s): BSD-3-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 $autoloaderFilters=array();
  33. public static $classMap=array();
  34. public static $enableIncludePath=true;
  35. private static $_aliases=array('system'=>YII_PATH,'zii'=>YII_ZII_PATH); // alias => path
  36. private static $_imports=array(); // alias => class name or directory
  37. private static $_includePaths; // list of include paths
  38. private static $_app;
  39. private static $_logger;
  40. public static function getVersion()
  41. {
  42. return '1.1.25-dev';
  43. }
  44. public static function createWebApplication($config=null)
  45. {
  46. return self::createApplication('CWebApplication',$config);
  47. }
  48. public static function createConsoleApplication($config=null)
  49. {
  50. return self::createApplication('CConsoleApplication',$config);
  51. }
  52. public static function createApplication($class,$config=null)
  53. {
  54. return new $class($config);
  55. }
  56. public static function app()
  57. {
  58. return self::$_app;
  59. }
  60. public static function setApplication($app)
  61. {
  62. if(self::$_app===null || $app===null)
  63. self::$_app=$app;
  64. else
  65. throw new CException(Yii::t('yii','Yii application can only be created once.'));
  66. }
  67. public static function getFrameworkPath()
  68. {
  69. return YII_PATH;
  70. }
  71. public static function createComponent($config)
  72. {
  73. $args = func_get_args();
  74. if(is_string($config))
  75. {
  76. $type=$config;
  77. $config=array();
  78. }
  79. elseif(isset($config['class']))
  80. {
  81. $type=$config['class'];
  82. unset($config['class']);
  83. }
  84. else
  85. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  86. if(!class_exists($type,false))
  87. $type=Yii::import($type,true);
  88. if(($n=func_num_args())>1)
  89. {
  90. if($n===2)
  91. $object=new $type($args[1]);
  92. elseif($n===3)
  93. $object=new $type($args[1],$args[2]);
  94. elseif($n===4)
  95. $object=new $type($args[1],$args[2],$args[3]);
  96. else
  97. {
  98. unset($args[0]);
  99. $class=new ReflectionClass($type);
  100. // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
  101. // $object=$class->newInstanceArgs($args);
  102. $object=call_user_func_array(array($class,'newInstance'),$args);
  103. }
  104. }
  105. else
  106. $object=new $type;
  107. foreach($config as $key=>$value)
  108. $object->$key=$value;
  109. return $object;
  110. }
  111. public static function import($alias,$forceInclude=false)
  112. {
  113. if(isset(self::$_imports[$alias])) // previously imported
  114. return self::$_imports[$alias];
  115. if(class_exists($alias,false) || interface_exists($alias,false))
  116. return self::$_imports[$alias]=$alias;
  117. if(($pos=strrpos($alias,'\\'))!==false) // a class name in PHP 5.3 namespace format
  118. {
  119. $namespace=str_replace('\\','.',ltrim(substr($alias,0,$pos),'\\'));
  120. if(($path=self::getPathOfAlias($namespace))!==false)
  121. {
  122. $classFile=$path.DIRECTORY_SEPARATOR.substr($alias,$pos+1).'.php';
  123. if($forceInclude)
  124. {
  125. if(is_file($classFile))
  126. require($classFile);
  127. else
  128. 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)));
  129. self::$_imports[$alias]=$alias;
  130. }
  131. else
  132. self::$classMap[$alias]=$classFile;
  133. return $alias;
  134. }
  135. else
  136. {
  137. // try to autoload the class with an autoloader
  138. if (class_exists($alias,true))
  139. return self::$_imports[$alias]=$alias;
  140. else
  141. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  142. array('{alias}'=>$namespace)));
  143. }
  144. }
  145. if(($pos=strrpos($alias,'.'))===false) // a simple class name
  146. {
  147. // try to autoload the class with an autoloader if $forceInclude is true
  148. if($forceInclude && (Yii::autoload($alias,true) || class_exists($alias,true)))
  149. self::$_imports[$alias]=$alias;
  150. return $alias;
  151. }
  152. $className=(string)substr($alias,$pos+1);
  153. $isClass=$className!=='*';
  154. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  155. return self::$_imports[$alias]=$className;
  156. if(($path=self::getPathOfAlias($alias))!==false)
  157. {
  158. if($isClass)
  159. {
  160. if($forceInclude)
  161. {
  162. if(is_file($path.'.php'))
  163. require($path.'.php');
  164. else
  165. 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)));
  166. self::$_imports[$alias]=$className;
  167. }
  168. else
  169. self::$classMap[$className]=$path.'.php';
  170. return $className;
  171. }
  172. else // a directory
  173. {
  174. if(self::$_includePaths===null)
  175. {
  176. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  177. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  178. unset(self::$_includePaths[$pos]);
  179. }
  180. array_unshift(self::$_includePaths,$path);
  181. if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  182. self::$enableIncludePath=false;
  183. return self::$_imports[$alias]=$path;
  184. }
  185. }
  186. else
  187. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  188. array('{alias}'=>$alias)));
  189. }
  190. public static function getPathOfAlias($alias)
  191. {
  192. if(isset(self::$_aliases[$alias]))
  193. return self::$_aliases[$alias];
  194. elseif(($pos=strpos($alias,'.'))!==false)
  195. {
  196. $rootAlias=substr($alias,0,$pos);
  197. if(isset(self::$_aliases[$rootAlias]))
  198. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  199. elseif(self::$_app instanceof CWebApplication)
  200. {
  201. if(self::$_app->findModule($rootAlias)!==null)
  202. return self::getPathOfAlias($alias);
  203. }
  204. }
  205. return false;
  206. }
  207. public static function setPathOfAlias($alias,$path)
  208. {
  209. if(empty($path))
  210. unset(self::$_aliases[$alias]);
  211. else
  212. self::$_aliases[$alias]=rtrim($path,'\\/');
  213. }
  214. public static function autoload($className,$classMapOnly=false)
  215. {
  216. foreach (self::$autoloaderFilters as $filter)
  217. {
  218. if (is_array($filter)
  219. && isset($filter[0]) && isset($filter[1])
  220. && is_string($filter[0]) && is_string($filter[1])
  221. && true === call_user_func(array($filter[0], $filter[1]), $className)
  222. )
  223. {
  224. return true;
  225. }
  226. elseif (is_string($filter)
  227. && true === call_user_func($filter, $className)
  228. )
  229. {
  230. return true;
  231. }
  232. elseif (is_callable($filter)
  233. && true === $filter($className)
  234. )
  235. {
  236. return true;
  237. }
  238. }
  239. // use include so that the error PHP file may appear
  240. if(isset(self::$classMap[$className]))
  241. include(self::$classMap[$className]);
  242. elseif(isset(self::$_coreClasses[$className]))
  243. include(YII_PATH.self::$_coreClasses[$className]);
  244. elseif($classMapOnly)
  245. return false;
  246. else
  247. {
  248. // include class file relying on include_path
  249. if(strpos($className,'\\')===false) // class without namespace
  250. {
  251. if(self::$enableIncludePath===false)
  252. {
  253. foreach(self::$_includePaths as $path)
  254. {
  255. $classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
  256. if(is_file($classFile))
  257. {
  258. include($classFile);
  259. if(YII_DEBUG && basename(realpath($classFile))!==$className.'.php')
  260. throw new CException(Yii::t('yii','Class name "{class}" does not match class file "{file}".', array(
  261. '{class}'=>$className,
  262. '{file}'=>$classFile,
  263. )));
  264. break;
  265. }
  266. }
  267. }
  268. else
  269. include($className.'.php');
  270. }
  271. else // class name with namespace in PHP 5.3
  272. {
  273. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  274. if(($path=self::getPathOfAlias($namespace))!==false && is_file($path.'.php'))
  275. include($path.'.php');
  276. else
  277. return false;
  278. }
  279. return class_exists($className,false) || interface_exists($className,false);
  280. }
  281. return true;
  282. }
  283. public static function trace($msg,$category='application')
  284. {
  285. if(YII_DEBUG)
  286. self::log($msg,CLogger::LEVEL_TRACE,$category);
  287. }
  288. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  289. {
  290. if(self::$_logger===null)
  291. self::$_logger=new CLogger;
  292. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  293. {
  294. $traces=debug_backtrace();
  295. $count=0;
  296. foreach($traces as $trace)
  297. {
  298. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  299. {
  300. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  301. if(++$count>=YII_TRACE_LEVEL)
  302. break;
  303. }
  304. }
  305. }
  306. self::$_logger->log($msg,$level,$category);
  307. }
  308. public static function beginProfile($token,$category='application')
  309. {
  310. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  311. }
  312. public static function endProfile($token,$category='application')
  313. {
  314. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  315. }
  316. public static function getLogger()
  317. {
  318. if(self::$_logger!==null)
  319. return self::$_logger;
  320. else
  321. return self::$_logger=new CLogger;
  322. }
  323. public static function setLogger($logger)
  324. {
  325. self::$_logger=$logger;
  326. }
  327. public static function powered()
  328. {
  329. return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
  330. }
  331. public static function t($category,$message,$params=array(),$source=null,$language=null)
  332. {
  333. if(self::$_app!==null)
  334. {
  335. if($source===null)
  336. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  337. if(($source=self::$_app->getComponent($source))!==null)
  338. $message=$source->translate($category,$message,$language);
  339. }
  340. if($params===array())
  341. return $message;
  342. if(!is_array($params))
  343. $params=array($params);
  344. if(isset($params[0])) // number choice
  345. {
  346. if(strpos($message,'|')!==false)
  347. {
  348. if(strpos($message,'#')===false)
  349. {
  350. $chunks=explode('|',$message);
  351. $expressions=self::$_app->getLocale($language)->getPluralRules();
  352. if($n=min(count($chunks),count($expressions)))
  353. {
  354. for($i=0;$i<$n;$i++)
  355. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  356. $message=implode('|',$chunks);
  357. }
  358. }
  359. $message=CChoiceFormat::format($message,$params[0]);
  360. }
  361. if(!isset($params['{n}']))
  362. $params['{n}']=$params[0];
  363. unset($params[0]);
  364. }
  365. return $params!==array() ? strtr($message,$params) : $message;
  366. }
  367. public static function registerAutoloader($callback, $append=false)
  368. {
  369. if($append)
  370. {
  371. self::$enableIncludePath=false;
  372. spl_autoload_register($callback);
  373. }
  374. else
  375. {
  376. spl_autoload_unregister(array('YiiBase','autoload'));
  377. spl_autoload_register($callback);
  378. spl_autoload_register(array('YiiBase','autoload'));
  379. }
  380. }
  381. private static $_coreClasses=array(
  382. 'CApplication' => '/base/CApplication.php',
  383. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  384. 'CBehavior' => '/base/CBehavior.php',
  385. 'CComponent' => '/base/CComponent.php',
  386. 'CDbStatePersister' => '/base/CDbStatePersister.php',
  387. 'CErrorEvent' => '/base/CErrorEvent.php',
  388. 'CErrorHandler' => '/base/CErrorHandler.php',
  389. 'CException' => '/base/CException.php',
  390. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  391. 'CHttpException' => '/base/CHttpException.php',
  392. 'CModel' => '/base/CModel.php',
  393. 'CModelBehavior' => '/base/CModelBehavior.php',
  394. 'CModelEvent' => '/base/CModelEvent.php',
  395. 'CModule' => '/base/CModule.php',
  396. 'CSecurityManager' => '/base/CSecurityManager.php',
  397. 'CStatePersister' => '/base/CStatePersister.php',
  398. 'CApcCache' => '/caching/CApcCache.php',
  399. 'CCache' => '/caching/CCache.php',
  400. 'CDbCache' => '/caching/CDbCache.php',
  401. 'CDummyCache' => '/caching/CDummyCache.php',
  402. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  403. 'CFileCache' => '/caching/CFileCache.php',
  404. 'CMemCache' => '/caching/CMemCache.php',
  405. 'CRedisCache' => '/caching/CRedisCache.php',
  406. 'CWinCache' => '/caching/CWinCache.php',
  407. 'CXCache' => '/caching/CXCache.php',
  408. 'CZendDataCache' => '/caching/CZendDataCache.php',
  409. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  410. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  411. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  412. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  413. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  414. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  415. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  416. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  417. 'CConfiguration' => '/collections/CConfiguration.php',
  418. 'CList' => '/collections/CList.php',
  419. 'CListIterator' => '/collections/CListIterator.php',
  420. 'CMap' => '/collections/CMap.php',
  421. 'CMapIterator' => '/collections/CMapIterator.php',
  422. 'CQueue' => '/collections/CQueue.php',
  423. 'CQueueIterator' => '/collections/CQueueIterator.php',
  424. 'CStack' => '/collections/CStack.php',
  425. 'CStackIterator' => '/collections/CStackIterator.php',
  426. 'CTypedList' => '/collections/CTypedList.php',
  427. 'CTypedMap' => '/collections/CTypedMap.php',
  428. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  429. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  430. 'CConsoleCommandBehavior' => '/console/CConsoleCommandBehavior.php',
  431. 'CConsoleCommandEvent' => '/console/CConsoleCommandEvent.php',
  432. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  433. 'CHelpCommand' => '/console/CHelpCommand.php',
  434. 'CDbCommand' => '/db/CDbCommand.php',
  435. 'CDbConnection' => '/db/CDbConnection.php',
  436. 'CDbDataReader' => '/db/CDbDataReader.php',
  437. 'CDbException' => '/db/CDbException.php',
  438. 'CDbMigration' => '/db/CDbMigration.php',
  439. 'CDbTransaction' => '/db/CDbTransaction.php',
  440. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  441. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  442. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  443. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  444. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  445. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  446. 'CDbExpression' => '/db/schema/CDbExpression.php',
  447. 'CDbSchema' => '/db/schema/CDbSchema.php',
  448. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  449. 'CCubridColumnSchema' => '/db/schema/cubrid/CCubridColumnSchema.php',
  450. 'CCubridSchema' => '/db/schema/cubrid/CCubridSchema.php',
  451. 'CCubridTableSchema' => '/db/schema/cubrid/CCubridTableSchema.php',
  452. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  453. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  454. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  455. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  456. 'CMssqlSqlsrvPdoAdapter' => '/db/schema/mssql/CMssqlSqlsrvPdoAdapter.php',
  457. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  458. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  459. 'CMysqlCommandBuilder' => '/db/schema/mysql/CMysqlCommandBuilder.php',
  460. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  461. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  462. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  463. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  464. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  465. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  466. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  467. 'CPgsqlCommandBuilder' => '/db/schema/pgsql/CPgsqlCommandBuilder.php',
  468. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  469. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  470. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  471. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  472. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  473. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  474. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  475. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  476. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  477. 'CLocale' => '/i18n/CLocale.php',
  478. 'CMessageSource' => '/i18n/CMessageSource.php',
  479. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  480. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  481. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  482. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  483. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  484. 'CChainedLogFilter' => '/logging/CChainedLogFilter.php',
  485. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  486. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  487. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  488. 'CLogFilter' => '/logging/CLogFilter.php',
  489. 'CLogRoute' => '/logging/CLogRoute.php',
  490. 'CLogRouter' => '/logging/CLogRouter.php',
  491. 'CLogger' => '/logging/CLogger.php',
  492. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  493. 'CSysLogRoute' => '/logging/CSysLogRoute.php',
  494. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  495. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  496. 'CFileHelper' => '/utils/CFileHelper.php',
  497. 'CFormatter' => '/utils/CFormatter.php',
  498. 'CLocalizedFormatter' => '/utils/CLocalizedFormatter.php',
  499. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  500. 'CPasswordHelper' => '/utils/CPasswordHelper.php',
  501. 'CPropertyValue' => '/utils/CPropertyValue.php',
  502. 'CTimestamp' => '/utils/CTimestamp.php',
  503. 'CVarDumper' => '/utils/CVarDumper.php',
  504. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  505. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  506. 'CCompareValidator' => '/validators/CCompareValidator.php',
  507. 'CDateValidator' => '/validators/CDateValidator.php',
  508. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  509. 'CEmailValidator' => '/validators/CEmailValidator.php',
  510. 'CExistValidator' => '/validators/CExistValidator.php',
  511. 'CFileValidator' => '/validators/CFileValidator.php',
  512. 'CFilterValidator' => '/validators/CFilterValidator.php',
  513. 'CInlineValidator' => '/validators/CInlineValidator.php',
  514. 'CNumberValidator' => '/validators/CNumberValidator.php',
  515. 'CRangeValidator' => '/validators/CRangeValidator.php',
  516. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  517. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  518. 'CSafeValidator' => '/validators/CSafeValidator.php',
  519. 'CStringValidator' => '/validators/CStringValidator.php',
  520. 'CTypeValidator' => '/validators/CTypeValidator.php',
  521. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  522. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  523. 'CUrlValidator' => '/validators/CUrlValidator.php',
  524. 'CValidator' => '/validators/CValidator.php',
  525. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  526. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  527. 'CAssetManager' => '/web/CAssetManager.php',
  528. 'CBaseController' => '/web/CBaseController.php',
  529. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  530. 'CClientScript' => '/web/CClientScript.php',
  531. 'CController' => '/web/CController.php',
  532. 'CDataProvider' => '/web/CDataProvider.php',
  533. 'CDataProviderIterator' => '/web/CDataProviderIterator.php',
  534. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  535. 'CExtController' => '/web/CExtController.php',
  536. 'CFormModel' => '/web/CFormModel.php',
  537. 'CHttpCookie' => '/web/CHttpCookie.php',
  538. 'CHttpRequest' => '/web/CHttpRequest.php',
  539. 'CHttpSession' => '/web/CHttpSession.php',
  540. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  541. 'COutputEvent' => '/web/COutputEvent.php',
  542. 'CPagination' => '/web/CPagination.php',
  543. 'CSort' => '/web/CSort.php',
  544. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  545. 'CTheme' => '/web/CTheme.php',
  546. 'CThemeManager' => '/web/CThemeManager.php',
  547. 'CUploadedFile' => '/web/CUploadedFile.php',
  548. 'CUrlManager' => '/web/CUrlManager.php',
  549. 'CWebApplication' => '/web/CWebApplication.php',
  550. 'CWebModule' => '/web/CWebModule.php',
  551. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  552. 'CAction' => '/web/actions/CAction.php',
  553. 'CInlineAction' => '/web/actions/CInlineAction.php',
  554. 'CViewAction' => '/web/actions/CViewAction.php',
  555. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  556. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  557. 'CAuthItem' => '/web/auth/CAuthItem.php',
  558. 'CAuthManager' => '/web/auth/CAuthManager.php',
  559. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  560. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  561. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  562. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  563. 'CWebUser' => '/web/auth/CWebUser.php',
  564. 'CFilter' => '/web/filters/CFilter.php',
  565. 'CFilterChain' => '/web/filters/CFilterChain.php',
  566. 'CHttpCacheFilter' => '/web/filters/CHttpCacheFilter.php',
  567. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  568. 'CForm' => '/web/form/CForm.php',
  569. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  570. 'CFormElement' => '/web/form/CFormElement.php',
  571. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  572. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  573. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  574. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  575. 'CHtml' => '/web/helpers/CHtml.php',
  576. 'CJSON' => '/web/helpers/CJSON.php',
  577. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  578. 'CJavaScriptExpression' => '/web/helpers/CJavaScriptExpression.php',
  579. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  580. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  581. 'CWebService' => '/web/services/CWebService.php',
  582. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  583. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  584. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  585. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  586. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  587. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  588. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  589. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  590. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  591. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  592. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  593. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  594. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  595. 'COutputCache' => '/web/widgets/COutputCache.php',
  596. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  597. 'CStarRating' => '/web/widgets/CStarRating.php',
  598. 'CTabView' => '/web/widgets/CTabView.php',
  599. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  600. 'CTreeView' => '/web/widgets/CTreeView.php',
  601. 'CWidget' => '/web/widgets/CWidget.php',
  602. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  603. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  604. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  605. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  606. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  607. );
  608. }
  609. spl_autoload_register(array('YiiBase','autoload'));
  610. if(!class_exists('YiiBase', false))
  611. require(dirname(__FILE__).'/YiiBase.php');
  612. class Yii extends YiiBase
  613. {
  614. }
  615. class CComponent
  616. {
  617. private $_e;
  618. private $_m;
  619. public function __get($name)
  620. {
  621. $getter='get'.$name;
  622. if(method_exists($this,$getter))
  623. return $this->$getter();
  624. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  625. {
  626. // duplicating getEventHandlers() here for performance
  627. $name=strtolower($name);
  628. if(!isset($this->_e[$name]))
  629. $this->_e[$name]=new CList;
  630. return $this->_e[$name];
  631. }
  632. elseif(isset($this->_m[$name]))
  633. return $this->_m[$name];
  634. elseif(is_array($this->_m))
  635. {
  636. foreach($this->_m as $object)
  637. {
  638. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  639. return $object->$name;
  640. }
  641. }
  642. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  643. array('{class}'=>get_class($this), '{property}'=>$name)));
  644. }
  645. public function __set($name,$value)
  646. {
  647. $setter='set'.$name;
  648. if(method_exists($this,$setter))
  649. return $this->$setter($value);
  650. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  651. {
  652. // duplicating getEventHandlers() here for performance
  653. $name=strtolower($name);
  654. if(!isset($this->_e[$name]))
  655. $this->_e[$name]=new CList;
  656. return $this->_e[$name]->add($value);
  657. }
  658. elseif(is_array($this->_m))
  659. {
  660. foreach($this->_m as $object)
  661. {
  662. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  663. return $object->$name=$value;
  664. }
  665. }
  666. if(method_exists($this,'get'.$name))
  667. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  668. array('{class}'=>get_class($this), '{property}'=>$name)));
  669. else
  670. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  671. array('{class}'=>get_class($this), '{property}'=>$name)));
  672. }
  673. public function __isset($name)
  674. {
  675. $getter='get'.$name;
  676. if(method_exists($this,$getter))
  677. return $this->$getter()!==null;
  678. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  679. {
  680. $name=strtolower($name);
  681. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  682. }
  683. elseif(is_array($this->_m))
  684. {
  685. if(isset($this->_m[$name]))
  686. return true;
  687. foreach($this->_m as $object)
  688. {
  689. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  690. return $object->$name!==null;
  691. }
  692. }
  693. return false;
  694. }
  695. public function __unset($name)
  696. {
  697. $setter='set'.$name;
  698. if(method_exists($this,$setter))
  699. $this->$setter(null);
  700. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  701. unset($this->_e[strtolower($name)]);
  702. elseif(is_array($this->_m))
  703. {
  704. if(isset($this->_m[$name]))
  705. $this->detachBehavior($name);
  706. else
  707. {
  708. foreach($this->_m as $object)
  709. {
  710. if($object->getEnabled())
  711. {
  712. if(property_exists($object,$name))
  713. return $object->$name=null;
  714. elseif($object->canSetProperty($name))
  715. return $object->$setter(null);
  716. }
  717. }
  718. }
  719. }
  720. elseif(method_exists($this,'get'.$name))
  721. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  722. array('{class}'=>get_class($this), '{property}'=>$name)));
  723. }
  724. public function __call($name,$parameters)
  725. {
  726. if($this->_m!==null)
  727. {
  728. foreach($this->_m as $object)
  729. {
  730. if($object->getEnabled() && method_exists($object,$name))
  731. return call_user_func_array(array($object,$name),$parameters);
  732. }
  733. }
  734. if(class_exists('Closure', false) && ($this->canGetProperty($name) || property_exists($this, $name)) && $this->$name instanceof Closure)
  735. return call_user_func_array($this->$name, $parameters);
  736. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  737. array('{class}'=>get_class($this), '{name}'=>$name)));
  738. }
  739. public function asa($behavior)
  740. {
  741. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  742. }
  743. public function attachBehaviors($behaviors)
  744. {
  745. foreach($behaviors as $name=>$behavior)
  746. $this->attachBehavior($name,$behavior);
  747. }
  748. public function detachBehaviors()
  749. {
  750. if($this->_m!==null)
  751. {
  752. foreach($this->_m as $name=>$behavior)
  753. $this->detachBehavior($name);
  754. $this->_m=null;
  755. }
  756. }
  757. public function attachBehavior($name,$behavior)
  758. {
  759. if(!($behavior instanceof IBehavior))
  760. $behavior=Yii::createComponent($behavior);
  761. $behavior->setEnabled(true);
  762. $behavior->attach($this);
  763. return $this->_m[$name]=$behavior;
  764. }
  765. public function detachBehavior($name)
  766. {
  767. if(isset($this->_m[$name]))
  768. {
  769. $this->_m[$name]->detach($this);
  770. $behavior=$this->_m[$name];
  771. unset($this->_m[$name]);
  772. return $behavior;
  773. }
  774. }
  775. public function enableBehaviors()
  776. {
  777. if($this->_m!==null)
  778. {
  779. foreach($this->_m as $behavior)
  780. $behavior->setEnabled(true);
  781. }
  782. }
  783. public function disableBehaviors()
  784. {
  785. if($this->_m!==null)
  786. {
  787. foreach($this->_m as $behavior)
  788. $behavior->setEnabled(false);
  789. }
  790. }
  791. public function enableBehavior($name)
  792. {
  793. if(isset($this->_m[$name]))
  794. $this->_m[$name]->setEnabled(true);
  795. }
  796. public function disableBehavior($name)
  797. {
  798. if(isset($this->_m[$name]))
  799. $this->_m[$name]->setEnabled(false);
  800. }
  801. public function hasProperty($name)
  802. {
  803. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  804. }
  805. public function canGetProperty($name)
  806. {
  807. return method_exists($this,'get'.$name);
  808. }
  809. public function canSetProperty($name)
  810. {
  811. return method_exists($this,'set'.$name);
  812. }
  813. public function hasEvent($name)
  814. {
  815. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  816. }
  817. public function hasEventHandler($name)
  818. {
  819. $name=strtolower($name);
  820. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  821. }
  822. public function getEventHandlers($name)
  823. {
  824. if($this->hasEvent($name))
  825. {
  826. $name=strtolower($name);
  827. if(!isset($this->_e[$name]))
  828. $this->_e[$name]=new CList;
  829. return $this->_e[$name];
  830. }
  831. else
  832. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  833. array('{class}'=>get_class($this), '{event}'=>$name)));
  834. }
  835. public function attachEventHandler($name,$handler)
  836. {
  837. $this->getEventHandlers($name)->add($handler);
  838. }
  839. public function detachEventHandler($name,$handler)
  840. {
  841. if($this->hasEventHandler($name))
  842. return $this->getEventHandlers($name)->remove($handler)!==false;
  843. else
  844. return false;
  845. }
  846. public function raiseEvent($name,$event)
  847. {
  848. $name=strtolower($name);
  849. if(isset($this->_e[$name]))
  850. {
  851. foreach($this->_e[$name] as $handler)
  852. {
  853. if(is_string($handler))
  854. call_user_func($handler,$event);
  855. elseif(is_callable($handler,true))
  856. {
  857. if(is_array($handler))
  858. {
  859. // an array: 0 - object, 1 - method name
  860. list($object,$method)=$handler;
  861. if(is_string($object)) // static method call
  862. call_user_func($handler,$event);
  863. elseif(method_exists($object,$method))
  864. $object->$method($event);
  865. else
  866. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  867. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  868. }
  869. else // PHP 5.3: anonymous function
  870. call_user_func($handler,$event);
  871. }
  872. else
  873. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  874. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  875. // stop further handling if param.handled is set true
  876. if(($event instanceof CEvent) && $event->handled)
  877. return;
  878. }
  879. }
  880. elseif(YII_DEBUG && !$this->hasEvent($name))
  881. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  882. array('{class}'=>get_class($this), '{event}'=>$name)));
  883. }
  884. public function evaluateExpression($_expression_,$_data_=array())
  885. {
  886. if(is_string($_expression_))
  887. {
  888. extract($_data_);
  889. try
  890. {
  891. return eval('return ' . $_expression_ . ';');
  892. }
  893. catch (ParseError $e)
  894. {
  895. return false;
  896. }
  897. }
  898. else
  899. {
  900. $_data_[]=$this;
  901. return call_user_func_array($_expression_, array_values($_data_));
  902. }
  903. }
  904. }
  905. class CEvent extends CComponent
  906. {
  907. public $sender;
  908. public $handled=false;
  909. public $params;
  910. public function __construct($sender=null,$params=null)
  911. {
  912. $this->sender=$sender;
  913. $this->params=$params;
  914. }
  915. }
  916. class CEnumerable
  917. {
  918. }
  919. abstract class CModule extends CComponent
  920. {
  921. public $preload=array();
  922. public $behaviors=array();
  923. private $_id;
  924. private $_parentModule;
  925. private $_basePath;
  926. private $_modulePath;
  927. private $_params;
  928. private $_modules=array();
  929. private $_moduleConfig=array();
  930. private $_components=array();
  931. private $_componentConfig=array();
  932. public function __construct($id,$parent,$config=null)
  933. {
  934. $this->_id=$id;
  935. $this->_parentModule=$parent;
  936. // set basePath as early as possible to avoid trouble
  937. if(is_string($config))
  938. $config=require($config);
  939. if(isset($config['basePath']))
  940. {
  941. $this->setBasePath($config['basePath']);
  942. unset($config['basePath']);
  943. }
  944. Yii::setPathOfAlias($id,$this->getBasePath());
  945. $this->preinit();
  946. $this->configure($config);
  947. $this->attachBehaviors($this->behaviors);
  948. $this->preloadComponents();
  949. $this->init();
  950. }
  951. public function __get($name)
  952. {
  953. if($this->hasComponent($name))
  954. return $this->getComponent($name);
  955. else
  956. return parent::__get($name);
  957. }
  958. public function __isset($name)
  959. {
  960. if($this->hasComponent($name))
  961. return $this->getComponent($name)!==null;
  962. else
  963. return parent::__isset($name);
  964. }
  965. public function getId()
  966. {
  967. return $this->_id;
  968. }
  969. public function setId($id)
  970. {
  971. $this->_id=$id;
  972. }
  973. public function getBasePath()
  974. {
  975. if($this->_basePath===null)
  976. {
  977. $class=new ReflectionClass(get_class($this));
  978. $this->_basePath=dirname($class->getFileName());
  979. }
  980. return $this->_basePath;
  981. }
  982. public function setBasePath($path)
  983. {
  984. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  985. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  986. array('{path}'=>$path)));
  987. }
  988. public function getParams()
  989. {
  990. if($this->_params!==null)
  991. return $this->_params;
  992. else
  993. {
  994. $this->_params=new CAttributeCollection;
  995. $this->_params->caseSensitive=true;
  996. return $this->_params;
  997. }
  998. }
  999. public function setParams($value)
  1000. {
  1001. $params=$this->getParams();
  1002. foreach($value as $k=>$v)
  1003. $params->add($k,$v);
  1004. }
  1005. public function getModulePath()
  1006. {
  1007. if($this->_modulePath!==null)
  1008. return $this->_modulePath;
  1009. else
  1010. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  1011. }
  1012. public function setModulePath($value)
  1013. {
  1014. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  1015. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  1016. array('{path}'=>$value)));
  1017. }
  1018. public function setImport($aliases)
  1019. {
  1020. foreach($aliases as $alias)
  1021. Yii::import($alias);
  1022. }
  1023. public function setAliases($mappings)
  1024. {
  1025. foreach($mappings as $name=>$alias)
  1026. {
  1027. if(($path=Yii::getPathOfAlias($alias))!==false)
  1028. Yii::setPathOfAlias($name,$path);
  1029. else
  1030. Yii::setPathOfAlias($name,$alias);
  1031. }
  1032. }
  1033. public function getParentModule()
  1034. {
  1035. return $this->_parentModule;
  1036. }
  1037. public function getModule($id)
  1038. {
  1039. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  1040. return $this->_modules[$id];
  1041. elseif(isset($this->_moduleConfig[$id]))
  1042. {
  1043. $config=$this->_moduleConfig[$id];
  1044. if(!isset($config['enabled']) || $config['enabled'])
  1045. {
  1046. $class=$config['class'];
  1047. unset($config['class'], $config['enabled']);
  1048. if($this===Yii::app())
  1049. $module=Yii::createComponent($class,$id,null,$config);
  1050. else
  1051. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  1052. return $this->_modules[$id]=$module;
  1053. }
  1054. }
  1055. }
  1056. public function hasModule($id)
  1057. {
  1058. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  1059. }
  1060. public function getModules()
  1061. {
  1062. return $this->_moduleConfig;
  1063. }
  1064. public function setModules($modules,$merge=true)
  1065. {
  1066. foreach($modules as $id=>$module)
  1067. {
  1068. if(is_int($id))
  1069. {
  1070. $id=$module;
  1071. $module=array();
  1072. }
  1073. if(isset($this->_moduleConfig[$id]) && $merge)
  1074. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1075. else
  1076. {
  1077. if(!isset($module['class']))
  1078. {
  1079. if (Yii::getPathOfAlias($id)===false)
  1080. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1081. $module['class']=$id.'.'.ucfirst($id).'Module';
  1082. }
  1083. $this->_moduleConfig[$id]=$module;
  1084. }
  1085. }
  1086. }
  1087. public function hasComponent($id)
  1088. {
  1089. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1090. }
  1091. public function getComponent($id,$createIfNull=true)
  1092. {
  1093. if(isset($this->_components[$id]))
  1094. return $this->_components[$id];
  1095. elseif(isset($this->_componentConfig[$id]) && $createIfNull)
  1096. {
  1097. $config=$this->_componentConfig[$id];
  1098. if(!isset($config['enabled']) || $config['enabled'])
  1099. {
  1100. unset($config['enabled']);
  1101. $component=Yii::createComponent($config);
  1102. $component->init();
  1103. return $this->_components[$id]=$component;
  1104. }
  1105. }
  1106. }
  1107. public function setComponent($id,$component,$merge=true)
  1108. {
  1109. if($component===null)
  1110. {
  1111. unset($this->_components[$id]);
  1112. return;
  1113. }
  1114. elseif($component instanceof IApplicationComponent)
  1115. {
  1116. $this->_components[$id]=$component;
  1117. if(!$component->getIsInitialized())
  1118. $component->init();
  1119. return;
  1120. }
  1121. elseif(isset($this->_components[$id]))
  1122. {
  1123. if(isset($component['class']) && get_class($this->_components[$id])!==$component['class'])
  1124. {
  1125. unset($this->_components[$id]);
  1126. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1127. return;
  1128. }
  1129. foreach($component as $key=>$value)
  1130. {
  1131. if($key!=='class')
  1132. $this->_components[$id]->$key=$value;
  1133. }
  1134. }
  1135. elseif(isset($this->_componentConfig[$id]['class'],$component['class'])
  1136. && $this->_componentConfig[$id]['class']!==$component['class'])
  1137. {
  1138. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1139. return;
  1140. }
  1141. if(isset($this->_componentConfig[$id]) && $merge)
  1142. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1143. else
  1144. $this->_componentConfig[$id]=$component;
  1145. }
  1146. public function getComponents($loadedOnly=true)
  1147. {
  1148. if($loadedOnly)
  1149. return $this->_components;
  1150. else
  1151. return array_merge($this->_componentConfig, $this->_components);
  1152. }
  1153. public function setComponents($components,$merge=true)
  1154. {
  1155. foreach($components as $id=>$component)
  1156. $this->setComponent($id,$component,$merge);
  1157. }
  1158. public function configure($config)
  1159. {
  1160. if(is_array($config))
  1161. {
  1162. foreach($config as $key=>$value)
  1163. $this->$key=$value;
  1164. }
  1165. }
  1166. protected function preloadComponents()
  1167. {
  1168. foreach($this->preload as $id)
  1169. $this->getComponent($id);
  1170. }
  1171. protected function preinit()
  1172. {
  1173. }
  1174. protected function init()
  1175. {
  1176. }
  1177. }
  1178. abstract class CApplication extends CModule
  1179. {
  1180. public $name='My Application';
  1181. public $charset='UTF-8';
  1182. public $sourceLanguage='en_us';
  1183. public $localeClass='CLocale';
  1184. private $_id;
  1185. private $_basePath;
  1186. private $_runtimePath;
  1187. private $_extensionPath;
  1188. private $_globalState;
  1189. private $_stateChanged;
  1190. private $_ended=false;
  1191. private $_language;
  1192. private $_homeUrl;
  1193. abstract public function processRequest();
  1194. public function __construct($config=null)
  1195. {
  1196. Yii::setApplication($this);
  1197. // set basePath as early as possible to avoid trouble
  1198. if(is_string($config))
  1199. $config=require($config);
  1200. if(isset($config['basePath']))
  1201. {
  1202. $this->setBasePath($config['basePath']);
  1203. unset($config['basePath']);
  1204. }
  1205. else
  1206. $this->setBasePath('protected');
  1207. Yii::setPathOfAlias('application',$this->getBasePath());
  1208. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1209. if(isset($config['extensionPath']))
  1210. {
  1211. $this->setExtensionPath($config['extensionPath']);
  1212. unset($config['extensionPath']);
  1213. }
  1214. else
  1215. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1216. if(isset($config['aliases']))
  1217. {
  1218. $this->setAliases($config['aliases']);
  1219. unset($config['aliases']);
  1220. }
  1221. $this->preinit();
  1222. $this->initSystemHandlers();
  1223. $this->registerCoreComponents();
  1224. $this->configure($config);
  1225. $this->attachBehaviors($this->behaviors);
  1226. $this->preloadComponents();
  1227. $this->init();
  1228. }
  1229. public function run()
  1230. {
  1231. if($this->hasEventHandler('onBeginRequest'))
  1232. $this->onBeginRequest(new CEvent($this));
  1233. register_shutdown_function(array($this,'end'),0,false);
  1234. $this->processRequest();
  1235. if($this->hasEventHandler('onEndRequest'))
  1236. $this->onEndRequest(new CEvent($this));
  1237. }
  1238. public function end($status=0,$exit=true)
  1239. {
  1240. if($this->hasEventHandler('onEndRequest'))
  1241. $this->onEndRequest(new CEvent($this));
  1242. if($exit)
  1243. exit($status);
  1244. }
  1245. public function onBeginRequest($event)
  1246. {
  1247. $this->raiseEvent('onBeginRequest',$event);
  1248. }
  1249. public function onEndRequest($event)
  1250. {
  1251. if(!$this->_ended)
  1252. {
  1253. $this->_ended=true;
  1254. $this->raiseEvent('onEndRequest',$event);
  1255. }
  1256. }
  1257. public function getId()
  1258. {
  1259. if($this->_id!==null)
  1260. return $this->_id;
  1261. else
  1262. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1263. }
  1264. public function setId($id)
  1265. {
  1266. $this->_id=$id;
  1267. }
  1268. public function getBasePath()
  1269. {
  1270. return $this->_basePath;
  1271. }
  1272. public function setBasePath($path)
  1273. {
  1274. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1275. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1276. array('{path}'=>$path)));
  1277. }
  1278. public function getRuntimePath()
  1279. {
  1280. if($this->_runtimePath!==null)
  1281. return $this->_runtimePath;
  1282. else
  1283. {
  1284. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1285. return $this->_runtimePath;
  1286. }
  1287. }
  1288. public function setRuntimePath($path)
  1289. {
  1290. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1291. 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.',
  1292. array('{path}'=>$path)));
  1293. $this->_runtimePath=$runtimePath;
  1294. }
  1295. public function getExtensionPath()
  1296. {
  1297. return Yii::getPathOfAlias('ext');
  1298. }
  1299. public function setExtensionPath($path)
  1300. {
  1301. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1302. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1303. array('{path}'=>$path)));
  1304. Yii::setPathOfAlias('ext',$extensionPath);
  1305. }
  1306. public function getLanguage()
  1307. {
  1308. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1309. }
  1310. public function setLanguage($language)
  1311. {
  1312. $this->_language=$language;
  1313. }
  1314. public function getTimeZone()
  1315. {
  1316. return date_default_timezone_get();
  1317. }
  1318. public function setTimeZone($value)
  1319. {
  1320. date_default_timezone_set($value);
  1321. }
  1322. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1323. {
  1324. if($srcLanguage===null)
  1325. $srcLanguage=$this->sourceLanguage;
  1326. if($language===null)
  1327. $language=$this->getLanguage();
  1328. if($language===$srcLanguage)
  1329. return $srcFile;
  1330. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1331. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1332. }
  1333. public function getLocale($localeID=null)
  1334. {
  1335. return call_user_func_array(array($this->localeClass, 'getInstance'),array($localeID===null?$this->getLanguage():$localeID));
  1336. }
  1337. public function getLocaleDataPath()
  1338. {
  1339. $vars=get_class_vars($this->localeClass);
  1340. if(empty($vars['dataPath']))
  1341. return Yii::getPathOfAlias('system.i18n.data');
  1342. return $vars['dataPath'];
  1343. }
  1344. public function setLocaleDataPath($value)
  1345. {
  1346. $property=new ReflectionProperty($this->localeClass,'dataPath');
  1347. $property->setValue($value);
  1348. }
  1349. public function getNumberFormatter()
  1350. {
  1351. return $this->getLocale()->getNumberFormatter();
  1352. }
  1353. public function getDateFormatter()
  1354. {
  1355. return $this->getLocale()->getDateFormatter();
  1356. }
  1357. public function getDb()
  1358. {
  1359. return $this->getComponent('db');
  1360. }
  1361. public function getErrorHandler()
  1362. {
  1363. return $this->getComponent('errorHandler');
  1364. }
  1365. public function getSecurityManager()
  1366. {
  1367. return $this->getComponent('securityManager');
  1368. }
  1369. public function getStatePersister()
  1370. {
  1371. return $this->getComponent('statePersister');
  1372. }
  1373. public function getCache()
  1374. {
  1375. return $this->getComponent('cache');
  1376. }
  1377. public function getCoreMessages()
  1378. {
  1379. return $this->getComponent('coreMessages');
  1380. }
  1381. public function getMessages()
  1382. {
  1383. return $this->getComponent('messages');
  1384. }
  1385. public function getRequest()
  1386. {
  1387. return $this->getComponent('request');
  1388. }
  1389. public function getUrlManager()
  1390. {
  1391. return $this->getComponent('urlManager');
  1392. }
  1393. public function getFormat()
  1394. {
  1395. return $this->getComponent('format');
  1396. }
  1397. public function getController()
  1398. {
  1399. return null;
  1400. }
  1401. public function createUrl($route,$params=array(),$ampersand='&')
  1402. {
  1403. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1404. }
  1405. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1406. {
  1407. $url=$this->createUrl($route,$params,$ampersand);
  1408. if(strpos($url,'http')===0 || strpos($url,'//')===0)
  1409. return $url;
  1410. else
  1411. return $this->getRequest()->getHostInfo($schema).$url;
  1412. }
  1413. public function getBaseUrl($absolute=false)
  1414. {
  1415. return $this->getRequest()->getBaseUrl($absolute);
  1416. }
  1417. public function getHomeUrl()
  1418. {
  1419. if($this->_homeUrl===null)
  1420. {
  1421. if($this->getUrlManager()->showScriptName)
  1422. return $this->getRequest()->getScriptUrl();
  1423. else
  1424. return $this->getRequest()->getBaseUrl().'/';
  1425. }
  1426. else
  1427. return $this->_homeUrl;
  1428. }
  1429. public function setHomeUrl($value)
  1430. {
  1431. $this->_homeUrl=$value;
  1432. }
  1433. public function getGlobalState($key,$defaultValue=null)
  1434. {
  1435. if($this->_globalState===null)
  1436. $this->loadGlobalState();
  1437. if(isset($this->_globalState[$key]))
  1438. return $this->_globalState[$key];
  1439. else
  1440. return $defaultValue;
  1441. }
  1442. public function setGlobalState($key,$value,$defaultValue=null)
  1443. {
  1444. if($this->_globalState===null)
  1445. $this->loadGlobalState();
  1446. $changed=$this->_stateChanged;
  1447. if($value===$defaultValue)
  1448. {
  1449. if(isset($this->_globalState[$key]))
  1450. {
  1451. unset($this->_globalState[$key]);
  1452. $this->_stateChanged=true;
  1453. }
  1454. }
  1455. elseif(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1456. {
  1457. $this->_globalState[$key]=$value;
  1458. $this->_stateChanged=true;
  1459. }
  1460. if($this->_stateChanged!==$changed)
  1461. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1462. }
  1463. public function clearGlobalState($key)
  1464. {
  1465. $this->setGlobalState($key,true,true);
  1466. }
  1467. public function loadGlobalState()
  1468. {
  1469. $persister=$this->getStatePersister();
  1470. if(($this->_globalState=$persister->load())===null)
  1471. $this->_globalState=array();
  1472. $this->_stateChanged=false;
  1473. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1474. }
  1475. public function saveGlobalState()
  1476. {
  1477. if($this->_stateChanged)
  1478. {
  1479. $this->_stateChanged=false;
  1480. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1481. $this->getStatePersister()->save($this->_globalState);
  1482. }
  1483. }
  1484. public function handleException($exception)
  1485. {
  1486. // disable error capturing to avoid recursive errors
  1487. restore_error_handler();
  1488. restore_exception_handler();
  1489. $category='exception.'.get_class($exception);
  1490. if($exception instanceof CHttpException)
  1491. $category.='.'.$exception->statusCode;
  1492. // php <5.2 doesn't support string conversion auto-magically
  1493. $message=$exception->__toString();
  1494. if(isset($_SERVER['REQUEST_URI']))
  1495. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  1496. if(isset($_SERVER['HTTP_REFERER']))
  1497. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  1498. $message.="\n---";
  1499. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1500. try
  1501. {
  1502. $event=new CExceptionEvent($this,$exception);
  1503. $this->onException($event);
  1504. if(!$event->handled)
  1505. {
  1506. // try an error handler
  1507. if(($handler=$this->getErrorHandler())!==null)
  1508. $handler->handle($event);
  1509. else
  1510. $this->displayException($exception);
  1511. }
  1512. }
  1513. catch(Exception $e)
  1514. {
  1515. $this->displayException($e);
  1516. }
  1517. try
  1518. {
  1519. $this->end(1);
  1520. }
  1521. catch(Exception $e)
  1522. {
  1523. // use the most primitive way to log error
  1524. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1525. $msg .= $e->getTraceAsString()."\n";
  1526. $msg .= "Previous exception:\n";
  1527. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1528. $msg .= $exception->getTraceAsString()."\n";
  1529. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1530. error_log($msg);
  1531. exit(1);
  1532. }
  1533. }
  1534. public function handleError($code,$message,$file,$line)
  1535. {
  1536. if($code & error_reporting())
  1537. {
  1538. // disable error capturing to avoid recursive errors
  1539. restore_error_handler();
  1540. restore_exception_handler();
  1541. $log="$message ($file:$line)\nStack trace:\n";
  1542. $trace=debug_backtrace();
  1543. array_shift($trace);
  1544. foreach($trace as $i=>$t)
  1545. {
  1546. if(!isset($t['file']))
  1547. $t['file']='unknown';
  1548. if(!isset($t['line']))
  1549. $t['line']=0;
  1550. if(!isset($t['function']))
  1551. $t['function']='unknown';
  1552. $log.="#$i {$t['file']}({$t['line']}): ";
  1553. if(isset($t['object']) && is_object($t['object']))
  1554. $log.=get_class($t['object']).'->';
  1555. $log.="{$t['function']}()\n";
  1556. }
  1557. if(isset($_SERVER['REQUEST_URI']))
  1558. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1559. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1560. try
  1561. {
  1562. Yii::import('CErrorEvent',true);
  1563. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1564. $this->onError($event);
  1565. if(!$event->handled)
  1566. {
  1567. // try an error handler
  1568. if(($handler=$this->getErrorHandler())!==null)
  1569. $handler->handle($event);
  1570. else
  1571. $this->displayError($code,$message,$file,$line);
  1572. }
  1573. }
  1574. catch(Exception $e)
  1575. {
  1576. $this->displayException($e);
  1577. }
  1578. try
  1579. {
  1580. $this->end(1);
  1581. }
  1582. catch(Exception $e)
  1583. {
  1584. // use the most primitive way to log error
  1585. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1586. $msg .= $e->getTraceAsString()."\n";
  1587. $msg .= "Previous error:\n";
  1588. $msg .= $log."\n";
  1589. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1590. error_log($msg);
  1591. exit(1);
  1592. }
  1593. }
  1594. }
  1595. public function onException($event)
  1596. {
  1597. $this->raiseEvent('onException',$event);
  1598. }
  1599. public function onError($event)
  1600. {
  1601. $this->raiseEvent('onError',$event);
  1602. }
  1603. public function displayError($code,$message,$file,$line)
  1604. {
  1605. if(YII_DEBUG)
  1606. {
  1607. echo "<h1>PHP Error [$code]</h1>\n";
  1608. echo "<p>$message ($file:$line)</p>\n";
  1609. echo '<pre>';
  1610. $trace=debug_backtrace();
  1611. // skip the first 2 stacks as they are always irrelevant
  1612. if(count($trace)>2)
  1613. $trace=array_slice($trace,2);
  1614. foreach($trace as $i=>$t)
  1615. {
  1616. if(!isset($t['file']))
  1617. $t['file']='unknown';
  1618. if(!isset($t['line']))
  1619. $t['line']=0;
  1620. if(!isset($t['function']))
  1621. $t['function']='unknown';
  1622. echo "#$i {$t['file']}({$t['line']}): ";
  1623. if(isset($t['object']) && is_object($t['object']))
  1624. echo get_class($t['object']).'->';
  1625. echo "{$t['function']}()\n";
  1626. }
  1627. echo '</pre>';
  1628. }
  1629. else
  1630. {
  1631. echo "<h1>PHP Error [$code]</h1>\n";
  1632. echo "<p>$message</p>\n";
  1633. }
  1634. }
  1635. public function displayException($exception)
  1636. {
  1637. if(YII_DEBUG)
  1638. {
  1639. echo '<h1>'.get_class($exception)."</h1>\n";
  1640. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1641. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1642. }
  1643. else
  1644. {
  1645. echo '<h1>'.get_class($exception)."</h1>\n";
  1646. echo '<p>'.$exception->getMessage().'</p>';
  1647. }
  1648. }
  1649. protected function initSystemHandlers()
  1650. {
  1651. if(YII_ENABLE_EXCEPTION_HANDLER)
  1652. set_exception_handler(array($this,'handleException'));
  1653. if(YII_ENABLE_ERROR_HANDLER)
  1654. set_error_handler(array($this,'handleError'),error_reporting());
  1655. }
  1656. protected function registerCoreComponents()
  1657. {
  1658. $components=array(
  1659. 'coreMessages'=>array(
  1660. 'class'=>'CPhpMessageSource',
  1661. 'language'=>'en_us',
  1662. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1663. ),
  1664. 'db'=>array(
  1665. 'class'=>'CDbConnection',
  1666. ),
  1667. 'messages'=>array(
  1668. 'class'=>'CPhpMessageSource',
  1669. ),
  1670. 'errorHandler'=>array(
  1671. 'class'=>'CErrorHandler',
  1672. ),
  1673. 'securityManager'=>array(
  1674. 'class'=>'CSecurityManager',
  1675. ),
  1676. 'statePersister'=>array(
  1677. 'class'=>'CStatePersister',
  1678. ),
  1679. 'urlManager'=>array(
  1680. 'class'=>'CUrlManager',
  1681. ),
  1682. 'request'=>array(
  1683. 'class'=>'CHttpRequest',
  1684. ),
  1685. 'format'=>array(
  1686. 'class'=>'CFormatter',
  1687. ),
  1688. );
  1689. $this->setComponents($components);
  1690. }
  1691. }
  1692. class CWebApplication extends CApplication
  1693. {
  1694. public $defaultController='site';
  1695. public $layout='main';
  1696. public $controllerMap=array();
  1697. public $catchAllRequest;
  1698. public $controllerNamespace;
  1699. private $_controllerPath;
  1700. private $_viewPath;
  1701. private $_systemViewPath;
  1702. private $_layoutPath;
  1703. private $_controller;
  1704. private $_theme;
  1705. public function processRequest()
  1706. {
  1707. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1708. {
  1709. $route=$this->catchAllRequest[0];
  1710. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1711. $_GET[$name]=$value;
  1712. }
  1713. else
  1714. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1715. $this->runController($route);
  1716. }
  1717. protected function registerCoreComponents()
  1718. {
  1719. parent::registerCoreComponents();
  1720. $components=array(
  1721. 'session'=>array(
  1722. 'class'=>'CHttpSession',
  1723. ),
  1724. 'assetManager'=>array(
  1725. 'class'=>'CAssetManager',
  1726. ),
  1727. 'user'=>array(
  1728. 'class'=>'CWebUser',
  1729. ),
  1730. 'themeManager'=>array(
  1731. 'class'=>'CThemeManager',
  1732. ),
  1733. 'authManager'=>array(
  1734. 'class'=>'CPhpAuthManager',
  1735. ),
  1736. 'clientScript'=>array(
  1737. 'class'=>'CClientScript',
  1738. ),
  1739. 'widgetFactory'=>array(
  1740. 'class'=>'CWidgetFactory',
  1741. ),
  1742. );
  1743. $this->setComponents($components);
  1744. }
  1745. public function getAuthManager()
  1746. {
  1747. return $this->getComponent('authManager');
  1748. }
  1749. public function getAssetManager()
  1750. {
  1751. return $this->getComponent('assetManager');
  1752. }
  1753. public function getSession()
  1754. {
  1755. return $this->getComponent('session');
  1756. }
  1757. public function getUser()
  1758. {
  1759. return $this->getComponent('user');
  1760. }
  1761. public function getViewRenderer()
  1762. {
  1763. return $this->getComponent('viewRenderer');
  1764. }
  1765. public function getClientScript()
  1766. {
  1767. return $this->getComponent('clientScript');
  1768. }
  1769. public function getWidgetFactory()
  1770. {
  1771. return $this->getComponent('widgetFactory');
  1772. }
  1773. public function getThemeManager()
  1774. {
  1775. return $this->getComponent('themeManager');
  1776. }
  1777. public function getTheme()
  1778. {
  1779. if(is_string($this->_theme))
  1780. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1781. return $this->_theme;
  1782. }
  1783. public function setTheme($value)
  1784. {
  1785. $this->_theme=$value;
  1786. }
  1787. public function runController($route)
  1788. {
  1789. if(($ca=$this->createController($route))!==null)
  1790. {
  1791. list($controller,$actionID)=$ca;
  1792. $oldController=$this->_controller;
  1793. $this->_controller=$controller;
  1794. $controller->init();
  1795. $controller->run($actionID);
  1796. $this->_controller=$oldController;
  1797. }
  1798. else
  1799. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1800. array('{route}'=>$route===''?$this->defaultController:$route)));
  1801. }
  1802. public function createController($route,$owner=null)
  1803. {
  1804. if($owner===null)
  1805. $owner=$this;
  1806. if((array)$route===$route || ($route=trim($route,'/'))==='')
  1807. $route=$owner->defaultController;
  1808. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1809. $route.='/';
  1810. while(($pos=strpos($route,'/'))!==false)
  1811. {
  1812. $id=substr($route,0,$pos);
  1813. if(!preg_match('/^\w+$/',$id))
  1814. return null;
  1815. if(!$caseSensitive)
  1816. $id=strtolower($id);
  1817. $route=(string)substr($route,$pos+1);
  1818. if(!isset($basePath)) // first segment
  1819. {
  1820. if(isset($owner->controllerMap[$id]))
  1821. {
  1822. return array(
  1823. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1824. $this->parseActionParams($route),
  1825. );
  1826. }
  1827. if(($module=$owner->getModule($id))!==null)
  1828. return $this->createController($route,$module);
  1829. $basePath=$owner->getControllerPath();
  1830. $controllerID='';
  1831. }
  1832. else
  1833. $controllerID.='/';
  1834. $className=ucfirst($id).'Controller';
  1835. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1836. if($owner->controllerNamespace!==null)
  1837. $className=$owner->controllerNamespace.'\\'.str_replace('/','\\',$controllerID).$className;
  1838. if(is_file($classFile))
  1839. {
  1840. if(!class_exists($className,false))
  1841. require($classFile);
  1842. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1843. {
  1844. $id[0]=strtolower($id[0]);
  1845. return array(
  1846. new $className($controllerID.$id,$owner===$this?null:$owner),
  1847. $this->parseActionParams($route),
  1848. );
  1849. }
  1850. return null;
  1851. }
  1852. $controllerID.=$id;
  1853. $basePath.=DIRECTORY_SEPARATOR.$id;
  1854. }
  1855. }
  1856. protected function parseActionParams($pathInfo)
  1857. {
  1858. if(($pos=strpos($pathInfo,'/'))!==false)
  1859. {
  1860. $manager=$this->getUrlManager();
  1861. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1862. $actionID=substr($pathInfo,0,$pos);
  1863. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1864. }
  1865. else
  1866. return $pathInfo;
  1867. }
  1868. public function getController()
  1869. {
  1870. return $this->_controller;
  1871. }
  1872. public function setController($value)
  1873. {
  1874. $this->_controller=$value;
  1875. }
  1876. public function getControllerPath()
  1877. {
  1878. if($this->_controllerPath!==null)
  1879. return $this->_controllerPath;
  1880. else
  1881. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1882. }
  1883. public function setControllerPath($value)
  1884. {
  1885. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1886. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1887. array('{path}'=>$value)));
  1888. }
  1889. public function getViewPath()
  1890. {
  1891. if($this->_viewPath!==null)
  1892. return $this->_viewPath;
  1893. else
  1894. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1895. }
  1896. public function setViewPath($path)
  1897. {
  1898. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1899. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1900. array('{path}'=>$path)));
  1901. }
  1902. public function getSystemViewPath()
  1903. {
  1904. if($this->_systemViewPath!==null)
  1905. return $this->_systemViewPath;
  1906. else
  1907. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1908. }
  1909. public function setSystemViewPath($path)
  1910. {
  1911. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1912. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1913. array('{path}'=>$path)));
  1914. }
  1915. public function getLayoutPath()
  1916. {
  1917. if($this->_layoutPath!==null)
  1918. return $this->_layoutPath;
  1919. else
  1920. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1921. }
  1922. public function setLayoutPath($path)
  1923. {
  1924. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1925. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1926. array('{path}'=>$path)));
  1927. }
  1928. public function beforeControllerAction($controller,$action)
  1929. {
  1930. return true;
  1931. }
  1932. public function afterControllerAction($controller,$action)
  1933. {
  1934. }
  1935. public function findModule($id)
  1936. {
  1937. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1938. {
  1939. do
  1940. {
  1941. if(($m=$module->getModule($id))!==null)
  1942. return $m;
  1943. } while(($module=$module->getParentModule())!==null);
  1944. }
  1945. if(($m=$this->getModule($id))!==null)
  1946. return $m;
  1947. }
  1948. protected function init()
  1949. {
  1950. parent::init();
  1951. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1952. $this->getRequest();
  1953. }
  1954. }
  1955. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1956. {
  1957. private $_d=array();
  1958. private $_r=false;
  1959. public function __construct($data=null,$readOnly=false)
  1960. {
  1961. if($data!==null)
  1962. $this->copyFrom($data);
  1963. $this->setReadOnly($readOnly);
  1964. }
  1965. public function getReadOnly()
  1966. {
  1967. return $this->_r;
  1968. }
  1969. protected function setReadOnly($value)
  1970. {
  1971. $this->_r=$value;
  1972. }
  1973. public function getIterator()
  1974. {
  1975. return new CMapIterator($this->_d);
  1976. }
  1977. public function count()
  1978. {
  1979. return $this->getCount();
  1980. }
  1981. public function getCount()
  1982. {
  1983. return count($this->_d);
  1984. }
  1985. public function getKeys()
  1986. {
  1987. return array_keys($this->_d);
  1988. }
  1989. public function itemAt($key)
  1990. {
  1991. if(isset($this->_d[$key]))
  1992. return $this->_d[$key];
  1993. else
  1994. return null;
  1995. }
  1996. public function add($key,$value)
  1997. {
  1998. if(!$this->_r)
  1999. {
  2000. if($key===null)
  2001. $this->_d[]=$value;
  2002. else
  2003. $this->_d[$key]=$value;
  2004. }
  2005. else
  2006. throw new CException(Yii::t('yii','The map is read only.'));
  2007. }
  2008. public function remove($key)
  2009. {
  2010. if(!$this->_r)
  2011. {
  2012. if(isset($this->_d[$key]))
  2013. {
  2014. $value=$this->_d[$key];
  2015. unset($this->_d[$key]);
  2016. return $value;
  2017. }
  2018. else
  2019. {
  2020. // it is possible the value is null, which is not detected by isset
  2021. unset($this->_d[$key]);
  2022. return null;
  2023. }
  2024. }
  2025. else
  2026. throw new CException(Yii::t('yii','The map is read only.'));
  2027. }
  2028. public function clear()
  2029. {
  2030. foreach(array_keys($this->_d) as $key)
  2031. $this->remove($key);
  2032. }
  2033. public function contains($key)
  2034. {
  2035. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  2036. }
  2037. public function toArray()
  2038. {
  2039. return $this->_d;
  2040. }
  2041. public function copyFrom($data)
  2042. {
  2043. if(is_array($data) || $data instanceof Traversable)
  2044. {
  2045. if($this->getCount()>0)
  2046. $this->clear();
  2047. if($data instanceof CMap)
  2048. $data=$data->_d;
  2049. foreach($data as $key=>$value)
  2050. $this->add($key,$value);
  2051. }
  2052. elseif($data!==null)
  2053. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  2054. }
  2055. public function mergeWith($data,$recursive=true)
  2056. {
  2057. if(is_array($data) || $data instanceof Traversable)
  2058. {
  2059. if($data instanceof CMap)
  2060. $data=$data->_d;
  2061. if($recursive)
  2062. {
  2063. if($data instanceof Traversable)
  2064. {
  2065. $d=array();
  2066. foreach($data as $key=>$value)
  2067. $d[$key]=$value;
  2068. $this->_d=self::mergeArray($this->_d,$d);
  2069. }
  2070. else
  2071. $this->_d=self::mergeArray($this->_d,$data);
  2072. }
  2073. else
  2074. {
  2075. foreach($data as $key=>$value)
  2076. $this->add($key,$value);
  2077. }
  2078. }
  2079. elseif($data!==null)
  2080. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  2081. }
  2082. public static function mergeArray($a,$b)
  2083. {
  2084. $args=func_get_args();
  2085. $res=array_shift($args);
  2086. while(!empty($args))
  2087. {
  2088. $next=array_shift($args);
  2089. foreach($next as $k => $v)
  2090. {
  2091. if(is_integer($k))
  2092. isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
  2093. elseif(is_array($v) && isset($res[$k]) && is_array($res[$k]))
  2094. $res[$k]=self::mergeArray($res[$k],$v);
  2095. else
  2096. $res[$k]=$v;
  2097. }
  2098. }
  2099. return $res;
  2100. }
  2101. public function offsetExists($offset)
  2102. {
  2103. return $this->contains($offset);
  2104. }
  2105. public function offsetGet($offset)
  2106. {
  2107. return $this->itemAt($offset);
  2108. }
  2109. public function offsetSet($offset,$item)
  2110. {
  2111. $this->add($offset,$item);
  2112. }
  2113. public function offsetUnset($offset)
  2114. {
  2115. $this->remove($offset);
  2116. }
  2117. }
  2118. class CLogger extends CComponent
  2119. {
  2120. const LEVEL_TRACE='trace';
  2121. const LEVEL_WARNING='warning';
  2122. const LEVEL_ERROR='error';
  2123. const LEVEL_INFO='info';
  2124. const LEVEL_PROFILE='profile';
  2125. public $autoFlush=10000;
  2126. public $autoDump=false;
  2127. private $_logs=array();
  2128. private $_logCount=0;
  2129. private $_levels;
  2130. private $_categories;
  2131. private $_except=array();
  2132. private $_timings;
  2133. private $_processing=false;
  2134. public function log($message,$level='info',$category='application')
  2135. {
  2136. $this->_logs[]=array($message,$level,$category,microtime(true));
  2137. $this->_logCount++;
  2138. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
  2139. {
  2140. $this->_processing=true;
  2141. $this->flush($this->autoDump);
  2142. $this->_processing=false;
  2143. }
  2144. }
  2145. public function getLogs($levels='',$categories=array(), $except=array())
  2146. {
  2147. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2148. if (is_string($categories))
  2149. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2150. else
  2151. $this->_categories=array_filter(array_map('strtolower',$categories));
  2152. if (is_string($except))
  2153. $this->_except=preg_split('/[\s,]+/',strtolower($except),-1,PREG_SPLIT_NO_EMPTY);
  2154. else
  2155. $this->_except=array_filter(array_map('strtolower',$except));
  2156. $ret=$this->_logs;
  2157. if(!empty($levels))
  2158. $ret=array_values(array_filter($ret,array($this,'filterByLevel')));
  2159. if(!empty($this->_categories) || !empty($this->_except))
  2160. $ret=array_values(array_filter($ret,array($this,'filterByCategory')));
  2161. return $ret;
  2162. }
  2163. private function filterByCategory($value)
  2164. {
  2165. return $this->filterAllCategories($value, 2);
  2166. }
  2167. private function filterTimingByCategory($value)
  2168. {
  2169. return $this->filterAllCategories($value, 1);
  2170. }
  2171. private function filterAllCategories($value, $index)
  2172. {
  2173. $cat=strtolower($value[$index]);
  2174. $ret=empty($this->_categories);
  2175. foreach($this->_categories as $category)
  2176. {
  2177. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2178. $ret=true;
  2179. }
  2180. if($ret)
  2181. {
  2182. foreach($this->_except as $category)
  2183. {
  2184. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2185. $ret=false;
  2186. }
  2187. }
  2188. return $ret;
  2189. }
  2190. private function filterByLevel($value)
  2191. {
  2192. return in_array(strtolower($value[1]),$this->_levels);
  2193. }
  2194. public function getExecutionTime()
  2195. {
  2196. return microtime(true)-YII_BEGIN_TIME;
  2197. }
  2198. public function getMemoryUsage()
  2199. {
  2200. if(function_exists('memory_get_usage'))
  2201. return memory_get_usage();
  2202. else
  2203. {
  2204. $output=array();
  2205. if(strncmp(PHP_OS,'WIN',3)===0)
  2206. {
  2207. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2208. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2209. }
  2210. else
  2211. {
  2212. $pid=getmypid();
  2213. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2214. $output=explode(" ",$output[0]);
  2215. return isset($output[1]) ? $output[1]*1024 : 0;
  2216. }
  2217. }
  2218. }
  2219. public function getProfilingResults($token=null,$categories=null,$refresh=false)
  2220. {
  2221. if($this->_timings===null || $refresh)
  2222. $this->calculateTimings();
  2223. if($token===null && $categories===null)
  2224. return $this->_timings;
  2225. $timings = $this->_timings;
  2226. if($categories!==null) {
  2227. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2228. $timings=array_filter($timings,array($this,'filterTimingByCategory'));
  2229. }
  2230. $results=array();
  2231. foreach($timings as $timing)
  2232. {
  2233. if($token===null || $timing[0]===$token)
  2234. $results[]=$timing[2];
  2235. }
  2236. return $results;
  2237. }
  2238. private function calculateTimings()
  2239. {
  2240. $this->_timings=array();
  2241. $stack=array();
  2242. foreach($this->_logs as $log)
  2243. {
  2244. if($log[1]!==CLogger::LEVEL_PROFILE)
  2245. continue;
  2246. list($message,$level,$category,$timestamp)=$log;
  2247. if(!strncasecmp($message,'begin:',6))
  2248. {
  2249. $log[0]=substr($message,6);
  2250. $stack[]=$log;
  2251. }
  2252. elseif(!strncasecmp($message,'end:',4))
  2253. {
  2254. $token=substr($message,4);
  2255. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2256. {
  2257. $delta=$log[3]-$last[3];
  2258. $this->_timings[]=array($message,$category,$delta);
  2259. }
  2260. else
  2261. 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.',
  2262. array('{token}'=>$token)));
  2263. }
  2264. }
  2265. $now=microtime(true);
  2266. while(($last=array_pop($stack))!==null)
  2267. {
  2268. $delta=$now-$last[3];
  2269. $this->_timings[]=array($last[0],$last[2],$delta);
  2270. }
  2271. }
  2272. public function flush($dumpLogs=false)
  2273. {
  2274. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2275. $this->_logs=array();
  2276. $this->_logCount=0;
  2277. }
  2278. public function onFlush($event)
  2279. {
  2280. $this->raiseEvent('onFlush', $event);
  2281. }
  2282. }
  2283. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2284. {
  2285. public $behaviors=array();
  2286. private $_initialized=false;
  2287. public function init()
  2288. {
  2289. $this->attachBehaviors($this->behaviors);
  2290. $this->_initialized=true;
  2291. }
  2292. public function getIsInitialized()
  2293. {
  2294. return $this->_initialized;
  2295. }
  2296. }
  2297. class CHttpRequest extends CApplicationComponent
  2298. {
  2299. public $jsonAsArray = true;
  2300. public $enableCookieValidation=false;
  2301. public $enableCsrfValidation=false;
  2302. public $csrfTokenName='YII_CSRF_TOKEN';
  2303. public $csrfCookie;
  2304. private $_requestUri;
  2305. private $_pathInfo;
  2306. private $_scriptFile;
  2307. private $_scriptUrl;
  2308. private $_hostInfo;
  2309. private $_baseUrl;
  2310. private $_cookies;
  2311. private $_preferredAcceptTypes;
  2312. private $_preferredLanguages;
  2313. private $_csrfToken;
  2314. private $_restParams;
  2315. private $_httpVersion;
  2316. public function init()
  2317. {
  2318. parent::init();
  2319. $this->normalizeRequest();
  2320. }
  2321. protected function normalizeRequest()
  2322. {
  2323. // normalize request
  2324. if(version_compare(PHP_VERSION,'7.4.0','<'))
  2325. {
  2326. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2327. {
  2328. if(isset($_GET))
  2329. $_GET=$this->stripSlashes($_GET);
  2330. if(isset($_POST))
  2331. $_POST=$this->stripSlashes($_POST);
  2332. if(isset($_REQUEST))
  2333. $_REQUEST=$this->stripSlashes($_REQUEST);
  2334. if(isset($_COOKIE))
  2335. $_COOKIE=$this->stripSlashes($_COOKIE);
  2336. }
  2337. }
  2338. if($this->enableCsrfValidation)
  2339. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2340. }
  2341. public function stripSlashes(&$data)
  2342. {
  2343. if(is_array($data))
  2344. {
  2345. if(count($data) == 0)
  2346. return $data;
  2347. $keys=array_map('stripslashes',array_keys($data));
  2348. $data=array_combine($keys,array_values($data));
  2349. return array_map(array($this,'stripSlashes'),$data);
  2350. }
  2351. else
  2352. return stripslashes($data);
  2353. }
  2354. public function getParam($name,$defaultValue=null)
  2355. {
  2356. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2357. }
  2358. public function getQuery($name,$defaultValue=null)
  2359. {
  2360. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2361. }
  2362. public function getPost($name,$defaultValue=null)
  2363. {
  2364. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2365. }
  2366. public function getDelete($name,$defaultValue=null)
  2367. {
  2368. if($this->getIsDeleteViaPostRequest())
  2369. return $this->getPost($name, $defaultValue);
  2370. if($this->getIsDeleteRequest())
  2371. {
  2372. $restParams=$this->getRestParams();
  2373. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2374. }
  2375. else
  2376. return $defaultValue;
  2377. }
  2378. public function getPut($name,$defaultValue=null)
  2379. {
  2380. if($this->getIsPutViaPostRequest())
  2381. return $this->getPost($name, $defaultValue);
  2382. if($this->getIsPutRequest())
  2383. {
  2384. $restParams=$this->getRestParams();
  2385. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2386. }
  2387. else
  2388. return $defaultValue;
  2389. }
  2390. public function getPatch($name,$defaultValue=null)
  2391. {
  2392. if($this->getIsPatchViaPostRequest())
  2393. return $this->getPost($name, $defaultValue);
  2394. if($this->getIsPatchRequest())
  2395. {
  2396. $restParams=$this->getRestParams();
  2397. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2398. }
  2399. else
  2400. return $defaultValue;
  2401. }
  2402. public function getRestParams()
  2403. {
  2404. if($this->_restParams===null)
  2405. {
  2406. $result=array();
  2407. if (strncmp($this->getContentType(), 'application/json', 16) === 0)
  2408. $result = CJSON::decode($this->getRawBody(), $this->jsonAsArray);
  2409. elseif(function_exists('mb_parse_str'))
  2410. mb_parse_str($this->getRawBody(), $result);
  2411. else
  2412. parse_str($this->getRawBody(), $result);
  2413. $this->_restParams=$result;
  2414. }
  2415. return $this->_restParams;
  2416. }
  2417. public function getRawBody()
  2418. {
  2419. static $rawBody;
  2420. if($rawBody===null)
  2421. $rawBody=file_get_contents('php://input');
  2422. return $rawBody;
  2423. }
  2424. public function getUrl()
  2425. {
  2426. return $this->getRequestUri();
  2427. }
  2428. public function getHostInfo($schema='')
  2429. {
  2430. if($this->_hostInfo===null)
  2431. {
  2432. if($secure=$this->getIsSecureConnection())
  2433. $http='https';
  2434. else
  2435. $http='http';
  2436. if(isset($_SERVER['HTTP_HOST']))
  2437. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2438. else
  2439. {
  2440. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2441. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2442. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2443. $this->_hostInfo.=':'.$port;
  2444. }
  2445. }
  2446. if($schema!=='')
  2447. {
  2448. $secure=$this->getIsSecureConnection();
  2449. if($secure && $schema==='https' || !$secure && $schema==='http')
  2450. return $this->_hostInfo;
  2451. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2452. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2453. $port=':'.$port;
  2454. else
  2455. $port='';
  2456. $pos=strpos($this->_hostInfo,':');
  2457. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2458. }
  2459. else
  2460. return $this->_hostInfo;
  2461. }
  2462. public function setHostInfo($value)
  2463. {
  2464. $this->_hostInfo=rtrim($value,'/');
  2465. }
  2466. public function getBaseUrl($absolute=false)
  2467. {
  2468. if($this->_baseUrl===null)
  2469. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2470. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2471. }
  2472. public function setBaseUrl($value)
  2473. {
  2474. $this->_baseUrl=$value;
  2475. }
  2476. public function getScriptUrl()
  2477. {
  2478. if($this->_scriptUrl===null)
  2479. {
  2480. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2481. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2482. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2483. elseif(basename($_SERVER['PHP_SELF'])===$scriptName)
  2484. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2485. elseif(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2486. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2487. elseif(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2488. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2489. elseif(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2490. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2491. else
  2492. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2493. }
  2494. return $this->_scriptUrl;
  2495. }
  2496. public function setScriptUrl($value)
  2497. {
  2498. $this->_scriptUrl='/'.trim($value,'/');
  2499. }
  2500. public function getPathInfo()
  2501. {
  2502. if($this->_pathInfo===null)
  2503. {
  2504. $pathInfo=$this->getRequestUri();
  2505. if(($pos=strpos($pathInfo,'?'))!==false)
  2506. $pathInfo=substr($pathInfo,0,$pos);
  2507. $pathInfo=$this->decodePathInfo($pathInfo);
  2508. $scriptUrl=$this->getScriptUrl();
  2509. $baseUrl=$this->getBaseUrl();
  2510. if(strpos($pathInfo,$scriptUrl)===0)
  2511. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2512. elseif($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2513. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2514. elseif(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2515. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2516. else
  2517. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2518. if($pathInfo==='/' || $pathInfo===false)
  2519. $pathInfo='';
  2520. elseif($pathInfo!=='' && $pathInfo[0]==='/')
  2521. $pathInfo=substr($pathInfo,1);
  2522. if(($posEnd=strlen($pathInfo)-1)>0 && $pathInfo[$posEnd]==='/')
  2523. $pathInfo=substr($pathInfo,0,$posEnd);
  2524. $this->_pathInfo=$pathInfo;
  2525. }
  2526. return $this->_pathInfo;
  2527. }
  2528. protected function decodePathInfo($pathInfo)
  2529. {
  2530. $pathInfo = urldecode($pathInfo);
  2531. // is it UTF-8?
  2532. // http://w3.org/International/questions/qa-forms-utf-8.html
  2533. if(preg_match('%^(?:
  2534. [\x09\x0A\x0D\x20-\x7E] # ASCII
  2535. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  2536. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  2537. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  2538. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  2539. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  2540. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  2541. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  2542. )*$%xs', $pathInfo))
  2543. {
  2544. return $pathInfo;
  2545. }
  2546. else
  2547. {
  2548. return utf8_encode($pathInfo);
  2549. }
  2550. }
  2551. public function getRequestUri()
  2552. {
  2553. if($this->_requestUri===null)
  2554. {
  2555. if(isset($_SERVER['REQUEST_URI']))
  2556. {
  2557. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2558. if(!empty($_SERVER['HTTP_HOST']))
  2559. {
  2560. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2561. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2562. }
  2563. else
  2564. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2565. }
  2566. elseif(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2567. {
  2568. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2569. if(!empty($_SERVER['QUERY_STRING']))
  2570. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2571. }
  2572. else
  2573. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2574. }
  2575. return $this->_requestUri;
  2576. }
  2577. public function getQueryString()
  2578. {
  2579. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2580. }
  2581. public function getIsSecureConnection()
  2582. {
  2583. return isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'],'on')===0 || $_SERVER['HTTPS']==1)
  2584. || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'],'https')===0;
  2585. }
  2586. public function getRequestType()
  2587. {
  2588. if(isset($_POST['_method']))
  2589. return strtoupper($_POST['_method']);
  2590. elseif(isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']))
  2591. return strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
  2592. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2593. }
  2594. public function getIsPostRequest()
  2595. {
  2596. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2597. }
  2598. public function getIsDeleteRequest()
  2599. {
  2600. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE')) || $this->getIsDeleteViaPostRequest();
  2601. }
  2602. protected function getIsDeleteViaPostRequest()
  2603. {
  2604. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'DELETE');
  2605. }
  2606. public function getIsPutRequest()
  2607. {
  2608. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT')) || $this->getIsPutViaPostRequest();
  2609. }
  2610. protected function getIsPutViaPostRequest()
  2611. {
  2612. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PUT');
  2613. }
  2614. public function getIsPatchRequest()
  2615. {
  2616. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PATCH')) || $this->getIsPatchViaPostRequest();
  2617. }
  2618. protected function getIsPatchViaPostRequest()
  2619. {
  2620. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PATCH');
  2621. }
  2622. public function getIsAjaxRequest()
  2623. {
  2624. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2625. }
  2626. public function getIsFlashRequest()
  2627. {
  2628. return isset($_SERVER['HTTP_USER_AGENT']) && (stripos($_SERVER['HTTP_USER_AGENT'],'Shockwave')!==false || stripos($_SERVER['HTTP_USER_AGENT'],'Flash')!==false);
  2629. }
  2630. public function getServerName()
  2631. {
  2632. return $_SERVER['SERVER_NAME'];
  2633. }
  2634. public function getServerPort()
  2635. {
  2636. return $_SERVER['SERVER_PORT'];
  2637. }
  2638. public function getUrlReferrer()
  2639. {
  2640. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2641. }
  2642. public function getUserAgent()
  2643. {
  2644. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2645. }
  2646. public function getUserHostAddress()
  2647. {
  2648. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2649. }
  2650. public function getUserHost()
  2651. {
  2652. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2653. }
  2654. public function getScriptFile()
  2655. {
  2656. if($this->_scriptFile!==null)
  2657. return $this->_scriptFile;
  2658. else
  2659. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2660. }
  2661. public function getBrowser($userAgent=null)
  2662. {
  2663. return get_browser($userAgent,true);
  2664. }
  2665. public function getAcceptTypes()
  2666. {
  2667. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2668. }
  2669. public function getContentType()
  2670. {
  2671. if (isset($_SERVER["CONTENT_TYPE"])) {
  2672. return $_SERVER["CONTENT_TYPE"];
  2673. } elseif (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
  2674. //fix bug https://bugs.php.net/bug.php?id=66606
  2675. return $_SERVER["HTTP_CONTENT_TYPE"];
  2676. }
  2677. return null;
  2678. }
  2679. private $_port;
  2680. public function getPort()
  2681. {
  2682. if($this->_port===null)
  2683. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2684. return $this->_port;
  2685. }
  2686. public function setPort($value)
  2687. {
  2688. $this->_port=(int)$value;
  2689. $this->_hostInfo=null;
  2690. }
  2691. private $_securePort;
  2692. public function getSecurePort()
  2693. {
  2694. if($this->_securePort===null)
  2695. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2696. return $this->_securePort;
  2697. }
  2698. public function setSecurePort($value)
  2699. {
  2700. $this->_securePort=(int)$value;
  2701. $this->_hostInfo=null;
  2702. }
  2703. public function getCookies()
  2704. {
  2705. if($this->_cookies!==null)
  2706. return $this->_cookies;
  2707. else
  2708. return $this->_cookies=new CCookieCollection($this);
  2709. }
  2710. public function redirect($url,$terminate=true,$statusCode=302)
  2711. {
  2712. if(strpos($url,'/')===0 && strpos($url,'//')!==0)
  2713. $url=$this->getHostInfo().$url;
  2714. header('Location: '.$url, true, $statusCode);
  2715. if($terminate)
  2716. Yii::app()->end();
  2717. }
  2718. public static function parseAcceptHeader($header)
  2719. {
  2720. $matches=array();
  2721. $accepts=array();
  2722. // get individual entries with their type, subtype, basetype and params
  2723. preg_match_all('/(?:\G\s?,\s?|^)(\w+|\*)\/(\w+|\*)(?:\+(\w+))?|(?<!^)\G(?:\s?;\s?(\w+)=([\w\.]+))/',$header,$matches);
  2724. // the regexp should (in theory) always return an array of 6 arrays
  2725. if(count($matches)===6)
  2726. {
  2727. $i=0;
  2728. $itemLen=count($matches[1]);
  2729. while($i<$itemLen)
  2730. {
  2731. // fill out a content type
  2732. $accept=array(
  2733. 'type'=>$matches[1][$i],
  2734. 'subType'=>$matches[2][$i],
  2735. 'baseType'=>null,
  2736. 'params'=>array(),
  2737. );
  2738. // fill in the base type if it exists
  2739. if($matches[3][$i]!==null && $matches[3][$i]!=='')
  2740. $accept['baseType']=$matches[3][$i];
  2741. // continue looping while there is no new content type, to fill in all accompanying params
  2742. for($i++;$i<$itemLen;$i++)
  2743. {
  2744. // if the next content type is null, then the item is a param for the current content type
  2745. if($matches[1][$i]===null || $matches[1][$i]==='')
  2746. {
  2747. // if this is the quality param, convert it to a double
  2748. if($matches[4][$i]==='q')
  2749. {
  2750. // sanity check on q value
  2751. $q=(double)$matches[5][$i];
  2752. if($q>1)
  2753. $q=(double)1;
  2754. elseif($q<0)
  2755. $q=(double)0;
  2756. $accept['params'][$matches[4][$i]]=$q;
  2757. }
  2758. else
  2759. $accept['params'][$matches[4][$i]]=$matches[5][$i];
  2760. }
  2761. else
  2762. break;
  2763. }
  2764. // q defaults to 1 if not explicitly given
  2765. if(!isset($accept['params']['q']))
  2766. $accept['params']['q']=(double)1;
  2767. $accepts[] = $accept;
  2768. }
  2769. }
  2770. return $accepts;
  2771. }
  2772. public static function compareAcceptTypes($a,$b)
  2773. {
  2774. // check for equal quality first
  2775. if($a['params']['q']===$b['params']['q'])
  2776. if(!($a['type']==='*' xor $b['type']==='*'))
  2777. if (!($a['subType']==='*' xor $b['subType']==='*'))
  2778. // finally, higher number of parameters counts as greater precedence
  2779. if(count($a['params'])===count($b['params']))
  2780. return 0;
  2781. else
  2782. return count($a['params'])<count($b['params']) ? 1 : -1;
  2783. // more specific takes precedence - whichever one doesn't have a * subType
  2784. else
  2785. return $a['subType']==='*' ? 1 : -1;
  2786. // more specific takes precedence - whichever one doesn't have a * type
  2787. else
  2788. return $a['type']==='*' ? 1 : -1;
  2789. else
  2790. return ($a['params']['q']<$b['params']['q']) ? 1 : -1;
  2791. }
  2792. public function getPreferredAcceptTypes()
  2793. {
  2794. if($this->_preferredAcceptTypes===null)
  2795. {
  2796. $accepts=self::parseAcceptHeader($this->getAcceptTypes());
  2797. usort($accepts,array(get_class($this),'compareAcceptTypes'));
  2798. $this->_preferredAcceptTypes=$accepts;
  2799. }
  2800. return $this->_preferredAcceptTypes;
  2801. }
  2802. public function getPreferredAcceptType()
  2803. {
  2804. $preferredAcceptTypes=$this->getPreferredAcceptTypes();
  2805. return empty($preferredAcceptTypes) ? false : $preferredAcceptTypes[0];
  2806. }
  2807. private function stringCompare($a, $b)
  2808. {
  2809. if ($a[0] == $b[0]) {
  2810. return 0;
  2811. }
  2812. return ($a[0] < $b[0]) ? 1 : -1;
  2813. }
  2814. public function getPreferredLanguages()
  2815. {
  2816. if($this->_preferredLanguages===null)
  2817. {
  2818. $sortedLanguages=array();
  2819. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $n=preg_match_all('/([\w\-_]+)(?:\s*;\s*q\s*=\s*(\d*\.?\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))
  2820. {
  2821. $languages=array();
  2822. for($i=0;$i<$n;++$i)
  2823. {
  2824. $q=$matches[2][$i];
  2825. if($q==='')
  2826. $q=1;
  2827. if($q)
  2828. $languages[]=array((float)$q,$matches[1][$i]);
  2829. }
  2830. usort($languages, array($this, 'stringCompare'));
  2831. foreach($languages as $language)
  2832. $sortedLanguages[]=$language[1];
  2833. }
  2834. $this->_preferredLanguages=$sortedLanguages;
  2835. }
  2836. return $this->_preferredLanguages;
  2837. }
  2838. public function getPreferredLanguage($languages=array())
  2839. {
  2840. $preferredLanguages=$this->getPreferredLanguages();
  2841. if(empty($languages)) {
  2842. return !empty($preferredLanguages) ? CLocale::getCanonicalID($preferredLanguages[0]) : false;
  2843. }
  2844. foreach ($preferredLanguages as $preferredLanguage) {
  2845. $preferredLanguage=CLocale::getCanonicalID($preferredLanguage);
  2846. foreach ($languages as $language) {
  2847. $language=CLocale::getCanonicalID($language);
  2848. // en_us==en_us, en==en_us, en_us==en
  2849. if($language===$preferredLanguage || strpos($preferredLanguage,$language.'_')===0 || strpos($language,$preferredLanguage.'_')===0) {
  2850. return $language;
  2851. }
  2852. }
  2853. }
  2854. return reset($languages);
  2855. }
  2856. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2857. {
  2858. if($mimeType===null)
  2859. {
  2860. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2861. $mimeType='text/plain';
  2862. }
  2863. $fileSize=(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content));
  2864. $contentStart=0;
  2865. $contentEnd=$fileSize-1;
  2866. $httpVersion=$this->getHttpVersion();
  2867. if(isset($_SERVER['HTTP_RANGE']))
  2868. {
  2869. header('Accept-Ranges: bytes');
  2870. //client sent us a multibyte range, can not hold this one for now
  2871. if(strpos($_SERVER['HTTP_RANGE'],',')!==false)
  2872. {
  2873. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2874. throw new CHttpException(416,'Requested Range Not Satisfiable');
  2875. }
  2876. $range=str_replace('bytes=','',$_SERVER['HTTP_RANGE']);
  2877. //range requests starts from "-", so it means that data must be dumped the end point.
  2878. if($range[0]==='-')
  2879. $contentStart=$fileSize-substr($range,1);
  2880. else
  2881. {
  2882. $range=explode('-',$range);
  2883. $contentStart=$range[0];
  2884. // check if the last-byte-pos presents in header
  2885. if((isset($range[1]) && is_numeric($range[1])))
  2886. $contentEnd=$range[1];
  2887. }
  2888. /* Check the range and make sure it's treated according to the specs.
  2889. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  2890. */
  2891. // End bytes can not be larger than $end.
  2892. $contentEnd=($contentEnd > $fileSize) ? $fileSize-1 : $contentEnd;
  2893. // Validate the requested range and return an error if it's not correct.
  2894. $wrongContentStart=($contentStart>$contentEnd || $contentStart>$fileSize-1 || $contentStart<0);
  2895. if($wrongContentStart)
  2896. {
  2897. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2898. throw new CHttpException(416,'Requested Range Not Satisfiable');
  2899. }
  2900. header("HTTP/$httpVersion 206 Partial Content");
  2901. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2902. }
  2903. else
  2904. header("HTTP/$httpVersion 200 OK");
  2905. $length=$contentEnd-$contentStart+1; // Calculate new content length
  2906. header('Pragma: public');
  2907. header('Expires: 0');
  2908. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2909. header("Content-Type: $mimeType");
  2910. header('Content-Length: '.$length);
  2911. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2912. header('Content-Transfer-Encoding: binary');
  2913. $content=function_exists('mb_substr') ? mb_substr($content,$contentStart,$length,'8bit') : substr($content,$contentStart,$length);
  2914. if($terminate)
  2915. {
  2916. // clean up the application first because the file downloading could take long time
  2917. // which may cause timeout of some resources (such as DB connection)
  2918. ob_start();
  2919. Yii::app()->end(0,false);
  2920. ob_end_clean();
  2921. echo $content;
  2922. exit(0);
  2923. }
  2924. else
  2925. echo $content;
  2926. }
  2927. public function xSendFile($filePath, $options=array())
  2928. {
  2929. if(!isset($options['forceDownload']) || $options['forceDownload'])
  2930. $disposition='attachment';
  2931. else
  2932. $disposition='inline';
  2933. if(!isset($options['saveName']))
  2934. $options['saveName']=basename($filePath);
  2935. if(!isset($options['mimeType']))
  2936. {
  2937. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2938. $options['mimeType']='text/plain';
  2939. }
  2940. if(!isset($options['xHeader']))
  2941. $options['xHeader']='X-Sendfile';
  2942. if($options['mimeType']!==null)
  2943. header('Content-Type: '.$options['mimeType']);
  2944. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  2945. if(isset($options['addHeaders']))
  2946. {
  2947. foreach($options['addHeaders'] as $header=>$value)
  2948. header($header.': '.$value);
  2949. }
  2950. header(trim($options['xHeader']).': '.$filePath);
  2951. if(!isset($options['terminate']) || $options['terminate'])
  2952. Yii::app()->end();
  2953. }
  2954. public function getCsrfToken()
  2955. {
  2956. if($this->_csrfToken===null)
  2957. {
  2958. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2959. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2960. {
  2961. $cookie=$this->createCsrfCookie();
  2962. $this->_csrfToken=$cookie->value;
  2963. $this->getCookies()->add($cookie->name,$cookie);
  2964. }
  2965. }
  2966. return $this->_csrfToken;
  2967. }
  2968. protected function createCsrfCookie()
  2969. {
  2970. $securityManager=Yii::app()->getSecurityManager();
  2971. $token=$securityManager->generateRandomBytes(32);
  2972. $maskedToken=$securityManager->maskToken($token);
  2973. $cookie=new CHttpCookie($this->csrfTokenName,$maskedToken);
  2974. if(is_array($this->csrfCookie))
  2975. {
  2976. foreach($this->csrfCookie as $name=>$value)
  2977. $cookie->$name=$value;
  2978. }
  2979. return $cookie;
  2980. }
  2981. public function validateCsrfToken($event)
  2982. {
  2983. if ($this->getIsPostRequest() ||
  2984. $this->getIsPutRequest() ||
  2985. $this->getIsPatchRequest() ||
  2986. $this->getIsDeleteRequest())
  2987. {
  2988. $cookies=$this->getCookies();
  2989. $method=$this->getRequestType();
  2990. switch($method)
  2991. {
  2992. case 'POST':
  2993. $maskedUserToken=$this->getPost($this->csrfTokenName);
  2994. break;
  2995. case 'PUT':
  2996. $maskedUserToken=$this->getPut($this->csrfTokenName);
  2997. break;
  2998. case 'PATCH':
  2999. $maskedUserToken=$this->getPatch($this->csrfTokenName);
  3000. break;
  3001. case 'DELETE':
  3002. $maskedUserToken=$this->getDelete($this->csrfTokenName);
  3003. }
  3004. if (!empty($maskedUserToken) && $cookies->contains($this->csrfTokenName))
  3005. {
  3006. $securityManager=Yii::app()->getSecurityManager();
  3007. $maskedCookieToken=$cookies->itemAt($this->csrfTokenName)->value;
  3008. $cookieToken=$securityManager->unmaskToken($maskedCookieToken);
  3009. $userToken=$securityManager->unmaskToken($maskedUserToken);
  3010. $valid=$cookieToken===$userToken;
  3011. }
  3012. else
  3013. $valid = false;
  3014. if (!$valid)
  3015. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  3016. }
  3017. }
  3018. public function getHttpVersion()
  3019. {
  3020. if($this->_httpVersion===null)
  3021. {
  3022. if(isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL']==='HTTP/1.0')
  3023. $this->_httpVersion='1.0';
  3024. else
  3025. $this->_httpVersion='1.1';
  3026. }
  3027. return $this->_httpVersion;
  3028. }
  3029. }
  3030. class CCookieCollection extends CMap
  3031. {
  3032. private $_request;
  3033. private $_initialized=false;
  3034. public function __construct(CHttpRequest $request)
  3035. {
  3036. $this->_request=$request;
  3037. $this->copyfrom($this->getCookies());
  3038. $this->_initialized=true;
  3039. }
  3040. public function getRequest()
  3041. {
  3042. return $this->_request;
  3043. }
  3044. protected function getCookies()
  3045. {
  3046. $cookies=array();
  3047. if($this->_request->enableCookieValidation)
  3048. {
  3049. $sm=Yii::app()->getSecurityManager();
  3050. foreach($_COOKIE as $name=>$value)
  3051. {
  3052. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  3053. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  3054. }
  3055. }
  3056. else
  3057. {
  3058. foreach($_COOKIE as $name=>$value)
  3059. $cookies[$name]=new CHttpCookie($name,$value);
  3060. }
  3061. return $cookies;
  3062. }
  3063. public function add($name,$cookie)
  3064. {
  3065. if($cookie instanceof CHttpCookie)
  3066. {
  3067. $this->remove($name);
  3068. parent::add($name,$cookie);
  3069. if($this->_initialized)
  3070. $this->addCookie($cookie);
  3071. }
  3072. else
  3073. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  3074. }
  3075. public function remove($name,$options=array())
  3076. {
  3077. if(($cookie=parent::remove($name))!==null)
  3078. {
  3079. if($this->_initialized)
  3080. {
  3081. $cookie->configure($options);
  3082. $this->removeCookie($cookie);
  3083. }
  3084. }
  3085. return $cookie;
  3086. }
  3087. protected function addCookie($cookie)
  3088. {
  3089. $value=$cookie->value;
  3090. if($this->_request->enableCookieValidation)
  3091. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  3092. if(version_compare(PHP_VERSION,'7.3.0','>='))
  3093. setcookie($cookie->name,$value,$this->getCookieOptions($cookie));
  3094. elseif(version_compare(PHP_VERSION,'5.2.0','>='))
  3095. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  3096. else
  3097. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  3098. }
  3099. protected function removeCookie($cookie)
  3100. {
  3101. $cookie->expire=0;
  3102. if(version_compare(PHP_VERSION,'7.3.0','>='))
  3103. setcookie($cookie->name,'',$this->getCookieOptions($cookie));
  3104. elseif(version_compare(PHP_VERSION,'5.2.0','>='))
  3105. setcookie($cookie->name,'',$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  3106. else
  3107. setcookie($cookie->name,'',$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  3108. }
  3109. protected function getCookieOptions($cookie)
  3110. {
  3111. return array(
  3112. 'expires'=>$cookie->expire,
  3113. 'path'=>$cookie->path,
  3114. 'domain'=>$cookie->domain,
  3115. 'secure'=>$cookie->secure,
  3116. 'httpOnly'=>$cookie->httpOnly,
  3117. 'sameSite'=>$cookie->sameSite
  3118. );
  3119. }
  3120. }
  3121. class CUrlManager extends CApplicationComponent
  3122. {
  3123. const CACHE_KEY='Yii.CUrlManager.rules';
  3124. const GET_FORMAT='get';
  3125. const PATH_FORMAT='path';
  3126. public $rules=array();
  3127. public $urlSuffix='';
  3128. public $showScriptName=true;
  3129. public $appendParams=true;
  3130. public $routeVar='r';
  3131. public $caseSensitive=true;
  3132. public $matchValue=false;
  3133. public $cacheID='cache';
  3134. public $useStrictParsing=false;
  3135. public $urlRuleClass='CUrlRule';
  3136. private $_urlFormat=self::GET_FORMAT;
  3137. private $_rules=array();
  3138. private $_baseUrl;
  3139. public function init()
  3140. {
  3141. parent::init();
  3142. $this->processRules();
  3143. }
  3144. protected function processRules()
  3145. {
  3146. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  3147. return;
  3148. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  3149. {
  3150. $hash=md5(serialize($this->rules));
  3151. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  3152. {
  3153. $this->_rules=$data[0];
  3154. return;
  3155. }
  3156. }
  3157. foreach($this->rules as $pattern=>$route)
  3158. $this->_rules[]=$this->createUrlRule($route,$pattern);
  3159. if(isset($cache))
  3160. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  3161. }
  3162. public function addRules($rules,$append=true)
  3163. {
  3164. if ($append)
  3165. {
  3166. foreach($rules as $pattern=>$route)
  3167. $this->_rules[]=$this->createUrlRule($route,$pattern);
  3168. }
  3169. else
  3170. {
  3171. $rules=array_reverse($rules);
  3172. foreach($rules as $pattern=>$route)
  3173. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  3174. }
  3175. }
  3176. protected function createUrlRule($route,$pattern)
  3177. {
  3178. if(is_array($route) && isset($route['class']))
  3179. return $route;
  3180. else
  3181. {
  3182. $urlRuleClass=Yii::import($this->urlRuleClass,true);
  3183. return new $urlRuleClass($route,$pattern);
  3184. }
  3185. }
  3186. public function createUrl($route,$params=array(),$ampersand='&')
  3187. {
  3188. unset($params[$this->routeVar]);
  3189. foreach($params as $i=>$param)
  3190. if($param===null)
  3191. $params[$i]='';
  3192. if(isset($params['#']))
  3193. {
  3194. $anchor='#'.$params['#'];
  3195. unset($params['#']);
  3196. }
  3197. else
  3198. $anchor='';
  3199. $route=trim($route,'/');
  3200. foreach($this->_rules as $i=>$rule)
  3201. {
  3202. if(is_array($rule))
  3203. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  3204. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  3205. {
  3206. if($rule->hasHostInfo)
  3207. return $url==='' ? '/'.$anchor : $url.$anchor;
  3208. else
  3209. return $this->getBaseUrl().'/'.$url.$anchor;
  3210. }
  3211. }
  3212. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  3213. }
  3214. protected function createUrlDefault($route,$params,$ampersand)
  3215. {
  3216. if($this->getUrlFormat()===self::PATH_FORMAT)
  3217. {
  3218. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  3219. if($this->appendParams)
  3220. {
  3221. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  3222. return $route==='' ? $url : $url.$this->urlSuffix;
  3223. }
  3224. else
  3225. {
  3226. if($route!=='')
  3227. $url.=$this->urlSuffix;
  3228. $query=$this->createPathInfo($params,'=',$ampersand);
  3229. return $query==='' ? $url : $url.'?'.$query;
  3230. }
  3231. }
  3232. else
  3233. {
  3234. $url=$this->getBaseUrl();
  3235. if(!$this->showScriptName)
  3236. $url.='/';
  3237. if($route!=='')
  3238. {
  3239. $url.='?'.$this->routeVar.'='.$route;
  3240. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  3241. $url.=$ampersand.$query;
  3242. }
  3243. elseif(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  3244. $url.='?'.$query;
  3245. return $url;
  3246. }
  3247. }
  3248. public function parseUrl($request)
  3249. {
  3250. if($this->getUrlFormat()===self::PATH_FORMAT)
  3251. {
  3252. $rawPathInfo=$request->getPathInfo();
  3253. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3254. foreach($this->_rules as $i=>$rule)
  3255. {
  3256. if(is_array($rule))
  3257. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  3258. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  3259. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  3260. }
  3261. if($this->useStrictParsing)
  3262. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  3263. array('{route}'=>$pathInfo)));
  3264. else
  3265. return $pathInfo;
  3266. }
  3267. elseif(isset($_GET[$this->routeVar]))
  3268. return $_GET[$this->routeVar];
  3269. elseif(isset($_POST[$this->routeVar]))
  3270. return $_POST[$this->routeVar];
  3271. else
  3272. return '';
  3273. }
  3274. public function parsePathInfo($pathInfo)
  3275. {
  3276. if($pathInfo==='')
  3277. return;
  3278. $segs=explode('/',$pathInfo.'/');
  3279. $n=count($segs);
  3280. for($i=0;$i<$n-1;$i+=2)
  3281. {
  3282. $key=$segs[$i];
  3283. if($key==='') continue;
  3284. $value=$segs[$i+1];
  3285. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  3286. {
  3287. $name=substr($key,0,$pos);
  3288. for($j=$m-1;$j>=0;--$j)
  3289. {
  3290. if($matches[1][$j]==='')
  3291. $value=array($value);
  3292. else
  3293. $value=array($matches[1][$j]=>$value);
  3294. }
  3295. if(isset($_GET[$name]) && is_array($_GET[$name]))
  3296. $value=CMap::mergeArray($_GET[$name],$value);
  3297. $_REQUEST[$name]=$_GET[$name]=$value;
  3298. }
  3299. else
  3300. $_REQUEST[$key]=$_GET[$key]=$value;
  3301. }
  3302. }
  3303. public function createPathInfo($params,$equal,$ampersand, $key=null)
  3304. {
  3305. $pairs = array();
  3306. foreach($params as $k => $v)
  3307. {
  3308. if ($key!==null)
  3309. $k = $key.'['.$k.']';
  3310. if (is_array($v))
  3311. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  3312. else
  3313. $pairs[]=urlencode($k).$equal.urlencode($v);
  3314. }
  3315. return implode($ampersand,$pairs);
  3316. }
  3317. public function removeUrlSuffix($pathInfo,$urlSuffix)
  3318. {
  3319. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  3320. return substr($pathInfo,0,-strlen($urlSuffix));
  3321. else
  3322. return $pathInfo;
  3323. }
  3324. public function getBaseUrl()
  3325. {
  3326. if($this->_baseUrl!==null)
  3327. return $this->_baseUrl;
  3328. else
  3329. {
  3330. if($this->showScriptName)
  3331. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  3332. else
  3333. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  3334. return $this->_baseUrl;
  3335. }
  3336. }
  3337. public function setBaseUrl($value)
  3338. {
  3339. $this->_baseUrl=$value;
  3340. }
  3341. public function getUrlFormat()
  3342. {
  3343. return $this->_urlFormat;
  3344. }
  3345. public function setUrlFormat($value)
  3346. {
  3347. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  3348. $this->_urlFormat=$value;
  3349. else
  3350. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  3351. }
  3352. }
  3353. abstract class CBaseUrlRule extends CComponent
  3354. {
  3355. public $hasHostInfo=false;
  3356. abstract public function createUrl($manager,$route,$params,$ampersand);
  3357. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  3358. }
  3359. class CUrlRule extends CBaseUrlRule
  3360. {
  3361. public $urlSuffix;
  3362. public $caseSensitive;
  3363. public $defaultParams=array();
  3364. public $matchValue;
  3365. public $verb;
  3366. public $parsingOnly=false;
  3367. public $route;
  3368. public $references=array();
  3369. public $routePattern;
  3370. public $pattern;
  3371. public $template;
  3372. public $params=array();
  3373. public $append;
  3374. public $hasHostInfo;
  3375. protected function escapeRegexpSpecialChars($matches)
  3376. {
  3377. return preg_quote($matches[0]);
  3378. }
  3379. public function __construct($route,$pattern)
  3380. {
  3381. if(is_array($route))
  3382. {
  3383. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  3384. {
  3385. if(isset($route[$name]))
  3386. $this->$name=$route[$name];
  3387. }
  3388. if(isset($route['pattern']))
  3389. $pattern=$route['pattern'];
  3390. $route=$route[0];
  3391. }
  3392. $this->route=trim($route,'/');
  3393. $tr2['/']=$tr['/']='\\/';
  3394. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  3395. {
  3396. foreach($matches2[1] as $name)
  3397. $this->references[$name]="<$name>";
  3398. }
  3399. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  3400. if($this->verb!==null)
  3401. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  3402. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  3403. {
  3404. $tokens=array_combine($matches[1],$matches[2]);
  3405. foreach($tokens as $name=>$value)
  3406. {
  3407. if($value==='')
  3408. $value='[^\/]+';
  3409. $tr["<$name>"]="(?P<$name>$value)";
  3410. if(isset($this->references[$name]))
  3411. $tr2["<$name>"]=$tr["<$name>"];
  3412. else
  3413. $this->params[$name]=$value;
  3414. }
  3415. }
  3416. $p=rtrim($pattern,'*');
  3417. $this->append=$p!==$pattern;
  3418. $p=trim($p,'/');
  3419. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  3420. $p=$this->template;
  3421. if(!$this->parsingOnly)
  3422. $p=preg_replace_callback('/(?<=^|>)[^<]+(?=<|$)/',array($this,'escapeRegexpSpecialChars'),$p);
  3423. $this->pattern='/^'.strtr($p,$tr).'\/';
  3424. if($this->append)
  3425. $this->pattern.='/u';
  3426. else
  3427. $this->pattern.='$/u';
  3428. if($this->references!==array())
  3429. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  3430. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  3431. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  3432. array('{route}'=>$route,'{pattern}'=>$pattern)));
  3433. }
  3434. public function createUrl($manager,$route,$params,$ampersand)
  3435. {
  3436. if($this->parsingOnly)
  3437. return false;
  3438. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3439. $case='';
  3440. else
  3441. $case='i';
  3442. $tr=array();
  3443. if($route!==$this->route)
  3444. {
  3445. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  3446. {
  3447. foreach($this->references as $key=>$name)
  3448. $tr[$name]=$matches[$key];
  3449. }
  3450. else
  3451. return false;
  3452. }
  3453. foreach($this->defaultParams as $key=>$value)
  3454. {
  3455. if(isset($params[$key]))
  3456. {
  3457. if($params[$key]==$value)
  3458. unset($params[$key]);
  3459. else
  3460. return false;
  3461. }
  3462. }
  3463. foreach($this->params as $key=>$value)
  3464. if(!isset($params[$key]))
  3465. return false;
  3466. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  3467. {
  3468. foreach($this->params as $key=>$value)
  3469. {
  3470. if(!preg_match('/\A'.$value.'\z/u'.$case,$params[$key]))
  3471. return false;
  3472. }
  3473. }
  3474. foreach($this->params as $key=>$value)
  3475. {
  3476. $tr["<$key>"]=urlencode($params[$key]);
  3477. unset($params[$key]);
  3478. }
  3479. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3480. $url=strtr($this->template,$tr);
  3481. if($this->hasHostInfo)
  3482. {
  3483. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  3484. if(stripos($url,$hostInfo)===0)
  3485. $url=substr($url,strlen($hostInfo));
  3486. }
  3487. if(empty($params))
  3488. return $url!=='' ? $url.$suffix : $url;
  3489. if($this->append)
  3490. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  3491. else
  3492. {
  3493. if($url!=='')
  3494. $url.=$suffix;
  3495. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  3496. }
  3497. return $url;
  3498. }
  3499. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  3500. {
  3501. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  3502. return false;
  3503. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3504. $case='';
  3505. else
  3506. $case='i';
  3507. if($this->urlSuffix!==null)
  3508. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3509. // URL suffix required, but not found in the requested URL
  3510. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3511. {
  3512. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3513. if($urlSuffix!='' && $urlSuffix!=='/')
  3514. return false;
  3515. }
  3516. if($this->hasHostInfo)
  3517. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3518. $pathInfo.='/';
  3519. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3520. {
  3521. foreach($this->defaultParams as $name=>$value)
  3522. {
  3523. if(!isset($_GET[$name]))
  3524. $_REQUEST[$name]=$_GET[$name]=$value;
  3525. }
  3526. $tr=array();
  3527. foreach($matches as $key=>$value)
  3528. {
  3529. if(isset($this->references[$key]))
  3530. $tr[$this->references[$key]]=$value;
  3531. elseif(isset($this->params[$key]))
  3532. $_REQUEST[$key]=$_GET[$key]=$value;
  3533. }
  3534. if($pathInfo!==$matches[0]) // there're additional GET params
  3535. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3536. if($this->routePattern!==null)
  3537. return strtr($this->route,$tr);
  3538. else
  3539. return $this->route;
  3540. }
  3541. else
  3542. return false;
  3543. }
  3544. }
  3545. abstract class CBaseController extends CComponent
  3546. {
  3547. private $_widgetStack=array();
  3548. abstract public function getViewFile($viewName);
  3549. public function renderFile($viewFile,$data=null,$return=false)
  3550. {
  3551. $widgetCount=count($this->_widgetStack);
  3552. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3553. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3554. else
  3555. $content=$this->renderInternal($viewFile,$data,$return);
  3556. if(count($this->_widgetStack)===$widgetCount)
  3557. return $content;
  3558. else
  3559. {
  3560. $widget=end($this->_widgetStack);
  3561. 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.',
  3562. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3563. }
  3564. }
  3565. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3566. {
  3567. // we use special variable names here to avoid conflict when extracting data
  3568. if(is_array($_data_))
  3569. extract($_data_,EXTR_PREFIX_SAME,'data');
  3570. else
  3571. $data=$_data_;
  3572. if($_return_)
  3573. {
  3574. ob_start();
  3575. ob_implicit_flush(false);
  3576. require($_viewFile_);
  3577. return ob_get_clean();
  3578. }
  3579. else
  3580. require($_viewFile_);
  3581. }
  3582. public function createWidget($className,$properties=array())
  3583. {
  3584. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3585. $widget->init();
  3586. return $widget;
  3587. }
  3588. public function widget($className,$properties=array(),$captureOutput=false)
  3589. {
  3590. if($captureOutput)
  3591. {
  3592. ob_start();
  3593. ob_implicit_flush(false);
  3594. try
  3595. {
  3596. $widget=$this->createWidget($className,$properties);
  3597. $widget->run();
  3598. }
  3599. catch(Exception $e)
  3600. {
  3601. ob_end_clean();
  3602. throw $e;
  3603. }
  3604. return ob_get_clean();
  3605. }
  3606. else
  3607. {
  3608. $widget=$this->createWidget($className,$properties);
  3609. $widget->run();
  3610. return $widget;
  3611. }
  3612. }
  3613. public function beginWidget($className,$properties=array())
  3614. {
  3615. $widget=$this->createWidget($className,$properties);
  3616. $this->_widgetStack[]=$widget;
  3617. return $widget;
  3618. }
  3619. public function endWidget($id='')
  3620. {
  3621. if(($widget=array_pop($this->_widgetStack))!==null)
  3622. {
  3623. $widget->run();
  3624. return $widget;
  3625. }
  3626. else
  3627. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3628. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3629. }
  3630. public function beginClip($id,$properties=array())
  3631. {
  3632. $properties['id']=$id;
  3633. $this->beginWidget('CClipWidget',$properties);
  3634. }
  3635. public function endClip()
  3636. {
  3637. $this->endWidget('CClipWidget');
  3638. }
  3639. public function beginCache($id,$properties=array())
  3640. {
  3641. $properties['id']=$id;
  3642. $cache=$this->beginWidget('COutputCache',$properties);
  3643. if($cache->getIsContentCached())
  3644. {
  3645. $this->endCache();
  3646. return false;
  3647. }
  3648. else
  3649. return true;
  3650. }
  3651. public function endCache()
  3652. {
  3653. $this->endWidget('COutputCache');
  3654. }
  3655. public function beginContent($view=null,$data=array())
  3656. {
  3657. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3658. }
  3659. public function endContent()
  3660. {
  3661. $this->endWidget('CContentDecorator');
  3662. }
  3663. }
  3664. class CController extends CBaseController
  3665. {
  3666. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3667. public $layout;
  3668. public $defaultAction='index';
  3669. private $_id;
  3670. private $_action;
  3671. private $_pageTitle;
  3672. private $_cachingStack;
  3673. private $_clips;
  3674. private $_dynamicOutput;
  3675. private $_pageStates;
  3676. private $_module;
  3677. public function __construct($id,$module=null)
  3678. {
  3679. $this->_id=$id;
  3680. $this->_module=$module;
  3681. $this->attachBehaviors($this->behaviors());
  3682. }
  3683. public function init()
  3684. {
  3685. }
  3686. public function filters()
  3687. {
  3688. return array();
  3689. }
  3690. public function actions()
  3691. {
  3692. return array();
  3693. }
  3694. public function behaviors()
  3695. {
  3696. return array();
  3697. }
  3698. public function accessRules()
  3699. {
  3700. return array();
  3701. }
  3702. public function run($actionID)
  3703. {
  3704. if(($action=$this->createAction($actionID))!==null)
  3705. {
  3706. if(($parent=$this->getModule())===null)
  3707. $parent=Yii::app();
  3708. if($parent->beforeControllerAction($this,$action))
  3709. {
  3710. $this->runActionWithFilters($action,$this->filters());
  3711. $parent->afterControllerAction($this,$action);
  3712. }
  3713. }
  3714. else
  3715. $this->missingAction($actionID);
  3716. }
  3717. public function runActionWithFilters($action,$filters)
  3718. {
  3719. if(empty($filters))
  3720. $this->runAction($action);
  3721. else
  3722. {
  3723. $priorAction=$this->_action;
  3724. $this->_action=$action;
  3725. CFilterChain::create($this,$action,$filters)->run();
  3726. $this->_action=$priorAction;
  3727. }
  3728. }
  3729. public function runAction($action)
  3730. {
  3731. $priorAction=$this->_action;
  3732. $this->_action=$action;
  3733. if($this->beforeAction($action))
  3734. {
  3735. if($action->runWithParams($this->getActionParams())===false)
  3736. $this->invalidActionParams($action);
  3737. else
  3738. $this->afterAction($action);
  3739. }
  3740. $this->_action=$priorAction;
  3741. }
  3742. public function getActionParams()
  3743. {
  3744. return $_GET;
  3745. }
  3746. public function invalidActionParams($action)
  3747. {
  3748. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3749. }
  3750. public function processOutput($output)
  3751. {
  3752. Yii::app()->getClientScript()->render($output);
  3753. // if using page caching, we should delay dynamic output replacement
  3754. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3755. {
  3756. $output=$this->processDynamicOutput($output);
  3757. $this->_dynamicOutput=null;
  3758. }
  3759. if($this->_pageStates===null)
  3760. $this->_pageStates=$this->loadPageStates();
  3761. if(!empty($this->_pageStates))
  3762. $this->savePageStates($this->_pageStates,$output);
  3763. return $output;
  3764. }
  3765. public function processDynamicOutput($output)
  3766. {
  3767. if($this->_dynamicOutput)
  3768. {
  3769. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3770. }
  3771. return $output;
  3772. }
  3773. protected function replaceDynamicOutput($matches)
  3774. {
  3775. $content=$matches[0];
  3776. if(isset($this->_dynamicOutput[$matches[1]]))
  3777. {
  3778. $content=$this->_dynamicOutput[$matches[1]];
  3779. $this->_dynamicOutput[$matches[1]]=null;
  3780. }
  3781. return $content;
  3782. }
  3783. public function createAction($actionID)
  3784. {
  3785. if($actionID==='')
  3786. $actionID=$this->defaultAction;
  3787. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3788. return new CInlineAction($this,$actionID);
  3789. else
  3790. {
  3791. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3792. if($action!==null && !method_exists($action,'run'))
  3793. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3794. return $action;
  3795. }
  3796. }
  3797. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3798. {
  3799. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3800. {
  3801. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3802. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3803. }
  3804. elseif($pos===false)
  3805. return null;
  3806. // the action is defined in a provider
  3807. $prefix=substr($actionID,0,$pos+1);
  3808. if(!isset($actionMap[$prefix]))
  3809. return null;
  3810. $actionID=(string)substr($actionID,$pos+1);
  3811. $provider=$actionMap[$prefix];
  3812. if(is_string($provider))
  3813. $providerType=$provider;
  3814. elseif(is_array($provider) && isset($provider['class']))
  3815. {
  3816. $providerType=$provider['class'];
  3817. if(isset($provider[$actionID]))
  3818. {
  3819. if(is_string($provider[$actionID]))
  3820. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3821. else
  3822. $config=array_merge($provider[$actionID],$config);
  3823. }
  3824. }
  3825. else
  3826. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3827. $class=Yii::import($providerType,true);
  3828. $map=call_user_func(array($class,'actions'));
  3829. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3830. }
  3831. public function missingAction($actionID)
  3832. {
  3833. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3834. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3835. }
  3836. public function getAction()
  3837. {
  3838. return $this->_action;
  3839. }
  3840. public function setAction($value)
  3841. {
  3842. $this->_action=$value;
  3843. }
  3844. public function getId()
  3845. {
  3846. return $this->_id;
  3847. }
  3848. public function getUniqueId()
  3849. {
  3850. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3851. }
  3852. public function getRoute()
  3853. {
  3854. if(($action=$this->getAction())!==null)
  3855. return $this->getUniqueId().'/'.$action->getId();
  3856. else
  3857. return $this->getUniqueId();
  3858. }
  3859. public function getModule()
  3860. {
  3861. return $this->_module;
  3862. }
  3863. public function getViewPath()
  3864. {
  3865. if(($module=$this->getModule())===null)
  3866. $module=Yii::app();
  3867. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3868. }
  3869. public function getViewFile($viewName)
  3870. {
  3871. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3872. return $viewFile;
  3873. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3874. if(($module=$this->getModule())!==null)
  3875. $moduleViewPath=$module->getViewPath();
  3876. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3877. }
  3878. public function getLayoutFile($layoutName)
  3879. {
  3880. if($layoutName===false)
  3881. return false;
  3882. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3883. return $layoutFile;
  3884. if(empty($layoutName))
  3885. {
  3886. $module=$this->getModule();
  3887. while($module!==null)
  3888. {
  3889. if($module->layout===false)
  3890. return false;
  3891. if(!empty($module->layout))
  3892. break;
  3893. $module=$module->getParentModule();
  3894. }
  3895. if($module===null)
  3896. $module=Yii::app();
  3897. $layoutName=$module->layout;
  3898. }
  3899. elseif(($module=$this->getModule())===null)
  3900. $module=Yii::app();
  3901. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3902. }
  3903. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3904. {
  3905. if(empty($viewName))
  3906. return false;
  3907. if($moduleViewPath===null)
  3908. $moduleViewPath=$basePath;
  3909. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3910. $extension=$renderer->fileExtension;
  3911. else
  3912. $extension='.php';
  3913. if($viewName[0]==='/')
  3914. {
  3915. if(strncmp($viewName,'//',2)===0)
  3916. $viewFile=$basePath.$viewName;
  3917. else
  3918. $viewFile=$moduleViewPath.$viewName;
  3919. }
  3920. elseif(strpos($viewName,'.'))
  3921. $viewFile=Yii::getPathOfAlias($viewName);
  3922. else
  3923. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3924. if(is_file($viewFile.$extension))
  3925. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3926. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  3927. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3928. else
  3929. return false;
  3930. }
  3931. public function getClips()
  3932. {
  3933. if($this->_clips!==null)
  3934. return $this->_clips;
  3935. else
  3936. return $this->_clips=new CMap;
  3937. }
  3938. public function forward($route,$exit=true)
  3939. {
  3940. if(strpos($route,'/')===false)
  3941. $this->run($route);
  3942. else
  3943. {
  3944. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3945. $route=$module->getId().'/'.$route;
  3946. Yii::app()->runController($route);
  3947. }
  3948. if($exit)
  3949. Yii::app()->end();
  3950. }
  3951. public function render($view,$data=null,$return=false)
  3952. {
  3953. if($this->beforeRender($view))
  3954. {
  3955. $output=$this->renderPartial($view,$data,true);
  3956. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3957. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3958. $this->afterRender($view,$output);
  3959. $output=$this->processOutput($output);
  3960. if($return)
  3961. return $output;
  3962. else
  3963. echo $output;
  3964. }
  3965. }
  3966. protected function beforeRender($view)
  3967. {
  3968. return true;
  3969. }
  3970. protected function afterRender($view, &$output)
  3971. {
  3972. }
  3973. public function renderText($text,$return=false)
  3974. {
  3975. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3976. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3977. $text=$this->processOutput($text);
  3978. if($return)
  3979. return $text;
  3980. else
  3981. echo $text;
  3982. }
  3983. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3984. {
  3985. if(($viewFile=$this->getViewFile($view))!==false)
  3986. {
  3987. $output=$this->renderFile($viewFile,$data,true);
  3988. if($processOutput)
  3989. $output=$this->processOutput($output);
  3990. if($return)
  3991. return $output;
  3992. else
  3993. echo $output;
  3994. }
  3995. else
  3996. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3997. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3998. }
  3999. public function renderClip($name,$params=array(),$return=false)
  4000. {
  4001. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  4002. if($return)
  4003. return $text;
  4004. else
  4005. echo $text;
  4006. }
  4007. public function renderDynamic($callback)
  4008. {
  4009. $n=($this->_dynamicOutput === null ? 0 : count($this->_dynamicOutput));
  4010. echo "<###dynamic-$n###>";
  4011. $params=func_get_args();
  4012. array_shift($params);
  4013. $this->renderDynamicInternal($callback,$params);
  4014. }
  4015. public function renderDynamicInternal($callback,$params)
  4016. {
  4017. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  4018. if(is_string($callback) && method_exists($this,$callback))
  4019. $callback=array($this,$callback);
  4020. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  4021. }
  4022. public function createUrl($route,$params=array(),$ampersand='&')
  4023. {
  4024. if($route==='')
  4025. $route=$this->getId().'/'.$this->getAction()->getId();
  4026. elseif(strpos($route,'/')===false)
  4027. $route=$this->getId().'/'.$route;
  4028. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  4029. $route=$module->getId().'/'.$route;
  4030. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  4031. }
  4032. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  4033. {
  4034. $url=$this->createUrl($route,$params,$ampersand);
  4035. if(strpos($url,'http')===0)
  4036. return $url;
  4037. else
  4038. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  4039. }
  4040. public function getPageTitle()
  4041. {
  4042. if($this->_pageTitle!==null)
  4043. return $this->_pageTitle;
  4044. else
  4045. {
  4046. $name=ucfirst(basename($this->getId()));
  4047. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  4048. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  4049. else
  4050. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  4051. }
  4052. }
  4053. public function setPageTitle($value)
  4054. {
  4055. $this->_pageTitle=$value;
  4056. }
  4057. public function redirect($url,$terminate=true,$statusCode=302)
  4058. {
  4059. if(is_array($url))
  4060. {
  4061. $route=isset($url[0]) ? $url[0] : '';
  4062. $url=$this->createUrl($route,array_splice($url,1));
  4063. }
  4064. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  4065. }
  4066. public function refresh($terminate=true,$anchor='')
  4067. {
  4068. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  4069. }
  4070. public function recordCachingAction($context,$method,$params)
  4071. {
  4072. if($this->_cachingStack) // record only when there is an active output cache
  4073. {
  4074. foreach($this->_cachingStack as $cache)
  4075. $cache->recordAction($context,$method,$params);
  4076. }
  4077. }
  4078. public function getCachingStack($createIfNull=true)
  4079. {
  4080. if(!$this->_cachingStack)
  4081. $this->_cachingStack=new CStack;
  4082. return $this->_cachingStack;
  4083. }
  4084. public function isCachingStackEmpty()
  4085. {
  4086. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  4087. }
  4088. protected function beforeAction($action)
  4089. {
  4090. return true;
  4091. }
  4092. protected function afterAction($action)
  4093. {
  4094. }
  4095. public function filterPostOnly($filterChain)
  4096. {
  4097. if(Yii::app()->getRequest()->getIsPostRequest())
  4098. $filterChain->run();
  4099. else
  4100. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  4101. }
  4102. public function filterAjaxOnly($filterChain)
  4103. {
  4104. if(Yii::app()->getRequest()->getIsAjaxRequest())
  4105. $filterChain->run();
  4106. else
  4107. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  4108. }
  4109. public function filterAccessControl($filterChain)
  4110. {
  4111. $filter=new CAccessControlFilter;
  4112. $filter->setRules($this->accessRules());
  4113. $filter->filter($filterChain);
  4114. }
  4115. public function getPageState($name,$defaultValue=null)
  4116. {
  4117. if($this->_pageStates===null)
  4118. $this->_pageStates=$this->loadPageStates();
  4119. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  4120. }
  4121. public function setPageState($name,$value,$defaultValue=null)
  4122. {
  4123. if($this->_pageStates===null)
  4124. $this->_pageStates=$this->loadPageStates();
  4125. if($value===$defaultValue)
  4126. unset($this->_pageStates[$name]);
  4127. else
  4128. $this->_pageStates[$name]=$value;
  4129. $params=func_get_args();
  4130. $this->recordCachingAction('','setPageState',$params);
  4131. }
  4132. public function clearPageStates()
  4133. {
  4134. $this->_pageStates=array();
  4135. }
  4136. protected function loadPageStates()
  4137. {
  4138. if(!empty($_POST[self::STATE_INPUT_NAME]))
  4139. {
  4140. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  4141. {
  4142. if(extension_loaded('zlib'))
  4143. $data=@gzuncompress($data);
  4144. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  4145. return unserialize($data);
  4146. }
  4147. }
  4148. return array();
  4149. }
  4150. protected function savePageStates($states,&$output)
  4151. {
  4152. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  4153. if(extension_loaded('zlib'))
  4154. $data=gzcompress($data);
  4155. $value=base64_encode($data);
  4156. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  4157. }
  4158. }
  4159. abstract class CAction extends CComponent implements IAction
  4160. {
  4161. private $_id;
  4162. private $_controller;
  4163. public function __construct($controller,$id)
  4164. {
  4165. $this->_controller=$controller;
  4166. $this->_id=$id;
  4167. }
  4168. public function getController()
  4169. {
  4170. return $this->_controller;
  4171. }
  4172. public function getId()
  4173. {
  4174. return $this->_id;
  4175. }
  4176. public function runWithParams($params)
  4177. {
  4178. $method=new ReflectionMethod($this, 'run');
  4179. if($method->getNumberOfParameters()>0)
  4180. return $this->runWithParamsInternal($this, $method, $params);
  4181. $this->run();
  4182. return true;
  4183. }
  4184. protected function runWithParamsInternal($object, $method, $params)
  4185. {
  4186. $ps=array();
  4187. foreach($method->getParameters() as $i=>$param)
  4188. {
  4189. $name=$param->getName();
  4190. if(isset($params[$name]))
  4191. {
  4192. if(version_compare(PHP_VERSION,'8.0','>=')) {
  4193. $isArray=$param->getType() && $param->getType()->getName()==='array';
  4194. } else {
  4195. $isArray=$param->isArray();
  4196. }
  4197. if($isArray)
  4198. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  4199. elseif(!is_array($params[$name]))
  4200. $ps[]=$params[$name];
  4201. else
  4202. return false;
  4203. }
  4204. elseif($param->isDefaultValueAvailable())
  4205. $ps[]=$param->getDefaultValue();
  4206. else
  4207. return false;
  4208. }
  4209. $method->invokeArgs($object,$ps);
  4210. return true;
  4211. }
  4212. }
  4213. class CInlineAction extends CAction
  4214. {
  4215. public function run()
  4216. {
  4217. $method='action'.$this->getId();
  4218. $this->getController()->$method();
  4219. }
  4220. public function runWithParams($params)
  4221. {
  4222. $methodName='action'.$this->getId();
  4223. $controller=$this->getController();
  4224. $method=new ReflectionMethod($controller, $methodName);
  4225. if($method->getNumberOfParameters()>0)
  4226. return $this->runWithParamsInternal($controller, $method, $params);
  4227. $controller->$methodName();
  4228. return true;
  4229. }
  4230. }
  4231. class CWebUser extends CApplicationComponent implements IWebUser
  4232. {
  4233. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  4234. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  4235. const STATES_VAR='__states';
  4236. const AUTH_TIMEOUT_VAR='__timeout';
  4237. const AUTH_ABSOLUTE_TIMEOUT_VAR='__absolute_timeout';
  4238. public $allowAutoLogin=false;
  4239. public $guestName='Guest';
  4240. public $loginUrl=array('/site/login');
  4241. public $identityCookie;
  4242. public $authTimeout;
  4243. public $absoluteAuthTimeout;
  4244. public $autoRenewCookie=false;
  4245. public $autoUpdateFlash=true;
  4246. public $loginRequiredAjaxResponse;
  4247. private $_keyPrefix;
  4248. private $_access=array();
  4249. public function __get($name)
  4250. {
  4251. if($this->hasState($name))
  4252. return $this->getState($name);
  4253. else
  4254. return parent::__get($name);
  4255. }
  4256. public function __set($name,$value)
  4257. {
  4258. if($this->hasState($name))
  4259. $this->setState($name,$value);
  4260. else
  4261. parent::__set($name,$value);
  4262. }
  4263. public function __isset($name)
  4264. {
  4265. if($this->hasState($name))
  4266. return $this->getState($name)!==null;
  4267. else
  4268. return parent::__isset($name);
  4269. }
  4270. public function __unset($name)
  4271. {
  4272. if($this->hasState($name))
  4273. $this->setState($name,null);
  4274. else
  4275. parent::__unset($name);
  4276. }
  4277. public function init()
  4278. {
  4279. parent::init();
  4280. Yii::app()->getSession()->open();
  4281. if($this->getIsGuest() && $this->allowAutoLogin)
  4282. $this->restoreFromCookie();
  4283. elseif($this->autoRenewCookie && $this->allowAutoLogin)
  4284. $this->renewCookie();
  4285. if($this->autoUpdateFlash)
  4286. $this->updateFlash();
  4287. $this->updateAuthStatus();
  4288. }
  4289. public function login($identity,$duration=0)
  4290. {
  4291. $id=$identity->getId();
  4292. $states=$identity->getPersistentStates();
  4293. if($this->beforeLogin($id,$states,false))
  4294. {
  4295. $this->changeIdentity($id,$identity->getName(),$states);
  4296. if($duration>0)
  4297. {
  4298. if($this->allowAutoLogin)
  4299. $this->saveToCookie($duration);
  4300. else
  4301. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  4302. array('{class}'=>get_class($this))));
  4303. }
  4304. if ($this->absoluteAuthTimeout)
  4305. $this->setState(self::AUTH_ABSOLUTE_TIMEOUT_VAR, time()+$this->absoluteAuthTimeout);
  4306. $this->afterLogin(false);
  4307. }
  4308. return !$this->getIsGuest();
  4309. }
  4310. public function logout($destroySession=true)
  4311. {
  4312. if($this->beforeLogout())
  4313. {
  4314. if($this->allowAutoLogin)
  4315. {
  4316. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  4317. if($this->identityCookie!==null)
  4318. {
  4319. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4320. $cookie->value=null;
  4321. $cookie->expire=0;
  4322. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  4323. }
  4324. }
  4325. if($destroySession)
  4326. Yii::app()->getSession()->destroy();
  4327. else
  4328. $this->clearStates();
  4329. $this->_access=array();
  4330. $this->afterLogout();
  4331. }
  4332. }
  4333. public function getIsGuest()
  4334. {
  4335. return $this->getState('__id')===null;
  4336. }
  4337. public function getId()
  4338. {
  4339. return $this->getState('__id');
  4340. }
  4341. public function setId($value)
  4342. {
  4343. $this->setState('__id',$value);
  4344. }
  4345. public function getName()
  4346. {
  4347. if(($name=$this->getState('__name'))!==null)
  4348. return $name;
  4349. else
  4350. return $this->guestName;
  4351. }
  4352. public function setName($value)
  4353. {
  4354. $this->setState('__name',$value);
  4355. }
  4356. public function getReturnUrl($defaultUrl=null)
  4357. {
  4358. if($defaultUrl===null)
  4359. {
  4360. $defaultReturnUrl=Yii::app()->getUrlManager()->showScriptName ? Yii::app()->getRequest()->getScriptUrl() : Yii::app()->getRequest()->getBaseUrl().'/';
  4361. }
  4362. else
  4363. {
  4364. $defaultReturnUrl=CHtml::normalizeUrl($defaultUrl);
  4365. }
  4366. return $this->getState('__returnUrl',$defaultReturnUrl);
  4367. }
  4368. public function setReturnUrl($value)
  4369. {
  4370. $this->setState('__returnUrl',$value);
  4371. }
  4372. public function loginRequired()
  4373. {
  4374. $app=Yii::app();
  4375. $request=$app->getRequest();
  4376. if(!$request->getIsAjaxRequest())
  4377. {
  4378. $this->setReturnUrl($request->getUrl());
  4379. if(($url=$this->loginUrl)!==null)
  4380. {
  4381. if(is_array($url))
  4382. {
  4383. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  4384. $url=$app->createUrl($route,array_splice($url,1));
  4385. }
  4386. $request->redirect($url);
  4387. }
  4388. }
  4389. elseif(isset($this->loginRequiredAjaxResponse))
  4390. {
  4391. echo $this->loginRequiredAjaxResponse;
  4392. Yii::app()->end();
  4393. }
  4394. throw new CHttpException(403,Yii::t('yii','Login Required'));
  4395. }
  4396. protected function beforeLogin($id,$states,$fromCookie)
  4397. {
  4398. return true;
  4399. }
  4400. protected function afterLogin($fromCookie)
  4401. {
  4402. }
  4403. protected function beforeLogout()
  4404. {
  4405. return true;
  4406. }
  4407. protected function afterLogout()
  4408. {
  4409. }
  4410. protected function restoreFromCookie()
  4411. {
  4412. $app=Yii::app();
  4413. $request=$app->getRequest();
  4414. $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  4415. if($cookie && !empty($cookie->value) && is_string($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  4416. {
  4417. $data=@unserialize($data);
  4418. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4419. {
  4420. list($id,$name,$duration,$states)=$data;
  4421. if($this->beforeLogin($id,$states,true))
  4422. {
  4423. $this->changeIdentity($id,$name,$states);
  4424. if($this->autoRenewCookie)
  4425. {
  4426. $this->saveToCookie($duration);
  4427. }
  4428. $this->afterLogin(true);
  4429. }
  4430. }
  4431. }
  4432. }
  4433. protected function renewCookie()
  4434. {
  4435. $request=Yii::app()->getRequest();
  4436. $cookies=$request->getCookies();
  4437. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  4438. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  4439. {
  4440. $data=@unserialize($data);
  4441. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4442. {
  4443. $this->saveToCookie($data[2]);
  4444. }
  4445. }
  4446. }
  4447. protected function saveToCookie($duration)
  4448. {
  4449. $app=Yii::app();
  4450. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4451. $cookie->expire=time()+$duration;
  4452. $data=array(
  4453. $this->getId(),
  4454. $this->getName(),
  4455. $duration,
  4456. $this->saveIdentityStates(),
  4457. );
  4458. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  4459. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  4460. }
  4461. protected function createIdentityCookie($name)
  4462. {
  4463. $cookie=new CHttpCookie($name,'');
  4464. if(is_array($this->identityCookie))
  4465. {
  4466. foreach($this->identityCookie as $name=>$value)
  4467. $cookie->$name=$value;
  4468. }
  4469. return $cookie;
  4470. }
  4471. public function getStateKeyPrefix()
  4472. {
  4473. if($this->_keyPrefix!==null)
  4474. return $this->_keyPrefix;
  4475. else
  4476. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  4477. }
  4478. public function setStateKeyPrefix($value)
  4479. {
  4480. $this->_keyPrefix=$value;
  4481. }
  4482. public function getState($key,$defaultValue=null)
  4483. {
  4484. $key=$this->getStateKeyPrefix().$key;
  4485. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4486. }
  4487. public function setState($key,$value,$defaultValue=null)
  4488. {
  4489. $key=$this->getStateKeyPrefix().$key;
  4490. if($value===$defaultValue)
  4491. unset($_SESSION[$key]);
  4492. else
  4493. $_SESSION[$key]=$value;
  4494. }
  4495. public function hasState($key)
  4496. {
  4497. $key=$this->getStateKeyPrefix().$key;
  4498. return isset($_SESSION[$key]);
  4499. }
  4500. public function clearStates()
  4501. {
  4502. $keys=array_keys($_SESSION);
  4503. $prefix=$this->getStateKeyPrefix();
  4504. $n=strlen($prefix);
  4505. foreach($keys as $key)
  4506. {
  4507. if(!strncmp($key,$prefix,$n))
  4508. unset($_SESSION[$key]);
  4509. }
  4510. }
  4511. public function getFlashes($delete=true)
  4512. {
  4513. $flashes=array();
  4514. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  4515. $keys=array_keys($_SESSION);
  4516. $n=strlen($prefix);
  4517. foreach($keys as $key)
  4518. {
  4519. if(!strncmp($key,$prefix,$n))
  4520. {
  4521. $flashes[substr($key,$n)]=$_SESSION[$key];
  4522. if($delete)
  4523. unset($_SESSION[$key]);
  4524. }
  4525. }
  4526. if($delete)
  4527. $this->setState(self::FLASH_COUNTERS,array());
  4528. return $flashes;
  4529. }
  4530. public function getFlash($key,$defaultValue=null,$delete=true)
  4531. {
  4532. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4533. if($delete)
  4534. $this->setFlash($key,null);
  4535. return $value;
  4536. }
  4537. public function setFlash($key,$value,$defaultValue=null)
  4538. {
  4539. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4540. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4541. if($value===$defaultValue)
  4542. unset($counters[$key]);
  4543. else
  4544. $counters[$key]=0;
  4545. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4546. }
  4547. public function hasFlash($key)
  4548. {
  4549. return $this->getFlash($key, null, false)!==null;
  4550. }
  4551. protected function changeIdentity($id,$name,$states)
  4552. {
  4553. Yii::app()->getSession()->regenerateID(true);
  4554. $this->setId($id);
  4555. $this->setName($name);
  4556. $this->loadIdentityStates($states);
  4557. }
  4558. protected function saveIdentityStates()
  4559. {
  4560. $states=array();
  4561. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4562. $states[$name]=$this->getState($name);
  4563. return $states;
  4564. }
  4565. protected function loadIdentityStates($states)
  4566. {
  4567. $names=array();
  4568. if(is_array($states))
  4569. {
  4570. foreach($states as $name=>$value)
  4571. {
  4572. $this->setState($name,$value);
  4573. $names[$name]=true;
  4574. }
  4575. }
  4576. $this->setState(self::STATES_VAR,$names);
  4577. }
  4578. protected function updateFlash()
  4579. {
  4580. $counters=$this->getState(self::FLASH_COUNTERS);
  4581. if(!is_array($counters))
  4582. return;
  4583. foreach($counters as $key=>$count)
  4584. {
  4585. if($count)
  4586. {
  4587. unset($counters[$key]);
  4588. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4589. }
  4590. else
  4591. $counters[$key]++;
  4592. }
  4593. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4594. }
  4595. protected function updateAuthStatus()
  4596. {
  4597. if(($this->authTimeout!==null || $this->absoluteAuthTimeout!==null) && !$this->getIsGuest())
  4598. {
  4599. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4600. $expiresAbsolute=$this->getState(self::AUTH_ABSOLUTE_TIMEOUT_VAR);
  4601. if ($expires!==null && $expires < time() || $expiresAbsolute!==null && $expiresAbsolute < time())
  4602. $this->logout(false);
  4603. else
  4604. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4605. }
  4606. }
  4607. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4608. {
  4609. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4610. return $this->_access[$operation];
  4611. $access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4612. if($allowCaching && $params===array())
  4613. $this->_access[$operation]=$access;
  4614. return $access;
  4615. }
  4616. }
  4617. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4618. {
  4619. public $autoStart=true;
  4620. private $_frozenData;
  4621. public function init()
  4622. {
  4623. parent::init();
  4624. if($this->autoStart)
  4625. $this->open();
  4626. register_shutdown_function(array($this,'close'));
  4627. }
  4628. public function getUseCustomStorage()
  4629. {
  4630. return false;
  4631. }
  4632. public function open()
  4633. {
  4634. if($this->getUseCustomStorage())
  4635. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4636. @session_start();
  4637. if(YII_DEBUG && session_id()=='')
  4638. {
  4639. $message=Yii::t('yii','Failed to start session.');
  4640. if(function_exists('error_get_last'))
  4641. {
  4642. $error=error_get_last();
  4643. if(isset($error['message']))
  4644. $message=$error['message'];
  4645. }
  4646. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4647. }
  4648. }
  4649. public function close()
  4650. {
  4651. if(session_id()!=='')
  4652. @session_write_close();
  4653. }
  4654. public function destroy()
  4655. {
  4656. if(session_id()!=='')
  4657. {
  4658. @session_unset();
  4659. @session_destroy();
  4660. }
  4661. }
  4662. public function getIsStarted()
  4663. {
  4664. if(function_exists('session_status'))
  4665. return session_status()===PHP_SESSION_ACTIVE;
  4666. return session_id()!=='';
  4667. }
  4668. public function getSessionID()
  4669. {
  4670. return session_id();
  4671. }
  4672. public function setSessionID($value)
  4673. {
  4674. session_id($value);
  4675. }
  4676. public function regenerateID($deleteOldSession=false)
  4677. {
  4678. if($this->getIsStarted())
  4679. session_regenerate_id($deleteOldSession);
  4680. }
  4681. public function getSessionName()
  4682. {
  4683. return session_name();
  4684. }
  4685. public function setSessionName($value)
  4686. {
  4687. session_name($value);
  4688. }
  4689. public function getSavePath()
  4690. {
  4691. return session_save_path();
  4692. }
  4693. public function setSavePath($value)
  4694. {
  4695. if(is_dir($value))
  4696. session_save_path($value);
  4697. else
  4698. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4699. array('{path}'=>$value)));
  4700. }
  4701. public function getCookieParams()
  4702. {
  4703. return session_get_cookie_params();
  4704. }
  4705. public function setCookieParams($value)
  4706. {
  4707. $data=session_get_cookie_params();
  4708. extract($data);
  4709. extract($value);
  4710. $this->freeze();
  4711. if(isset($httponly) && isset($samesite))
  4712. {
  4713. if(version_compare(PHP_VERSION,'7.3.0','>='))
  4714. session_set_cookie_params(array('lifetime'=>$lifetime,'path'=>$path,'domain'=>$domain,'secure'=>$secure,'httponly'=>$httponly,'samesite'=>$samesite));
  4715. else
  4716. {
  4717. // Work around for setting sameSite cookie prior PHP 7.3
  4718. // https://stackoverflow.com/questions/39750906/php-setcookie-samesite-strict/46971326#46971326
  4719. $path .= '; samesite=' . $samesite;
  4720. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4721. }
  4722. }
  4723. else if(isset($httponly))
  4724. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4725. else
  4726. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4727. $this->unfreeze();
  4728. }
  4729. public function getCookieMode()
  4730. {
  4731. if(ini_get('session.use_cookies')==='0')
  4732. return 'none';
  4733. elseif(ini_get('session.use_only_cookies')==='0')
  4734. return 'allow';
  4735. else
  4736. return 'only';
  4737. }
  4738. public function setCookieMode($value)
  4739. {
  4740. if($value==='none')
  4741. {
  4742. $this->freeze();
  4743. ini_set('session.use_cookies','0');
  4744. ini_set('session.use_only_cookies','0');
  4745. $this->unfreeze();
  4746. }
  4747. elseif($value==='allow')
  4748. {
  4749. $this->freeze();
  4750. ini_set('session.use_cookies','1');
  4751. ini_set('session.use_only_cookies','0');
  4752. $this->unfreeze();
  4753. }
  4754. elseif($value==='only')
  4755. {
  4756. $this->freeze();
  4757. ini_set('session.use_cookies','1');
  4758. ini_set('session.use_only_cookies','1');
  4759. $this->unfreeze();
  4760. }
  4761. else
  4762. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4763. }
  4764. public function getGCProbability()
  4765. {
  4766. return (float)(ini_get('session.gc_probability')/ini_get('session.gc_divisor')*100);
  4767. }
  4768. public function setGCProbability($value)
  4769. {
  4770. if($value>=0 && $value<=100)
  4771. {
  4772. $this->freeze();
  4773. // percent * 21474837 / 2147483647 ≈ percent * 0.01
  4774. ini_set('session.gc_probability',floor($value*21474836.47));
  4775. ini_set('session.gc_divisor',2147483647);
  4776. $this->unfreeze();
  4777. }
  4778. else
  4779. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be a float between 0 and 100.',
  4780. array('{value}'=>$value)));
  4781. }
  4782. public function getUseTransparentSessionID()
  4783. {
  4784. return ini_get('session.use_trans_sid')==1;
  4785. }
  4786. public function setUseTransparentSessionID($value)
  4787. {
  4788. $this->freeze();
  4789. ini_set('session.use_trans_sid',$value?'1':'0');
  4790. $this->unfreeze();
  4791. }
  4792. public function getTimeout()
  4793. {
  4794. return (int)ini_get('session.gc_maxlifetime');
  4795. }
  4796. public function setTimeout($value)
  4797. {
  4798. $this->freeze();
  4799. ini_set('session.gc_maxlifetime',$value);
  4800. $this->unfreeze();
  4801. }
  4802. public function openSession($savePath,$sessionName)
  4803. {
  4804. return true;
  4805. }
  4806. public function closeSession()
  4807. {
  4808. return true;
  4809. }
  4810. public function readSession($id)
  4811. {
  4812. return '';
  4813. }
  4814. public function writeSession($id,$data)
  4815. {
  4816. return true;
  4817. }
  4818. public function destroySession($id)
  4819. {
  4820. return true;
  4821. }
  4822. public function gcSession($maxLifetime)
  4823. {
  4824. return true;
  4825. }
  4826. //------ The following methods enable CHttpSession to be CMap-like -----
  4827. public function getIterator()
  4828. {
  4829. return new CHttpSessionIterator;
  4830. }
  4831. public function getCount()
  4832. {
  4833. return count($_SESSION);
  4834. }
  4835. public function count()
  4836. {
  4837. return $this->getCount();
  4838. }
  4839. public function getKeys()
  4840. {
  4841. return array_keys($_SESSION);
  4842. }
  4843. public function get($key,$defaultValue=null)
  4844. {
  4845. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4846. }
  4847. public function itemAt($key)
  4848. {
  4849. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4850. }
  4851. public function add($key,$value)
  4852. {
  4853. $_SESSION[$key]=$value;
  4854. }
  4855. public function remove($key)
  4856. {
  4857. if(isset($_SESSION[$key]))
  4858. {
  4859. $value=$_SESSION[$key];
  4860. unset($_SESSION[$key]);
  4861. return $value;
  4862. }
  4863. else
  4864. return null;
  4865. }
  4866. public function clear()
  4867. {
  4868. foreach(array_keys($_SESSION) as $key)
  4869. unset($_SESSION[$key]);
  4870. }
  4871. public function contains($key)
  4872. {
  4873. return isset($_SESSION[$key]);
  4874. }
  4875. public function toArray()
  4876. {
  4877. return $_SESSION;
  4878. }
  4879. public function offsetExists($offset)
  4880. {
  4881. return isset($_SESSION[$offset]);
  4882. }
  4883. public function offsetGet($offset)
  4884. {
  4885. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4886. }
  4887. public function offsetSet($offset,$item)
  4888. {
  4889. $_SESSION[$offset]=$item;
  4890. }
  4891. public function offsetUnset($offset)
  4892. {
  4893. unset($_SESSION[$offset]);
  4894. }
  4895. protected function freeze()
  4896. {
  4897. if (isset($_SESSION) && $this->getIsStarted())
  4898. {
  4899. $this->_frozenData = $_SESSION;
  4900. $this->close();
  4901. }
  4902. }
  4903. protected function unfreeze()
  4904. {
  4905. if ($this->_frozenData !== null)
  4906. {
  4907. @session_start();
  4908. $_SESSION = $this->_frozenData;
  4909. $this->_frozenData = null;
  4910. }
  4911. }
  4912. public function setCacheLimiter($cacheLimiter)
  4913. {
  4914. $this->freeze();
  4915. session_cache_limiter($cacheLimiter);
  4916. $this->unfreeze();
  4917. }
  4918. }
  4919. class CHtml
  4920. {
  4921. const ID_PREFIX='yt';
  4922. public static $errorSummaryCss='errorSummary';
  4923. public static $errorMessageCss='errorMessage';
  4924. public static $errorCss='error';
  4925. public static $errorContainerTag='div';
  4926. public static $requiredCss='required';
  4927. public static $beforeRequiredLabel='';
  4928. public static $afterRequiredLabel=' <span class="required">*</span>';
  4929. public static $count=0;
  4930. public static $liveEvents=true;
  4931. public static $closeSingleTags=true;
  4932. public static $setScriptType=true;
  4933. public static $cdataScriptAndStyleContents=true;
  4934. public static $renderSpecialAttributesValue=true;
  4935. private static $_modelNameConverter;
  4936. public static function encode($text)
  4937. {
  4938. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4939. }
  4940. public static function decode($text)
  4941. {
  4942. return htmlspecialchars_decode($text,ENT_QUOTES);
  4943. }
  4944. public static function encodeArray($data)
  4945. {
  4946. $d=array();
  4947. foreach($data as $key=>$value)
  4948. {
  4949. if(is_string($key))
  4950. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4951. if(is_string($value))
  4952. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4953. elseif(is_array($value))
  4954. $value=self::encodeArray($value);
  4955. $d[$key]=$value;
  4956. }
  4957. return $d;
  4958. }
  4959. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4960. {
  4961. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4962. if($content===false)
  4963. return $closeTag && self::$closeSingleTags ? $html.' />' : $html.'>';
  4964. else
  4965. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4966. }
  4967. public static function openTag($tag,$htmlOptions=array())
  4968. {
  4969. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4970. }
  4971. public static function closeTag($tag)
  4972. {
  4973. return '</'.$tag.'>';
  4974. }
  4975. public static function cdata($text)
  4976. {
  4977. return '<![CDATA[' . $text . ']]>';
  4978. }
  4979. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4980. {
  4981. if($name!==null)
  4982. $options['name']=$name;
  4983. if($httpEquiv!==null)
  4984. $options['http-equiv']=$httpEquiv;
  4985. $options['content']=$content;
  4986. return self::tag('meta',$options);
  4987. }
  4988. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4989. {
  4990. if($relation!==null)
  4991. $options['rel']=$relation;
  4992. if($type!==null)
  4993. $options['type']=$type;
  4994. if($href!==null)
  4995. $options['href']=$href;
  4996. if($media!==null)
  4997. $options['media']=$media;
  4998. return self::tag('link',$options);
  4999. }
  5000. public static function css($text,$media='')
  5001. {
  5002. if($media!=='')
  5003. $media=' media="'.$media.'"';
  5004. if(self::$cdataScriptAndStyleContents)
  5005. $text="/*<![CDATA[*/\n{$text}\n/*]]>*/";
  5006. return "<style type=\"text/css\"{$media}>\n{$text}\n</style>";
  5007. }
  5008. public static function refresh($seconds,$url='')
  5009. {
  5010. $content="$seconds";
  5011. if($url!=='')
  5012. $content.=';url='.self::normalizeUrl($url);
  5013. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  5014. }
  5015. public static function cssFile($url,$media='')
  5016. {
  5017. return CHtml::linkTag('stylesheet','text/css',$url,$media!=='' ? $media : null);
  5018. }
  5019. public static function script($text,array $htmlOptions=array())
  5020. {
  5021. $defaultHtmlOptions=array();
  5022. if(self::$setScriptType)
  5023. $defaultHtmlOptions['type']='text/javascript';
  5024. $htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
  5025. if(self::$cdataScriptAndStyleContents)
  5026. $text="/*<![CDATA[*/\n{$text}\n/*]]>*/";
  5027. return self::tag('script',$htmlOptions,"\n{$text}\n");
  5028. }
  5029. public static function scriptFile($url,array $htmlOptions=array())
  5030. {
  5031. $defaultHtmlOptions=array();
  5032. if(self::$setScriptType)
  5033. $defaultHtmlOptions['type']='text/javascript';
  5034. $defaultHtmlOptions['src']=$url;
  5035. $htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
  5036. return self::tag('script',$htmlOptions,'');
  5037. }
  5038. public static function form($action='',$method='post',$htmlOptions=array())
  5039. {
  5040. return self::beginForm($action,$method,$htmlOptions);
  5041. }
  5042. public static function beginForm($action='',$method='post',$htmlOptions=array())
  5043. {
  5044. $htmlOptions['action']=$url=self::normalizeUrl($action);
  5045. if(strcasecmp($method,'get')!==0 && strcasecmp($method,'post')!==0)
  5046. {
  5047. $customMethod=$method;
  5048. $method='post';
  5049. }
  5050. else
  5051. $customMethod=false;
  5052. $htmlOptions['method']=$method;
  5053. $form=self::tag('form',$htmlOptions,false,false);
  5054. $hiddens=array();
  5055. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  5056. {
  5057. foreach(explode('&',substr(preg_replace('/#.+$/','',$url),$pos+1)) as $pair)
  5058. {
  5059. if(($pos=strpos($pair,'='))!==false)
  5060. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  5061. else
  5062. $hiddens[]=self::hiddenField(urldecode($pair),'',array('id'=>false));
  5063. }
  5064. }
  5065. $request=Yii::app()->request;
  5066. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  5067. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  5068. if($customMethod!==false)
  5069. $hiddens[]=self::hiddenField('_method',$customMethod);
  5070. if($hiddens!==array())
  5071. $form.="\n".implode("\n",$hiddens);
  5072. return $form;
  5073. }
  5074. public static function endForm()
  5075. {
  5076. return '</form>';
  5077. }
  5078. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  5079. {
  5080. return self::form($action,$method,$htmlOptions)."\n".
  5081. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  5082. }
  5083. public static function pageStateField($value)
  5084. {
  5085. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  5086. }
  5087. public static function link($text,$url='#',$htmlOptions=array())
  5088. {
  5089. if($url!=='')
  5090. $htmlOptions['href']=self::normalizeUrl($url);
  5091. self::clientChange('click',$htmlOptions);
  5092. return self::tag('a',$htmlOptions,$text);
  5093. }
  5094. public static function mailto($text,$email='',$htmlOptions=array())
  5095. {
  5096. if($email==='')
  5097. $email=$text;
  5098. return self::link($text,'mailto:'.$email,$htmlOptions);
  5099. }
  5100. public static function image($src,$alt='',$htmlOptions=array())
  5101. {
  5102. $htmlOptions['src']=$src;
  5103. $htmlOptions['alt']=$alt;
  5104. return self::tag('img',$htmlOptions);
  5105. }
  5106. public static function button($label='button',$htmlOptions=array())
  5107. {
  5108. if(!isset($htmlOptions['name']))
  5109. {
  5110. if(!array_key_exists('name',$htmlOptions))
  5111. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  5112. }
  5113. if(!isset($htmlOptions['type']))
  5114. $htmlOptions['type']='button';
  5115. if(!isset($htmlOptions['value']) && $htmlOptions['type']!='image')
  5116. $htmlOptions['value']=$label;
  5117. self::clientChange('click',$htmlOptions);
  5118. return self::tag('input',$htmlOptions);
  5119. }
  5120. public static function htmlButton($label='button',$htmlOptions=array())
  5121. {
  5122. if(!isset($htmlOptions['name']))
  5123. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  5124. if(!isset($htmlOptions['type']))
  5125. $htmlOptions['type']='button';
  5126. self::clientChange('click',$htmlOptions);
  5127. return self::tag('button',$htmlOptions,$label);
  5128. }
  5129. public static function submitButton($label='submit',$htmlOptions=array())
  5130. {
  5131. $htmlOptions['type']='submit';
  5132. return self::button($label,$htmlOptions);
  5133. }
  5134. public static function resetButton($label='reset',$htmlOptions=array())
  5135. {
  5136. $htmlOptions['type']='reset';
  5137. return self::button($label,$htmlOptions);
  5138. }
  5139. public static function imageButton($src,$htmlOptions=array())
  5140. {
  5141. $htmlOptions['src']=$src;
  5142. $htmlOptions['type']='image';
  5143. return self::button('submit',$htmlOptions);
  5144. }
  5145. public static function linkButton($label='submit',$htmlOptions=array())
  5146. {
  5147. if(!isset($htmlOptions['submit']))
  5148. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  5149. return self::link($label,'#',$htmlOptions);
  5150. }
  5151. public static function label($label,$for,$htmlOptions=array())
  5152. {
  5153. if($for===false)
  5154. unset($htmlOptions['for']);
  5155. else
  5156. $htmlOptions['for']=$for;
  5157. if(isset($htmlOptions['required']))
  5158. {
  5159. if($htmlOptions['required'])
  5160. {
  5161. if(isset($htmlOptions['class']))
  5162. $htmlOptions['class'].=' '.self::$requiredCss;
  5163. else
  5164. $htmlOptions['class']=self::$requiredCss;
  5165. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  5166. }
  5167. unset($htmlOptions['required']);
  5168. }
  5169. return self::tag('label',$htmlOptions,$label);
  5170. }
  5171. public static function colorField($name,$value='',$htmlOptions=array())
  5172. {
  5173. self::clientChange('change',$htmlOptions);
  5174. return self::inputField('color',$name,$value,$htmlOptions);
  5175. }
  5176. public static function textField($name,$value='',$htmlOptions=array())
  5177. {
  5178. self::clientChange('change',$htmlOptions);
  5179. return self::inputField('text',$name,$value,$htmlOptions);
  5180. }
  5181. public static function searchField($name,$value='',$htmlOptions=array())
  5182. {
  5183. self::clientChange('change',$htmlOptions);
  5184. return self::inputField('search',$name,$value,$htmlOptions);
  5185. }
  5186. public static function numberField($name,$value='',$htmlOptions=array())
  5187. {
  5188. self::clientChange('change',$htmlOptions);
  5189. return self::inputField('number',$name,$value,$htmlOptions);
  5190. }
  5191. public static function rangeField($name,$value='',$htmlOptions=array())
  5192. {
  5193. self::clientChange('change',$htmlOptions);
  5194. return self::inputField('range',$name,$value,$htmlOptions);
  5195. }
  5196. public static function dateField($name,$value='',$htmlOptions=array())
  5197. {
  5198. self::clientChange('change',$htmlOptions);
  5199. return self::inputField('date',$name,$value,$htmlOptions);
  5200. }
  5201. public static function timeField($name,$value='',$htmlOptions=array())
  5202. {
  5203. self::clientChange('change',$htmlOptions);
  5204. return self::inputField('time',$name,$value,$htmlOptions);
  5205. }
  5206. public static function dateTimeField($name,$value='',$htmlOptions=array())
  5207. {
  5208. self::clientChange('change',$htmlOptions);
  5209. return self::inputField('datetime',$name,$value,$htmlOptions);
  5210. }
  5211. public static function dateTimeLocalField($name,$value='',$htmlOptions=array())
  5212. {
  5213. self::clientChange('change',$htmlOptions);
  5214. return self::inputField('datetime-local',$name,$value,$htmlOptions);
  5215. }
  5216. public static function weekField($name,$value='',$htmlOptions=array())
  5217. {
  5218. self::clientChange('change',$htmlOptions);
  5219. return self::inputField('week',$name,$value,$htmlOptions);
  5220. }
  5221. public static function emailField($name,$value='',$htmlOptions=array())
  5222. {
  5223. self::clientChange('change',$htmlOptions);
  5224. return self::inputField('email',$name,$value,$htmlOptions);
  5225. }
  5226. public static function telField($name,$value='',$htmlOptions=array())
  5227. {
  5228. self::clientChange('change',$htmlOptions);
  5229. return self::inputField('tel',$name,$value,$htmlOptions);
  5230. }
  5231. public static function urlField($name,$value='',$htmlOptions=array())
  5232. {
  5233. self::clientChange('change',$htmlOptions);
  5234. return self::inputField('url',$name,$value,$htmlOptions);
  5235. }
  5236. public static function hiddenField($name,$value='',$htmlOptions=array())
  5237. {
  5238. return self::inputField('hidden',$name,$value,$htmlOptions);
  5239. }
  5240. public static function passwordField($name,$value='',$htmlOptions=array())
  5241. {
  5242. self::clientChange('change',$htmlOptions);
  5243. return self::inputField('password',$name,$value,$htmlOptions);
  5244. }
  5245. public static function fileField($name,$value='',$htmlOptions=array())
  5246. {
  5247. return self::inputField('file',$name,$value,$htmlOptions);
  5248. }
  5249. public static function textArea($name,$value='',$htmlOptions=array())
  5250. {
  5251. $htmlOptions['name']=$name;
  5252. if(!isset($htmlOptions['id']))
  5253. $htmlOptions['id']=self::getIdByName($name);
  5254. elseif($htmlOptions['id']===false)
  5255. unset($htmlOptions['id']);
  5256. self::clientChange('change',$htmlOptions);
  5257. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  5258. }
  5259. public static function radioButton($name,$checked=false,$htmlOptions=array())
  5260. {
  5261. if($checked)
  5262. $htmlOptions['checked']='checked';
  5263. else
  5264. unset($htmlOptions['checked']);
  5265. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  5266. self::clientChange('click',$htmlOptions);
  5267. if(array_key_exists('uncheckValue',$htmlOptions))
  5268. {
  5269. $uncheck=$htmlOptions['uncheckValue'];
  5270. unset($htmlOptions['uncheckValue']);
  5271. }
  5272. else
  5273. $uncheck=null;
  5274. if($uncheck!==null)
  5275. {
  5276. // add a hidden field so that if the radio button is not selected, it still submits a value
  5277. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  5278. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  5279. else
  5280. $uncheckOptions=array('id'=>false);
  5281. if(!empty($htmlOptions['disabled']))
  5282. $uncheckOptions['disabled']=$htmlOptions['disabled'];
  5283. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  5284. }
  5285. else
  5286. $hidden='';
  5287. // add a hidden field so that if the radio button is not selected, it still submits a value
  5288. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  5289. }
  5290. public static function checkBox($name,$checked=false,$htmlOptions=array())
  5291. {
  5292. if($checked)
  5293. $htmlOptions['checked']='checked';
  5294. else
  5295. unset($htmlOptions['checked']);
  5296. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  5297. self::clientChange('click',$htmlOptions);
  5298. if(array_key_exists('uncheckValue',$htmlOptions))
  5299. {
  5300. $uncheck=$htmlOptions['uncheckValue'];
  5301. unset($htmlOptions['uncheckValue']);
  5302. }
  5303. else
  5304. $uncheck=null;
  5305. if($uncheck!==null)
  5306. {
  5307. // add a hidden field so that if the check box is not checked, it still submits a value
  5308. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  5309. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  5310. else
  5311. $uncheckOptions=array('id'=>false);
  5312. if(!empty($htmlOptions['disabled']))
  5313. $uncheckOptions['disabled']=$htmlOptions['disabled'];
  5314. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  5315. }
  5316. else
  5317. $hidden='';
  5318. // add a hidden field so that if the check box is not checked, it still submits a value
  5319. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  5320. }
  5321. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  5322. {
  5323. $htmlOptions['name']=$name;
  5324. if(!isset($htmlOptions['id']))
  5325. $htmlOptions['id']=self::getIdByName($name);
  5326. elseif($htmlOptions['id']===false)
  5327. unset($htmlOptions['id']);
  5328. self::clientChange('change',$htmlOptions);
  5329. $options="\n".self::listOptions($select,$data,$htmlOptions);
  5330. $hidden='';
  5331. if(!empty($htmlOptions['multiple']))
  5332. {
  5333. if(substr($htmlOptions['name'],-2)!=='[]')
  5334. $htmlOptions['name'].='[]';
  5335. if(isset($htmlOptions['unselectValue']))
  5336. {
  5337. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5338. if(!empty($htmlOptions['disabled']))
  5339. $hiddenOptions['disabled']=$htmlOptions['disabled'];
  5340. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  5341. unset($htmlOptions['unselectValue']);
  5342. }
  5343. }
  5344. // add a hidden field so that if the option is not selected, it still submits a value
  5345. return $hidden . self::tag('select',$htmlOptions,$options);
  5346. }
  5347. public static function listBox($name,$select,$data,$htmlOptions=array())
  5348. {
  5349. if(!isset($htmlOptions['size']))
  5350. $htmlOptions['size']=4;
  5351. if(!empty($htmlOptions['multiple']))
  5352. {
  5353. if(substr($name,-2)!=='[]')
  5354. $name.='[]';
  5355. }
  5356. return self::dropDownList($name,$select,$data,$htmlOptions);
  5357. }
  5358. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  5359. {
  5360. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  5361. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:self::tag('br');
  5362. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  5363. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  5364. if(substr($name,-2)!=='[]')
  5365. $name.='[]';
  5366. if(isset($htmlOptions['checkAll']))
  5367. {
  5368. $checkAllLabel=$htmlOptions['checkAll'];
  5369. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  5370. }
  5371. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  5372. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  5373. unset($htmlOptions['labelOptions']);
  5374. $items=array();
  5375. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  5376. unset($htmlOptions['baseID']);
  5377. $id=0;
  5378. $checkAll=true;
  5379. foreach($data as $value=>$labelTitle)
  5380. {
  5381. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  5382. $checkAll=$checkAll && $checked;
  5383. $htmlOptions['value']=$value;
  5384. $htmlOptions['id']=$baseID.'_'.$id++;
  5385. $option=self::checkBox($name,$checked,$htmlOptions);
  5386. $beginLabel=self::openTag('label',$labelOptions);
  5387. $label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
  5388. $endLabel=self::closeTag('label');
  5389. $items[]=strtr($template,array(
  5390. '{input}'=>$option,
  5391. '{beginLabel}'=>$beginLabel,
  5392. '{label}'=>$label,
  5393. '{labelTitle}'=>$labelTitle,
  5394. '{endLabel}'=>$endLabel,
  5395. ));
  5396. }
  5397. if(isset($checkAllLabel))
  5398. {
  5399. $htmlOptions['value']=1;
  5400. $htmlOptions['id']=$id=$baseID.'_all';
  5401. $option=self::checkBox($id,$checkAll,$htmlOptions);
  5402. $beginLabel=self::openTag('label',$labelOptions);
  5403. $label=self::label($checkAllLabel,$id,$labelOptions);
  5404. $endLabel=self::closeTag('label');
  5405. $item=strtr($template,array(
  5406. '{input}'=>$option,
  5407. '{beginLabel}'=>$beginLabel,
  5408. '{label}'=>$label,
  5409. '{labelTitle}'=>$checkAllLabel,
  5410. '{endLabel}'=>$endLabel,
  5411. ));
  5412. if($checkAllLast)
  5413. $items[]=$item;
  5414. else
  5415. array_unshift($items,$item);
  5416. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  5417. $js=<<<EOD
  5418. jQuery('#$id').click(function() {
  5419. jQuery("input[name='$name']").prop('checked', this.checked);
  5420. });
  5421. jQuery("input[name='$name']").click(function() {
  5422. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  5423. });
  5424. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  5425. EOD;
  5426. $cs=Yii::app()->getClientScript();
  5427. $cs->registerCoreScript('jquery');
  5428. $cs->registerScript($id,$js);
  5429. }
  5430. if(empty($container))
  5431. return implode($separator,$items);
  5432. else
  5433. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  5434. }
  5435. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  5436. {
  5437. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  5438. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:self::tag('br');
  5439. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  5440. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  5441. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  5442. unset($htmlOptions['labelOptions']);
  5443. if(isset($htmlOptions['empty']))
  5444. {
  5445. if(!is_array($htmlOptions['empty']))
  5446. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5447. $data=CMap::mergeArray($htmlOptions['empty'],$data);
  5448. unset($htmlOptions['empty']);
  5449. }
  5450. $items=array();
  5451. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  5452. unset($htmlOptions['baseID']);
  5453. $id=0;
  5454. foreach($data as $value=>$labelTitle)
  5455. {
  5456. $checked=!strcmp($value,$select);
  5457. $htmlOptions['value']=$value;
  5458. $htmlOptions['id']=$baseID.'_'.$id++;
  5459. $option=self::radioButton($name,$checked,$htmlOptions);
  5460. $beginLabel=self::openTag('label',$labelOptions);
  5461. $label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
  5462. $endLabel=self::closeTag('label');
  5463. $items[]=strtr($template,array(
  5464. '{input}'=>$option,
  5465. '{beginLabel}'=>$beginLabel,
  5466. '{label}'=>$label,
  5467. '{labelTitle}'=>$labelTitle,
  5468. '{endLabel}'=>$endLabel,
  5469. ));
  5470. }
  5471. if(empty($container))
  5472. return implode($separator,$items);
  5473. else
  5474. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  5475. }
  5476. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  5477. {
  5478. if(!isset($htmlOptions['href']))
  5479. $htmlOptions['href']='#';
  5480. $ajaxOptions['url']=$url;
  5481. $htmlOptions['ajax']=$ajaxOptions;
  5482. self::clientChange('click',$htmlOptions);
  5483. return self::tag('a',$htmlOptions,$text);
  5484. }
  5485. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  5486. {
  5487. $ajaxOptions['url']=$url;
  5488. $htmlOptions['ajax']=$ajaxOptions;
  5489. return self::button($label,$htmlOptions);
  5490. }
  5491. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  5492. {
  5493. $ajaxOptions['type']='POST';
  5494. $htmlOptions['type']='submit';
  5495. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  5496. }
  5497. public static function ajax($options)
  5498. {
  5499. Yii::app()->getClientScript()->registerCoreScript('jquery');
  5500. if(!isset($options['url']))
  5501. $options['url']=new CJavaScriptExpression('location.href');
  5502. else
  5503. $options['url']=self::normalizeUrl($options['url']);
  5504. if(!isset($options['cache']))
  5505. $options['cache']=false;
  5506. if(!isset($options['data']) && isset($options['type']))
  5507. $options['data']=new CJavaScriptExpression('jQuery(this).parents("form").serialize()');
  5508. foreach(array('beforeSend','complete','error','success') as $name)
  5509. {
  5510. if(isset($options[$name]) && !($options[$name] instanceof CJavaScriptExpression))
  5511. $options[$name]=new CJavaScriptExpression($options[$name]);
  5512. }
  5513. if(isset($options['update']))
  5514. {
  5515. if(!isset($options['success']))
  5516. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['update'].'").html(html)}');
  5517. unset($options['update']);
  5518. }
  5519. if(isset($options['replace']))
  5520. {
  5521. if(!isset($options['success']))
  5522. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['replace'].'").replaceWith(html)}');
  5523. unset($options['replace']);
  5524. }
  5525. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  5526. }
  5527. public static function asset($path,$hashByName=false)
  5528. {
  5529. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  5530. }
  5531. public static function normalizeUrl($url)
  5532. {
  5533. if(is_array($url))
  5534. {
  5535. if(isset($url[0]))
  5536. {
  5537. if(($c=Yii::app()->getController())!==null)
  5538. $url=$c->createUrl($url[0],array_splice($url,1));
  5539. else
  5540. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  5541. }
  5542. else
  5543. $url='';
  5544. }
  5545. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  5546. }
  5547. protected static function inputField($type,$name,$value,$htmlOptions)
  5548. {
  5549. $htmlOptions['type']=$type;
  5550. $htmlOptions['value']=$value;
  5551. $htmlOptions['name']=$name;
  5552. if(!isset($htmlOptions['id']))
  5553. $htmlOptions['id']=self::getIdByName($name);
  5554. elseif($htmlOptions['id']===false)
  5555. unset($htmlOptions['id']);
  5556. return self::tag('input',$htmlOptions);
  5557. }
  5558. public static function activeLabel($model,$attribute,$htmlOptions=array())
  5559. {
  5560. $inputName=self::resolveName($model,$attribute);
  5561. if(isset($htmlOptions['for']))
  5562. {
  5563. $for=$htmlOptions['for'];
  5564. unset($htmlOptions['for']);
  5565. }
  5566. else
  5567. $for=self::getIdByName($inputName);
  5568. if(isset($htmlOptions['label']))
  5569. {
  5570. if(($label=$htmlOptions['label'])===false)
  5571. return '';
  5572. unset($htmlOptions['label']);
  5573. }
  5574. else
  5575. $label=$model->getAttributeLabel($attribute);
  5576. if($model->hasErrors($attribute))
  5577. self::addErrorCss($htmlOptions);
  5578. return self::label($label,$for,$htmlOptions);
  5579. }
  5580. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  5581. {
  5582. $realAttribute=$attribute;
  5583. self::resolveName($model,$attribute); // strip off square brackets if any
  5584. if (!isset($htmlOptions['required']))
  5585. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  5586. return self::activeLabel($model,$realAttribute,$htmlOptions);
  5587. }
  5588. public static function activeTextField($model,$attribute,$htmlOptions=array())
  5589. {
  5590. self::resolveNameID($model,$attribute,$htmlOptions);
  5591. self::clientChange('change',$htmlOptions);
  5592. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  5593. }
  5594. public static function activeSearchField($model,$attribute,$htmlOptions=array())
  5595. {
  5596. self::resolveNameID($model,$attribute,$htmlOptions);
  5597. self::clientChange('change',$htmlOptions);
  5598. return self::activeInputField('search',$model,$attribute,$htmlOptions);
  5599. }
  5600. public static function activeUrlField($model,$attribute,$htmlOptions=array())
  5601. {
  5602. self::resolveNameID($model,$attribute,$htmlOptions);
  5603. self::clientChange('change',$htmlOptions);
  5604. return self::activeInputField('url',$model,$attribute,$htmlOptions);
  5605. }
  5606. public static function activeEmailField($model,$attribute,$htmlOptions=array())
  5607. {
  5608. self::resolveNameID($model,$attribute,$htmlOptions);
  5609. self::clientChange('change',$htmlOptions);
  5610. return self::activeInputField('email',$model,$attribute,$htmlOptions);
  5611. }
  5612. public static function activeNumberField($model,$attribute,$htmlOptions=array())
  5613. {
  5614. self::resolveNameID($model,$attribute,$htmlOptions);
  5615. self::clientChange('change',$htmlOptions);
  5616. return self::activeInputField('number',$model,$attribute,$htmlOptions);
  5617. }
  5618. public static function activeRangeField($model,$attribute,$htmlOptions=array())
  5619. {
  5620. self::resolveNameID($model,$attribute,$htmlOptions);
  5621. self::clientChange('change',$htmlOptions);
  5622. return self::activeInputField('range',$model,$attribute,$htmlOptions);
  5623. }
  5624. public static function activeDateField($model,$attribute,$htmlOptions=array())
  5625. {
  5626. self::resolveNameID($model,$attribute,$htmlOptions);
  5627. self::clientChange('change',$htmlOptions);
  5628. return self::activeInputField('date',$model,$attribute,$htmlOptions);
  5629. }
  5630. public static function activeTimeField($model,$attribute,$htmlOptions=array())
  5631. {
  5632. self::resolveNameID($model,$attribute,$htmlOptions);
  5633. self::clientChange('change',$htmlOptions);
  5634. return self::activeInputField('time',$model,$attribute,$htmlOptions);
  5635. }
  5636. public static function activeDateTimeField($model,$attribute,$htmlOptions=array())
  5637. {
  5638. self::resolveNameID($model,$attribute,$htmlOptions);
  5639. self::clientChange('change',$htmlOptions);
  5640. return self::activeInputField('datetime',$model,$attribute,$htmlOptions);
  5641. }
  5642. public static function activeDateTimeLocalField($model,$attribute,$htmlOptions=array())
  5643. {
  5644. self::resolveNameID($model,$attribute,$htmlOptions);
  5645. self::clientChange('change',$htmlOptions);
  5646. return self::activeInputField('datetime-local',$model,$attribute,$htmlOptions);
  5647. }
  5648. public static function activeWeekField($model,$attribute,$htmlOptions=array())
  5649. {
  5650. self::resolveNameID($model,$attribute,$htmlOptions);
  5651. self::clientChange('change',$htmlOptions);
  5652. return self::activeInputField('week',$model,$attribute,$htmlOptions);
  5653. }
  5654. public static function activeColorField($model,$attribute,$htmlOptions=array())
  5655. {
  5656. self::resolveNameID($model,$attribute,$htmlOptions);
  5657. self::clientChange('change',$htmlOptions);
  5658. return self::activeInputField('color',$model,$attribute,$htmlOptions);
  5659. }
  5660. public static function activeTelField($model,$attribute,$htmlOptions=array())
  5661. {
  5662. self::resolveNameID($model,$attribute,$htmlOptions);
  5663. self::clientChange('change',$htmlOptions);
  5664. return self::activeInputField('tel',$model,$attribute,$htmlOptions);
  5665. }
  5666. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  5667. {
  5668. self::resolveNameID($model,$attribute,$htmlOptions);
  5669. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  5670. }
  5671. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  5672. {
  5673. self::resolveNameID($model,$attribute,$htmlOptions);
  5674. self::clientChange('change',$htmlOptions);
  5675. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  5676. }
  5677. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  5678. {
  5679. self::resolveNameID($model,$attribute,$htmlOptions);
  5680. self::clientChange('change',$htmlOptions);
  5681. if($model->hasErrors($attribute))
  5682. self::addErrorCss($htmlOptions);
  5683. if(isset($htmlOptions['value']))
  5684. {
  5685. $text=$htmlOptions['value'];
  5686. unset($htmlOptions['value']);
  5687. }
  5688. else
  5689. $text=self::resolveValue($model,$attribute);
  5690. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  5691. }
  5692. public static function activeFileField($model,$attribute,$htmlOptions=array())
  5693. {
  5694. self::resolveNameID($model,$attribute,$htmlOptions);
  5695. // add a hidden field so that if a model only has a file field, we can
  5696. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  5697. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5698. if(!empty($htmlOptions['disabled']))
  5699. $hiddenOptions['disabled']=$htmlOptions['disabled'];
  5700. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  5701. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  5702. }
  5703. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  5704. {
  5705. self::resolveNameID($model,$attribute,$htmlOptions);
  5706. if(!isset($htmlOptions['value']))
  5707. $htmlOptions['value']=1;
  5708. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5709. $htmlOptions['checked']='checked';
  5710. self::clientChange('click',$htmlOptions);
  5711. if(array_key_exists('uncheckValue',$htmlOptions))
  5712. {
  5713. $uncheck=$htmlOptions['uncheckValue'];
  5714. unset($htmlOptions['uncheckValue']);
  5715. }
  5716. else
  5717. $uncheck='0';
  5718. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5719. if(!empty($htmlOptions['disabled']))
  5720. $hiddenOptions['disabled']=$htmlOptions['disabled'];
  5721. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5722. // add a hidden field so that if the radio button is not selected, it still submits a value
  5723. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  5724. }
  5725. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  5726. {
  5727. self::resolveNameID($model,$attribute,$htmlOptions);
  5728. if(!isset($htmlOptions['value']))
  5729. $htmlOptions['value']=1;
  5730. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5731. $htmlOptions['checked']='checked';
  5732. self::clientChange('click',$htmlOptions);
  5733. if(array_key_exists('uncheckValue',$htmlOptions))
  5734. {
  5735. $uncheck=$htmlOptions['uncheckValue'];
  5736. unset($htmlOptions['uncheckValue']);
  5737. }
  5738. else
  5739. $uncheck='0';
  5740. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5741. if(!empty($htmlOptions['disabled']))
  5742. $hiddenOptions['disabled']=$htmlOptions['disabled'];
  5743. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5744. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  5745. }
  5746. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  5747. {
  5748. self::resolveNameID($model,$attribute,$htmlOptions);
  5749. $selection=self::resolveValue($model,$attribute);
  5750. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  5751. self::clientChange('change',$htmlOptions);
  5752. if($model->hasErrors($attribute))
  5753. self::addErrorCss($htmlOptions);
  5754. $hidden='';
  5755. if(!empty($htmlOptions['multiple']))
  5756. {
  5757. if(substr($htmlOptions['name'],-2)!=='[]')
  5758. $htmlOptions['name'].='[]';
  5759. if(isset($htmlOptions['unselectValue']))
  5760. {
  5761. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5762. if(!empty($htmlOptions['disabled']))
  5763. $hiddenOptions['disabled']=$htmlOptions['disabled'];
  5764. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  5765. unset($htmlOptions['unselectValue']);
  5766. }
  5767. }
  5768. return $hidden . self::tag('select',$htmlOptions,$options);
  5769. }
  5770. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  5771. {
  5772. if(!isset($htmlOptions['size']))
  5773. $htmlOptions['size']=4;
  5774. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  5775. }
  5776. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  5777. {
  5778. self::resolveNameID($model,$attribute,$htmlOptions);
  5779. $selection=self::resolveValue($model,$attribute);
  5780. if($model->hasErrors($attribute))
  5781. self::addErrorCss($htmlOptions);
  5782. $name=$htmlOptions['name'];
  5783. unset($htmlOptions['name']);
  5784. if(array_key_exists('uncheckValue',$htmlOptions))
  5785. {
  5786. $uncheck=$htmlOptions['uncheckValue'];
  5787. unset($htmlOptions['uncheckValue']);
  5788. }
  5789. else
  5790. $uncheck='';
  5791. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5792. if(!empty($htmlOptions['disabled']))
  5793. $hiddenOptions['disabled']=$htmlOptions['disabled'];
  5794. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5795. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  5796. }
  5797. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  5798. {
  5799. self::resolveNameID($model,$attribute,$htmlOptions);
  5800. $selection=self::resolveValue($model,$attribute);
  5801. if($model->hasErrors($attribute))
  5802. self::addErrorCss($htmlOptions);
  5803. $name=$htmlOptions['name'];
  5804. unset($htmlOptions['name']);
  5805. if(array_key_exists('uncheckValue',$htmlOptions))
  5806. {
  5807. $uncheck=$htmlOptions['uncheckValue'];
  5808. unset($htmlOptions['uncheckValue']);
  5809. }
  5810. else
  5811. $uncheck='';
  5812. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5813. if(!empty($htmlOptions['disabled']))
  5814. $hiddenOptions['disabled']=$htmlOptions['disabled'];
  5815. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5816. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  5817. }
  5818. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  5819. {
  5820. $content='';
  5821. if(!is_array($model))
  5822. $model=array($model);
  5823. if(isset($htmlOptions['firstError']))
  5824. {
  5825. $firstError=$htmlOptions['firstError'];
  5826. unset($htmlOptions['firstError']);
  5827. }
  5828. else
  5829. $firstError=false;
  5830. foreach($model as $m)
  5831. {
  5832. foreach($m->getErrors() as $errors)
  5833. {
  5834. foreach($errors as $error)
  5835. {
  5836. if($error!='')
  5837. {
  5838. if (!isset($htmlOptions['encode']) || $htmlOptions['encode'])
  5839. $error=self::encode($error);
  5840. $content.= '<li>'.$error."</li>\n";
  5841. }
  5842. if($firstError)
  5843. break;
  5844. }
  5845. }
  5846. }
  5847. if($content!=='')
  5848. {
  5849. if($header===null)
  5850. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5851. if(!isset($htmlOptions['class']))
  5852. $htmlOptions['class']=self::$errorSummaryCss;
  5853. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5854. }
  5855. else
  5856. return '';
  5857. }
  5858. public static function error($model,$attribute,$htmlOptions=array())
  5859. {
  5860. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5861. $error=$model->getError($attribute);
  5862. if (!isset($htmlOptions['encode']) || $htmlOptions['encode'])
  5863. $error=self::encode($error);
  5864. if($error!='')
  5865. {
  5866. if(!isset($htmlOptions['class']))
  5867. $htmlOptions['class']=self::$errorMessageCss;
  5868. return self::tag(self::$errorContainerTag,$htmlOptions,$error);
  5869. }
  5870. else
  5871. return '';
  5872. }
  5873. public static function listData($models,$valueField,$textField,$groupField='')
  5874. {
  5875. $listData=array();
  5876. if($groupField==='')
  5877. {
  5878. foreach($models as $model)
  5879. {
  5880. $value=self::value($model,$valueField);
  5881. $text=self::value($model,$textField);
  5882. $listData[$value]=$text;
  5883. }
  5884. }
  5885. else
  5886. {
  5887. foreach($models as $model)
  5888. {
  5889. $group=self::value($model,$groupField);
  5890. $value=self::value($model,$valueField);
  5891. $text=self::value($model,$textField);
  5892. if($group===null)
  5893. $listData[$value]=$text;
  5894. else
  5895. $listData[$group][$value]=$text;
  5896. }
  5897. }
  5898. return $listData;
  5899. }
  5900. public static function value($model,$attribute,$defaultValue=null)
  5901. {
  5902. if(is_scalar($attribute) || $attribute===null)
  5903. foreach(explode('.',$attribute) as $name)
  5904. {
  5905. if(is_object($model))
  5906. {
  5907. if ((version_compare(PHP_VERSION, '7.2.0', '>=')
  5908. && is_numeric($name))
  5909. || !isset($model->$name)
  5910. )
  5911. {
  5912. return $defaultValue;
  5913. }
  5914. else
  5915. {
  5916. $model=$model->$name;
  5917. }
  5918. }
  5919. elseif(is_array($model) && isset($model[$name]))
  5920. $model=$model[$name];
  5921. else
  5922. return $defaultValue;
  5923. }
  5924. else
  5925. return call_user_func($attribute,$model);
  5926. return $model;
  5927. }
  5928. public static function getIdByName($name)
  5929. {
  5930. return str_replace(array('[]','][','[',']',' '),array('','_','_','','_'),$name);
  5931. }
  5932. public static function activeId($model,$attribute)
  5933. {
  5934. return self::getIdByName(self::activeName($model,$attribute));
  5935. }
  5936. public static function modelName($model)
  5937. {
  5938. if(is_callable(self::$_modelNameConverter))
  5939. return call_user_func(self::$_modelNameConverter,$model);
  5940. $className=is_object($model) ? get_class($model) : (string)$model;
  5941. return trim(str_replace('\\','_',$className),'_');
  5942. }
  5943. public static function setModelNameConverter($converter)
  5944. {
  5945. if(is_callable($converter))
  5946. self::$_modelNameConverter=$converter;
  5947. elseif($converter===null)
  5948. self::$_modelNameConverter=null;
  5949. else
  5950. throw new CException(Yii::t('yii','The $converter argument must be a valid callback or null.'));
  5951. }
  5952. public static function activeName($model,$attribute)
  5953. {
  5954. $a=$attribute; // because the attribute name may be changed by resolveName
  5955. return self::resolveName($model,$a);
  5956. }
  5957. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5958. {
  5959. $htmlOptions['type']=$type;
  5960. if($type==='text'||$type==='password'||$type==='color'||$type==='date'||$type==='datetime'||
  5961. $type==='datetime-local'||$type==='email'||$type==='month'||$type==='number'||$type==='range'||
  5962. $type==='search'||$type==='tel'||$type==='time'||$type==='url'||$type==='week')
  5963. {
  5964. if(!isset($htmlOptions['maxlength']))
  5965. {
  5966. foreach($model->getValidators($attribute) as $validator)
  5967. {
  5968. if($validator instanceof CStringValidator && $validator->max!==null)
  5969. {
  5970. $htmlOptions['maxlength']=$validator->max;
  5971. break;
  5972. }
  5973. }
  5974. }
  5975. elseif($htmlOptions['maxlength']===false)
  5976. unset($htmlOptions['maxlength']);
  5977. }
  5978. if($type==='file')
  5979. unset($htmlOptions['value']);
  5980. elseif(!isset($htmlOptions['value']))
  5981. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5982. if($model->hasErrors($attribute))
  5983. self::addErrorCss($htmlOptions);
  5984. return self::tag('input',$htmlOptions);
  5985. }
  5986. public static function listOptions($selection,$listData,&$htmlOptions)
  5987. {
  5988. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5989. $content='';
  5990. if(isset($htmlOptions['prompt']))
  5991. {
  5992. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;','>'=>'&gt;'))."</option>\n";
  5993. unset($htmlOptions['prompt']);
  5994. }
  5995. if(isset($htmlOptions['empty']))
  5996. {
  5997. if(!is_array($htmlOptions['empty']))
  5998. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5999. foreach($htmlOptions['empty'] as $value=>$label)
  6000. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;','>'=>'&gt;'))."</option>\n";
  6001. unset($htmlOptions['empty']);
  6002. }
  6003. if(isset($htmlOptions['options']))
  6004. {
  6005. $options=$htmlOptions['options'];
  6006. unset($htmlOptions['options']);
  6007. }
  6008. else
  6009. $options=array();
  6010. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  6011. if(is_array($selection))
  6012. {
  6013. foreach($selection as $i=>$item)
  6014. {
  6015. if(is_object($item))
  6016. $selection[$i]=$item->$key;
  6017. }
  6018. }
  6019. elseif(is_object($selection))
  6020. $selection=$selection->$key;
  6021. foreach($listData as $key=>$value)
  6022. {
  6023. if(is_array($value))
  6024. {
  6025. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  6026. $dummy=array('options'=>$options);
  6027. if(isset($htmlOptions['encode']))
  6028. $dummy['encode']=$htmlOptions['encode'];
  6029. $content.=self::listOptions($selection,$value,$dummy);
  6030. $content.='</optgroup>'."\n";
  6031. }
  6032. else
  6033. {
  6034. $attributes=array('value'=>(string)$key,'encode'=>!$raw);
  6035. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  6036. $attributes['selected']='selected';
  6037. if(isset($options[$key]))
  6038. $attributes=array_merge($attributes,$options[$key]);
  6039. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  6040. }
  6041. }
  6042. unset($htmlOptions['key']);
  6043. return $content;
  6044. }
  6045. protected static function clientChange($event,&$htmlOptions)
  6046. {
  6047. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  6048. return;
  6049. if(isset($htmlOptions['live']))
  6050. {
  6051. $live=$htmlOptions['live'];
  6052. unset($htmlOptions['live']);
  6053. }
  6054. else
  6055. $live = self::$liveEvents;
  6056. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  6057. $return='return true';
  6058. else
  6059. $return='return false';
  6060. if(isset($htmlOptions['on'.$event]))
  6061. {
  6062. $handler=trim($htmlOptions['on'.$event],';').';';
  6063. unset($htmlOptions['on'.$event]);
  6064. }
  6065. else
  6066. $handler='';
  6067. if(isset($htmlOptions['id']))
  6068. $id=$htmlOptions['id'];
  6069. else
  6070. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  6071. $cs=Yii::app()->getClientScript();
  6072. $cs->registerCoreScript('jquery');
  6073. if(isset($htmlOptions['submit']))
  6074. {
  6075. $cs->registerCoreScript('yii');
  6076. $request=Yii::app()->getRequest();
  6077. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  6078. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  6079. if(isset($htmlOptions['params']))
  6080. $params=CJavaScript::encode($htmlOptions['params']);
  6081. else
  6082. $params='{}';
  6083. if($htmlOptions['submit']!=='')
  6084. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  6085. else
  6086. $url='';
  6087. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  6088. }
  6089. if(isset($htmlOptions['ajax']))
  6090. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  6091. if(isset($htmlOptions['confirm']))
  6092. {
  6093. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  6094. if($handler!=='')
  6095. $handler="if($confirm) {".$handler."} else return false;";
  6096. else
  6097. $handler="return $confirm;";
  6098. }
  6099. if($live)
  6100. $cs->registerScript('Yii.CHtml.#' . $id,"jQuery('body').on('$event','#$id',function(){{$handler}});");
  6101. else
  6102. $cs->registerScript('Yii.CHtml.#' . $id,"jQuery('#$id').on('$event', function(){{$handler}});");
  6103. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  6104. }
  6105. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  6106. {
  6107. if(!isset($htmlOptions['name']))
  6108. $htmlOptions['name']=self::resolveName($model,$attribute);
  6109. if(!isset($htmlOptions['id']))
  6110. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  6111. elseif($htmlOptions['id']===false)
  6112. unset($htmlOptions['id']);
  6113. }
  6114. public static function resolveName($model,&$attribute)
  6115. {
  6116. $modelName=self::modelName($model);
  6117. if(($pos=strpos($attribute,'['))!==false)
  6118. {
  6119. if($pos!==0) // e.g. name[a][b]
  6120. return $modelName.'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  6121. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  6122. {
  6123. $sub=substr($attribute,0,$pos+1);
  6124. $attribute=substr($attribute,$pos+1);
  6125. return $modelName.$sub.'['.$attribute.']';
  6126. }
  6127. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  6128. {
  6129. $name=$modelName.'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  6130. $attribute=$matches[1];
  6131. return $name;
  6132. }
  6133. }
  6134. return $modelName.'['.$attribute.']';
  6135. }
  6136. public static function resolveValue($model,$attribute)
  6137. {
  6138. if(($pos=strpos($attribute,'['))!==false)
  6139. {
  6140. if($pos===0) // [a]name[b][c], should ignore [a]
  6141. {
  6142. if(preg_match('/\](\w+(\[.+)?)/',$attribute,$matches))
  6143. $attribute=$matches[1]; // we get: name[b][c]
  6144. if(($pos=strpos($attribute,'['))===false)
  6145. return $model->$attribute;
  6146. }
  6147. $name=substr($attribute,0,$pos);
  6148. $value=$model->$name;
  6149. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  6150. {
  6151. if((is_array($value) || $value instanceof ArrayAccess) && isset($value[$id]))
  6152. $value=$value[$id];
  6153. else
  6154. return null;
  6155. }
  6156. return $value;
  6157. }
  6158. else
  6159. return $model->$attribute;
  6160. }
  6161. protected static function addErrorCss(&$htmlOptions)
  6162. {
  6163. if(empty(self::$errorCss))
  6164. return;
  6165. if(isset($htmlOptions['class']))
  6166. $htmlOptions['class'].=' '.self::$errorCss;
  6167. else
  6168. $htmlOptions['class']=self::$errorCss;
  6169. }
  6170. public static function renderAttributes($htmlOptions)
  6171. {
  6172. static $specialAttributes=array(
  6173. 'autofocus'=>1,
  6174. 'autoplay'=>1,
  6175. 'async'=>1,
  6176. 'checked'=>1,
  6177. 'controls'=>1,
  6178. 'declare'=>1,
  6179. 'default'=>1,
  6180. 'defer'=>1,
  6181. 'disabled'=>1,
  6182. 'formnovalidate'=>1,
  6183. 'hidden'=>1,
  6184. 'ismap'=>1,
  6185. 'itemscope'=>1,
  6186. 'loop'=>1,
  6187. 'multiple'=>1,
  6188. 'muted'=>1,
  6189. 'nohref'=>1,
  6190. 'noresize'=>1,
  6191. 'novalidate'=>1,
  6192. 'open'=>1,
  6193. 'readonly'=>1,
  6194. 'required'=>1,
  6195. 'reversed'=>1,
  6196. 'scoped'=>1,
  6197. 'seamless'=>1,
  6198. 'selected'=>1,
  6199. 'typemustmatch'=>1,
  6200. );
  6201. if($htmlOptions===array())
  6202. return '';
  6203. $html='';
  6204. if(isset($htmlOptions['encode']))
  6205. {
  6206. $raw=!$htmlOptions['encode'];
  6207. unset($htmlOptions['encode']);
  6208. }
  6209. else
  6210. $raw=false;
  6211. foreach($htmlOptions as $name=>$value)
  6212. {
  6213. if(isset($specialAttributes[$name]))
  6214. {
  6215. if($value===false && $name==='async') {
  6216. $html .= ' ' . $name.'="false"';
  6217. }
  6218. elseif($value)
  6219. {
  6220. $html .= ' ' . $name;
  6221. if(self::$renderSpecialAttributesValue)
  6222. $html .= '="' . $name . '"';
  6223. }
  6224. }
  6225. elseif($value!==null)
  6226. $html .= ' ' . $name . '="' . ($raw ? $value : self::encode($value)) . '"';
  6227. }
  6228. return $html;
  6229. }
  6230. }
  6231. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  6232. {
  6233. public $enableSkin=false;
  6234. public $widgets=array();
  6235. public $skinnableWidgets;
  6236. public $skinPath;
  6237. private $_skins=array(); // class name, skin name, property name => value
  6238. public function init()
  6239. {
  6240. parent::init();
  6241. if($this->enableSkin && $this->skinPath===null)
  6242. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  6243. }
  6244. public function createWidget($owner,$className,$properties=array())
  6245. {
  6246. $className=Yii::import($className,true);
  6247. $widget=new $className($owner);
  6248. if(isset($this->widgets[$className]))
  6249. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  6250. if($this->enableSkin)
  6251. {
  6252. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  6253. {
  6254. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  6255. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  6256. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  6257. }
  6258. }
  6259. foreach($properties as $name=>$value)
  6260. $widget->$name=$value;
  6261. return $widget;
  6262. }
  6263. protected function getSkin($className,$skinName)
  6264. {
  6265. if(!isset($this->_skins[$className][$skinName]))
  6266. {
  6267. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  6268. if(is_file($skinFile))
  6269. $this->_skins[$className]=require($skinFile);
  6270. else
  6271. $this->_skins[$className]=array();
  6272. if(($theme=Yii::app()->getTheme())!==null)
  6273. {
  6274. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  6275. if(is_file($skinFile))
  6276. {
  6277. $skins=require($skinFile);
  6278. foreach($skins as $name=>$skin)
  6279. $this->_skins[$className][$name]=$skin;
  6280. }
  6281. }
  6282. if(!isset($this->_skins[$className][$skinName]))
  6283. $this->_skins[$className][$skinName]=array();
  6284. }
  6285. return $this->_skins[$className][$skinName];
  6286. }
  6287. }
  6288. class CWidget extends CBaseController
  6289. {
  6290. public $actionPrefix;
  6291. public $skin='default';
  6292. private static $_viewPaths;
  6293. private static $_counter=0;
  6294. private $_id;
  6295. private $_owner;
  6296. public static function actions()
  6297. {
  6298. return array();
  6299. }
  6300. public function __construct($owner=null)
  6301. {
  6302. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  6303. }
  6304. public function getOwner()
  6305. {
  6306. return $this->_owner;
  6307. }
  6308. public function getId($autoGenerate=true)
  6309. {
  6310. if($this->_id!==null)
  6311. return $this->_id;
  6312. elseif($autoGenerate)
  6313. return $this->_id='yw'.self::$_counter++;
  6314. }
  6315. public function setId($value)
  6316. {
  6317. $this->_id=$value;
  6318. }
  6319. public function getController()
  6320. {
  6321. if($this->_owner instanceof CController)
  6322. return $this->_owner;
  6323. else
  6324. return Yii::app()->getController();
  6325. }
  6326. public function init()
  6327. {
  6328. }
  6329. public function run()
  6330. {
  6331. }
  6332. public function getViewPath($checkTheme=false)
  6333. {
  6334. $className=get_class($this);
  6335. $scope=$checkTheme?'theme':'local';
  6336. if(isset(self::$_viewPaths[$className][$scope]))
  6337. return self::$_viewPaths[$className][$scope];
  6338. else
  6339. {
  6340. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  6341. {
  6342. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  6343. if(strpos($className,'\\')!==false) // namespaced class
  6344. $path.=str_replace('\\','_',ltrim($className,'\\'));
  6345. else
  6346. $path.=$className;
  6347. if(is_dir($path))
  6348. return self::$_viewPaths[$className]['theme']=$path;
  6349. }
  6350. $class=new ReflectionClass($className);
  6351. return self::$_viewPaths[$className]['local']=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  6352. }
  6353. }
  6354. public function getViewFile($viewName)
  6355. {
  6356. if(($renderer=Yii::app()->getViewRenderer())!==null)
  6357. $extension=$renderer->fileExtension;
  6358. else
  6359. $extension='.php';
  6360. if(strpos($viewName,'.')) // a path alias
  6361. $viewFile=Yii::getPathOfAlias($viewName);
  6362. else
  6363. {
  6364. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  6365. if(is_file($viewFile.$extension))
  6366. return Yii::app()->findLocalizedFile($viewFile.$extension);
  6367. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  6368. return Yii::app()->findLocalizedFile($viewFile.'.php');
  6369. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  6370. }
  6371. if(is_file($viewFile.$extension))
  6372. return Yii::app()->findLocalizedFile($viewFile.$extension);
  6373. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  6374. return Yii::app()->findLocalizedFile($viewFile.'.php');
  6375. else
  6376. return false;
  6377. }
  6378. public function render($view,$data=null,$return=false)
  6379. {
  6380. if(($viewFile=$this->getViewFile($view))!==false)
  6381. return $this->renderFile($viewFile,$data,$return);
  6382. else
  6383. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  6384. array('{widget}'=>get_class($this), '{view}'=>$view)));
  6385. }
  6386. }
  6387. class CClientScript extends CApplicationComponent
  6388. {
  6389. const POS_HEAD=0;
  6390. const POS_BEGIN=1;
  6391. const POS_END=2;
  6392. const POS_LOAD=3;
  6393. const POS_READY=4;
  6394. public $enableJavaScript=true;
  6395. public $scriptMap=array();
  6396. public $packages=array();
  6397. public $corePackages;
  6398. public $scripts=array();
  6399. protected $cssFiles=array();
  6400. protected $scriptFiles=array();
  6401. protected $metaTags=array();
  6402. protected $linkTags=array();
  6403. protected $css=array();
  6404. protected $hasScripts=false;
  6405. protected $coreScripts=array();
  6406. public $coreScriptPosition=self::POS_HEAD;
  6407. public $defaultScriptFilePosition=self::POS_HEAD;
  6408. public $defaultScriptPosition=self::POS_READY;
  6409. private $_baseUrl;
  6410. public function reset()
  6411. {
  6412. $this->hasScripts=false;
  6413. $this->coreScripts=array();
  6414. $this->cssFiles=array();
  6415. $this->css=array();
  6416. $this->scriptFiles=array();
  6417. $this->scripts=array();
  6418. $this->metaTags=array();
  6419. $this->linkTags=array();
  6420. $this->recordCachingAction('clientScript','reset',array());
  6421. }
  6422. public function render(&$output)
  6423. {
  6424. if(!$this->hasScripts)
  6425. return;
  6426. $this->renderCoreScripts();
  6427. if(!empty($this->scriptMap))
  6428. $this->remapScripts();
  6429. $this->unifyScripts();
  6430. $this->renderHead($output);
  6431. if($this->enableJavaScript)
  6432. {
  6433. $this->renderBodyBegin($output);
  6434. $this->renderBodyEnd($output);
  6435. }
  6436. }
  6437. protected function unifyScripts()
  6438. {
  6439. if(!$this->enableJavaScript)
  6440. return;
  6441. $map=array();
  6442. if(isset($this->scriptFiles[self::POS_HEAD]))
  6443. $map=$this->scriptFiles[self::POS_HEAD];
  6444. if(isset($this->scriptFiles[self::POS_BEGIN]))
  6445. {
  6446. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile=>$scriptFileValue)
  6447. {
  6448. if(isset($map[$scriptFile]))
  6449. unset($this->scriptFiles[self::POS_BEGIN][$scriptFile]);
  6450. else
  6451. $map[$scriptFile]=true;
  6452. }
  6453. }
  6454. if(isset($this->scriptFiles[self::POS_END]))
  6455. {
  6456. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  6457. {
  6458. if(isset($map[$key]))
  6459. unset($this->scriptFiles[self::POS_END][$key]);
  6460. }
  6461. }
  6462. }
  6463. protected function remapScripts()
  6464. {
  6465. $cssFiles=array();
  6466. foreach($this->cssFiles as $url=>$media)
  6467. {
  6468. $name=basename($url);
  6469. if(isset($this->scriptMap[$name]))
  6470. {
  6471. if($this->scriptMap[$name]!==false)
  6472. $cssFiles[$this->scriptMap[$name]]=$media;
  6473. }
  6474. elseif(isset($this->scriptMap['*.css']))
  6475. {
  6476. if($this->scriptMap['*.css']!==false)
  6477. $cssFiles[$this->scriptMap['*.css']]=$media;
  6478. }
  6479. else
  6480. $cssFiles[$url]=$media;
  6481. }
  6482. $this->cssFiles=$cssFiles;
  6483. $jsFiles=array();
  6484. foreach($this->scriptFiles as $position=>$scriptFiles)
  6485. {
  6486. $jsFiles[$position]=array();
  6487. foreach($scriptFiles as $scriptFile=>$scriptFileValue)
  6488. {
  6489. $name=basename($scriptFile);
  6490. if(isset($this->scriptMap[$name]))
  6491. {
  6492. if($this->scriptMap[$name]!==false)
  6493. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  6494. }
  6495. elseif(isset($this->scriptMap['*.js']))
  6496. {
  6497. if($this->scriptMap['*.js']!==false)
  6498. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  6499. }
  6500. else
  6501. $jsFiles[$position][$scriptFile]=$scriptFileValue;
  6502. }
  6503. }
  6504. $this->scriptFiles=$jsFiles;
  6505. }
  6506. protected function renderScriptBatch(array $scripts)
  6507. {
  6508. $html = '';
  6509. $scriptBatches = array();
  6510. foreach($scripts as $scriptValue)
  6511. {
  6512. if(is_array($scriptValue))
  6513. {
  6514. $scriptContent = $scriptValue['content'];
  6515. unset($scriptValue['content']);
  6516. $scriptHtmlOptions = $scriptValue;
  6517. ksort($scriptHtmlOptions);
  6518. }
  6519. else
  6520. {
  6521. $scriptContent = $scriptValue;
  6522. $scriptHtmlOptions = array();
  6523. }
  6524. $key=serialize($scriptHtmlOptions);
  6525. $scriptBatches[$key]['htmlOptions']=$scriptHtmlOptions;
  6526. $scriptBatches[$key]['scripts'][]=$scriptContent;
  6527. }
  6528. foreach($scriptBatches as $scriptBatch)
  6529. if(!empty($scriptBatch['scripts']))
  6530. $html.=CHtml::script(implode("\n",$scriptBatch['scripts']),$scriptBatch['htmlOptions'])."\n";
  6531. return $html;
  6532. }
  6533. public function renderCoreScripts()
  6534. {
  6535. if($this->coreScripts===null)
  6536. return;
  6537. $cssFiles=array();
  6538. $jsFiles=array();
  6539. foreach($this->coreScripts as $name=>$package)
  6540. {
  6541. $baseUrl=$this->getPackageBaseUrl($name);
  6542. if(!empty($package['js']))
  6543. {
  6544. foreach($package['js'] as $js)
  6545. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  6546. }
  6547. if(!empty($package['css']))
  6548. {
  6549. foreach($package['css'] as $css)
  6550. $cssFiles[$baseUrl.'/'.$css]='';
  6551. }
  6552. }
  6553. // merge in place
  6554. if($cssFiles!==array())
  6555. {
  6556. foreach($this->cssFiles as $cssFile=>$media)
  6557. $cssFiles[$cssFile]=$media;
  6558. $this->cssFiles=$cssFiles;
  6559. }
  6560. if($jsFiles!==array())
  6561. {
  6562. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  6563. {
  6564. foreach($this->scriptFiles[$this->coreScriptPosition] as $url => $value)
  6565. $jsFiles[$url]=$value;
  6566. }
  6567. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  6568. }
  6569. }
  6570. public function renderHead(&$output)
  6571. {
  6572. $html='';
  6573. foreach($this->metaTags as $meta)
  6574. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  6575. foreach($this->linkTags as $link)
  6576. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  6577. foreach($this->cssFiles as $url=>$media)
  6578. $html.=CHtml::cssFile($url,$media)."\n";
  6579. foreach($this->css as $css)
  6580. $html.=CHtml::css($css[0],$css[1])."\n";
  6581. if($this->enableJavaScript)
  6582. {
  6583. if(isset($this->scriptFiles[self::POS_HEAD]))
  6584. {
  6585. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFileValueUrl=>$scriptFileValue)
  6586. {
  6587. if(is_array($scriptFileValue))
  6588. $html.=CHtml::scriptFile($scriptFileValueUrl,$scriptFileValue)."\n";
  6589. else
  6590. $html.=CHtml::scriptFile($scriptFileValueUrl)."\n";
  6591. }
  6592. }
  6593. if(isset($this->scripts[self::POS_HEAD]))
  6594. $html.=$this->renderScriptBatch($this->scripts[self::POS_HEAD]);
  6595. }
  6596. if($html!=='')
  6597. {
  6598. $count=0;
  6599. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  6600. if($count)
  6601. $output=str_replace('<###head###>',$html,$output);
  6602. else
  6603. $output=$html.$output;
  6604. }
  6605. }
  6606. public function renderBodyBegin(&$output)
  6607. {
  6608. $html='';
  6609. if(isset($this->scriptFiles[self::POS_BEGIN]))
  6610. {
  6611. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFileUrl=>$scriptFileValue)
  6612. {
  6613. if(is_array($scriptFileValue))
  6614. $html.=CHtml::scriptFile($scriptFileUrl,$scriptFileValue)."\n";
  6615. else
  6616. $html.=CHtml::scriptFile($scriptFileUrl)."\n";
  6617. }
  6618. }
  6619. if(isset($this->scripts[self::POS_BEGIN]))
  6620. $html.=$this->renderScriptBatch($this->scripts[self::POS_BEGIN]);
  6621. if($html!=='')
  6622. {
  6623. $count=0;
  6624. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  6625. if($count)
  6626. $output=str_replace('<###begin###>',$html,$output);
  6627. else
  6628. $output=$html.$output;
  6629. }
  6630. }
  6631. public function renderBodyEnd(&$output)
  6632. {
  6633. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  6634. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  6635. return;
  6636. $fullPage=0;
  6637. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  6638. $html='';
  6639. if(isset($this->scriptFiles[self::POS_END]))
  6640. {
  6641. foreach($this->scriptFiles[self::POS_END] as $scriptFileUrl=>$scriptFileValue)
  6642. {
  6643. if(is_array($scriptFileValue))
  6644. $html.=CHtml::scriptFile($scriptFileUrl,$scriptFileValue)."\n";
  6645. else
  6646. $html.=CHtml::scriptFile($scriptFileUrl)."\n";
  6647. }
  6648. }
  6649. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  6650. if(isset($this->scripts[self::POS_READY]))
  6651. {
  6652. if($fullPage)
  6653. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  6654. else
  6655. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  6656. }
  6657. if(isset($this->scripts[self::POS_LOAD]))
  6658. {
  6659. if($fullPage)
  6660. $scripts[]="jQuery(window).on('load',function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  6661. else
  6662. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  6663. }
  6664. if(!empty($scripts))
  6665. $html.=$this->renderScriptBatch($scripts);
  6666. if($fullPage)
  6667. $output=str_replace('<###end###>',$html,$output);
  6668. else
  6669. $output=$output.$html;
  6670. }
  6671. public function getCoreScriptUrl()
  6672. {
  6673. if($this->_baseUrl!==null)
  6674. return $this->_baseUrl;
  6675. else
  6676. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  6677. }
  6678. public function setCoreScriptUrl($value)
  6679. {
  6680. $this->_baseUrl=$value;
  6681. }
  6682. public function getPackageBaseUrl($name)
  6683. {
  6684. if(!isset($this->coreScripts[$name]))
  6685. return false;
  6686. $package=$this->coreScripts[$name];
  6687. if(isset($package['baseUrl']))
  6688. {
  6689. $baseUrl=$package['baseUrl'];
  6690. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  6691. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  6692. $baseUrl=rtrim($baseUrl,'/');
  6693. }
  6694. elseif(isset($package['basePath']))
  6695. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  6696. else
  6697. $baseUrl=$this->getCoreScriptUrl();
  6698. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  6699. }
  6700. public function hasPackage($name)
  6701. {
  6702. if(isset($this->coreScripts[$name]))
  6703. return true;
  6704. if(isset($this->packages[$name]))
  6705. return true;
  6706. else
  6707. {
  6708. if($this->corePackages===null)
  6709. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  6710. if(isset($this->corePackages[$name]))
  6711. return true;
  6712. }
  6713. return false;
  6714. }
  6715. public function registerPackage($name)
  6716. {
  6717. return $this->registerCoreScript($name);
  6718. }
  6719. public function registerCoreScript($name)
  6720. {
  6721. if(isset($this->coreScripts[$name]))
  6722. return $this;
  6723. if(isset($this->packages[$name]))
  6724. $package=$this->packages[$name];
  6725. else
  6726. {
  6727. if($this->corePackages===null)
  6728. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  6729. if(isset($this->corePackages[$name]))
  6730. $package=$this->corePackages[$name];
  6731. }
  6732. if(isset($package))
  6733. {
  6734. if(!empty($package['depends']))
  6735. {
  6736. foreach($package['depends'] as $p)
  6737. $this->registerCoreScript($p);
  6738. }
  6739. $this->coreScripts[$name]=$package;
  6740. $this->hasScripts=true;
  6741. $params=func_get_args();
  6742. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  6743. }
  6744. elseif(YII_DEBUG)
  6745. throw new CException('There is no CClientScript package: '.$name);
  6746. else
  6747. Yii::log('There is no CClientScript package: '.$name,CLogger::LEVEL_WARNING,'system.web.CClientScript');
  6748. return $this;
  6749. }
  6750. public function registerCssFile($url,$media='')
  6751. {
  6752. $this->hasScripts=true;
  6753. $this->cssFiles[$url]=$media;
  6754. $params=func_get_args();
  6755. $this->recordCachingAction('clientScript','registerCssFile',$params);
  6756. return $this;
  6757. }
  6758. public function registerCss($id,$css,$media='')
  6759. {
  6760. $this->hasScripts=true;
  6761. $this->css[$id]=array($css,$media);
  6762. $params=func_get_args();
  6763. $this->recordCachingAction('clientScript','registerCss',$params);
  6764. return $this;
  6765. }
  6766. public function registerScriptFile($url,$position=null,array $htmlOptions=array())
  6767. {
  6768. $params=func_get_args();
  6769. if($position===null)
  6770. $position=$this->defaultScriptFilePosition;
  6771. $this->hasScripts=true;
  6772. if(empty($htmlOptions))
  6773. $value=$url;
  6774. else
  6775. {
  6776. $value=$htmlOptions;
  6777. $value['src']=$url;
  6778. }
  6779. $this->scriptFiles[$position][$url]=$value;
  6780. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  6781. return $this;
  6782. }
  6783. public function registerScript($id,$script,$position=null,array $htmlOptions=array())
  6784. {
  6785. $params=func_get_args();
  6786. if($position===null)
  6787. $position=$this->defaultScriptPosition;
  6788. $this->hasScripts=true;
  6789. if(empty($htmlOptions))
  6790. $scriptValue=$script;
  6791. else
  6792. {
  6793. if($position==self::POS_LOAD || $position==self::POS_READY)
  6794. throw new CException(Yii::t('yii','Script HTML options are not allowed for "CClientScript::POS_LOAD" and "CClientScript::POS_READY".'));
  6795. $scriptValue=$htmlOptions;
  6796. $scriptValue['content']=$script;
  6797. }
  6798. $this->scripts[$position][$id]=$scriptValue;
  6799. if($position===self::POS_READY || $position===self::POS_LOAD)
  6800. $this->registerCoreScript('jquery');
  6801. $this->recordCachingAction('clientScript','registerScript',$params);
  6802. return $this;
  6803. }
  6804. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array(),$id=null)
  6805. {
  6806. $params=func_get_args();
  6807. $this->hasScripts=true;
  6808. if($name!==null)
  6809. $options['name']=$name;
  6810. if($httpEquiv!==null)
  6811. $options['http-equiv']=$httpEquiv;
  6812. $options['content']=$content;
  6813. $this->metaTags[null===$id?count($this->metaTags):$id]=$options;
  6814. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  6815. return $this;
  6816. }
  6817. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  6818. {
  6819. $params=func_get_args();
  6820. $this->hasScripts=true;
  6821. if($relation!==null)
  6822. $options['rel']=$relation;
  6823. if($type!==null)
  6824. $options['type']=$type;
  6825. if($href!==null)
  6826. $options['href']=$href;
  6827. if($media!==null)
  6828. $options['media']=$media;
  6829. $this->linkTags[serialize($options)]=$options;
  6830. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  6831. return $this;
  6832. }
  6833. public function isCssFileRegistered($url)
  6834. {
  6835. return isset($this->cssFiles[$url]);
  6836. }
  6837. public function isCssRegistered($id)
  6838. {
  6839. return isset($this->css[$id]);
  6840. }
  6841. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  6842. {
  6843. return isset($this->scriptFiles[$position][$url]);
  6844. }
  6845. public function isScriptRegistered($id,$position=self::POS_READY)
  6846. {
  6847. return isset($this->scripts[$position][$id]);
  6848. }
  6849. protected function recordCachingAction($context,$method,$params)
  6850. {
  6851. if(($controller=Yii::app()->getController())!==null)
  6852. $controller->recordCachingAction($context,$method,$params);
  6853. }
  6854. public function addPackage($name,$definition)
  6855. {
  6856. $this->packages[$name]=$definition;
  6857. return $this;
  6858. }
  6859. }
  6860. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  6861. {
  6862. private $_d=array();
  6863. private $_c=0;
  6864. private $_r=false;
  6865. public function __construct($data=null,$readOnly=false)
  6866. {
  6867. if($data!==null)
  6868. $this->copyFrom($data);
  6869. $this->setReadOnly($readOnly);
  6870. }
  6871. public function getReadOnly()
  6872. {
  6873. return $this->_r;
  6874. }
  6875. protected function setReadOnly($value)
  6876. {
  6877. $this->_r=$value;
  6878. }
  6879. public function getIterator()
  6880. {
  6881. return new CListIterator($this->_d);
  6882. }
  6883. public function count()
  6884. {
  6885. return $this->getCount();
  6886. }
  6887. public function getCount()
  6888. {
  6889. return $this->_c;
  6890. }
  6891. public function itemAt($index)
  6892. {
  6893. if(isset($this->_d[$index]))
  6894. return $this->_d[$index];
  6895. elseif($index>=0 && $index<$this->_c) // in case the value is null
  6896. return $this->_d[$index];
  6897. else
  6898. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6899. array('{index}'=>$index)));
  6900. }
  6901. public function add($item)
  6902. {
  6903. $this->insertAt($this->_c,$item);
  6904. return $this->_c-1;
  6905. }
  6906. public function insertAt($index,$item)
  6907. {
  6908. if(!$this->_r)
  6909. {
  6910. if($index===$this->_c)
  6911. $this->_d[$this->_c++]=$item;
  6912. elseif($index>=0 && $index<$this->_c)
  6913. {
  6914. array_splice($this->_d,$index,0,array($item));
  6915. $this->_c++;
  6916. }
  6917. else
  6918. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6919. array('{index}'=>$index)));
  6920. }
  6921. else
  6922. throw new CException(Yii::t('yii','The list is read only.'));
  6923. }
  6924. public function remove($item)
  6925. {
  6926. if(($index=$this->indexOf($item))>=0)
  6927. {
  6928. $this->removeAt($index);
  6929. return $index;
  6930. }
  6931. else
  6932. return false;
  6933. }
  6934. public function removeAt($index)
  6935. {
  6936. if(!$this->_r)
  6937. {
  6938. if($index>=0 && $index<$this->_c)
  6939. {
  6940. $this->_c--;
  6941. if($index===$this->_c)
  6942. return array_pop($this->_d);
  6943. else
  6944. {
  6945. $item=$this->_d[$index];
  6946. array_splice($this->_d,$index,1);
  6947. return $item;
  6948. }
  6949. }
  6950. else
  6951. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6952. array('{index}'=>$index)));
  6953. }
  6954. else
  6955. throw new CException(Yii::t('yii','The list is read only.'));
  6956. }
  6957. public function clear()
  6958. {
  6959. for($i=$this->_c-1;$i>=0;--$i)
  6960. $this->removeAt($i);
  6961. }
  6962. public function contains($item)
  6963. {
  6964. return $this->indexOf($item)>=0;
  6965. }
  6966. public function indexOf($item)
  6967. {
  6968. if(($index=array_search($item,$this->_d,true))!==false)
  6969. return $index;
  6970. else
  6971. return -1;
  6972. }
  6973. public function toArray()
  6974. {
  6975. return $this->_d;
  6976. }
  6977. public function copyFrom($data)
  6978. {
  6979. if(is_array($data) || ($data instanceof Traversable))
  6980. {
  6981. if($this->_c>0)
  6982. $this->clear();
  6983. if($data instanceof CList)
  6984. $data=$data->_d;
  6985. foreach($data as $item)
  6986. $this->add($item);
  6987. }
  6988. elseif($data!==null)
  6989. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6990. }
  6991. public function mergeWith($data)
  6992. {
  6993. if(is_array($data) || ($data instanceof Traversable))
  6994. {
  6995. if($data instanceof CList)
  6996. $data=$data->_d;
  6997. foreach($data as $item)
  6998. $this->add($item);
  6999. }
  7000. elseif($data!==null)
  7001. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  7002. }
  7003. public function offsetExists($offset)
  7004. {
  7005. return ($offset>=0 && $offset<$this->_c);
  7006. }
  7007. public function offsetGet($offset)
  7008. {
  7009. return $this->itemAt($offset);
  7010. }
  7011. public function offsetSet($offset,$item)
  7012. {
  7013. if($offset===null || $offset===$this->_c)
  7014. $this->insertAt($this->_c,$item);
  7015. else
  7016. {
  7017. $this->removeAt($offset);
  7018. $this->insertAt($offset,$item);
  7019. }
  7020. }
  7021. public function offsetUnset($offset)
  7022. {
  7023. $this->removeAt($offset);
  7024. }
  7025. }
  7026. class CFilterChain extends CList
  7027. {
  7028. public $controller;
  7029. public $action;
  7030. public $filterIndex=0;
  7031. public function __construct($controller,$action)
  7032. {
  7033. $this->controller=$controller;
  7034. $this->action=$action;
  7035. }
  7036. public static function create($controller,$action,$filters)
  7037. {
  7038. $chain=new CFilterChain($controller,$action);
  7039. $actionID=$action->getId();
  7040. foreach($filters as $filter)
  7041. {
  7042. if(is_string($filter)) // filterName [+|- action1 action2]
  7043. {
  7044. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  7045. {
  7046. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  7047. if(($filter[$pos]==='+')===$matched)
  7048. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  7049. }
  7050. else
  7051. $filter=CInlineFilter::create($controller,$filter);
  7052. }
  7053. elseif(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  7054. {
  7055. if(!isset($filter[0]))
  7056. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  7057. $filterClass=$filter[0];
  7058. unset($filter[0]);
  7059. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  7060. {
  7061. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  7062. if(($filterClass[$pos]==='+')===$matched)
  7063. $filterClass=trim(substr($filterClass,0,$pos));
  7064. else
  7065. continue;
  7066. }
  7067. $filter['class']=$filterClass;
  7068. $filter=Yii::createComponent($filter);
  7069. }
  7070. if(is_object($filter))
  7071. {
  7072. $filter->init();
  7073. $chain->add($filter);
  7074. }
  7075. }
  7076. return $chain;
  7077. }
  7078. public function insertAt($index,$item)
  7079. {
  7080. if($item instanceof IFilter)
  7081. parent::insertAt($index,$item);
  7082. else
  7083. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  7084. }
  7085. public function run()
  7086. {
  7087. if($this->offsetExists($this->filterIndex))
  7088. {
  7089. $filter=$this->itemAt($this->filterIndex++);
  7090. $filter->filter($this);
  7091. }
  7092. else
  7093. $this->controller->runAction($this->action);
  7094. }
  7095. }
  7096. class CFilter extends CComponent implements IFilter
  7097. {
  7098. public function filter($filterChain)
  7099. {
  7100. if($this->preFilter($filterChain))
  7101. {
  7102. $filterChain->run();
  7103. $this->postFilter($filterChain);
  7104. }
  7105. }
  7106. public function init()
  7107. {
  7108. }
  7109. protected function preFilter($filterChain)
  7110. {
  7111. return true;
  7112. }
  7113. protected function postFilter($filterChain)
  7114. {
  7115. }
  7116. }
  7117. class CInlineFilter extends CFilter
  7118. {
  7119. public $name;
  7120. public static function create($controller,$filterName)
  7121. {
  7122. if(method_exists($controller,'filter'.$filterName))
  7123. {
  7124. $filter=new CInlineFilter;
  7125. $filter->name=$filterName;
  7126. return $filter;
  7127. }
  7128. else
  7129. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  7130. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  7131. }
  7132. public function filter($filterChain)
  7133. {
  7134. $method='filter'.$this->name;
  7135. $filterChain->controller->$method($filterChain);
  7136. }
  7137. }
  7138. class CAccessControlFilter extends CFilter
  7139. {
  7140. public $message;
  7141. private $_rules=array();
  7142. public function getRules()
  7143. {
  7144. return $this->_rules;
  7145. }
  7146. public function setRules($rules)
  7147. {
  7148. foreach($rules as $rule)
  7149. {
  7150. if(is_array($rule) && isset($rule[0]))
  7151. {
  7152. $r=new CAccessRule;
  7153. $r->allow=$rule[0]==='allow';
  7154. foreach(array_slice($rule,1) as $name=>$value)
  7155. {
  7156. if($name==='expression' || $name==='roles' || $name==='message' || $name==='deniedCallback')
  7157. $r->$name=$value;
  7158. else
  7159. $r->$name=array_map('strtolower',$value);
  7160. }
  7161. $this->_rules[]=$r;
  7162. }
  7163. }
  7164. }
  7165. protected function preFilter($filterChain)
  7166. {
  7167. $app=Yii::app();
  7168. $request=$app->getRequest();
  7169. $user=$app->getUser();
  7170. $verb=$request->getRequestType();
  7171. $ip=$request->getUserHostAddress();
  7172. foreach($this->getRules() as $rule)
  7173. {
  7174. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  7175. break;
  7176. elseif($allow<0) // denied
  7177. {
  7178. if(isset($rule->deniedCallback))
  7179. call_user_func($rule->deniedCallback, $rule);
  7180. else
  7181. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  7182. return false;
  7183. }
  7184. }
  7185. return true;
  7186. }
  7187. protected function resolveErrorMessage($rule)
  7188. {
  7189. if($rule->message!==null)
  7190. return $rule->message;
  7191. elseif($this->message!==null)
  7192. return $this->message;
  7193. else
  7194. return Yii::t('yii','You are not authorized to perform this action.');
  7195. }
  7196. protected function accessDenied($user,$message)
  7197. {
  7198. if($user->getIsGuest())
  7199. $user->loginRequired();
  7200. else
  7201. throw new CHttpException(403,$message);
  7202. }
  7203. }
  7204. class CAccessRule extends CComponent
  7205. {
  7206. public $allow;
  7207. public $actions;
  7208. public $controllers;
  7209. public $users;
  7210. public $roles;
  7211. public $ips;
  7212. public $verbs;
  7213. public $expression;
  7214. public $message;
  7215. public $deniedCallback;
  7216. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  7217. {
  7218. if($this->isActionMatched($action)
  7219. && $this->isUserMatched($user)
  7220. && $this->isRoleMatched($user)
  7221. && $this->isIpMatched($ip)
  7222. && $this->isVerbMatched($verb)
  7223. && $this->isControllerMatched($controller)
  7224. && $this->isExpressionMatched($user))
  7225. return $this->allow ? 1 : -1;
  7226. else
  7227. return 0;
  7228. }
  7229. protected function isActionMatched($action)
  7230. {
  7231. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  7232. }
  7233. protected function isControllerMatched($controller)
  7234. {
  7235. return empty($this->controllers) || in_array(strtolower($controller->getUniqueId()),$this->controllers);
  7236. }
  7237. protected function isUserMatched($user)
  7238. {
  7239. if(empty($this->users))
  7240. return true;
  7241. foreach($this->users as $u)
  7242. {
  7243. if($u==='*')
  7244. return true;
  7245. elseif($u==='?' && $user->getIsGuest())
  7246. return true;
  7247. elseif($u==='@' && !$user->getIsGuest())
  7248. return true;
  7249. elseif(!strcasecmp($u,$user->getName()))
  7250. return true;
  7251. }
  7252. return false;
  7253. }
  7254. protected function isRoleMatched($user)
  7255. {
  7256. if(empty($this->roles))
  7257. return true;
  7258. foreach($this->roles as $key=>$role)
  7259. {
  7260. if(is_numeric($key))
  7261. {
  7262. if($user->checkAccess($role))
  7263. return true;
  7264. }
  7265. else
  7266. {
  7267. if($user->checkAccess($key,$role))
  7268. return true;
  7269. }
  7270. }
  7271. return false;
  7272. }
  7273. protected function isIpMatched($ip)
  7274. {
  7275. if(empty($this->ips))
  7276. return true;
  7277. foreach($this->ips as $rule)
  7278. {
  7279. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  7280. return true;
  7281. }
  7282. return false;
  7283. }
  7284. protected function isVerbMatched($verb)
  7285. {
  7286. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  7287. }
  7288. protected function isExpressionMatched($user)
  7289. {
  7290. if($this->expression===null)
  7291. return true;
  7292. else
  7293. return $this->evaluateExpression($this->expression, array('user'=>$user));
  7294. }
  7295. }
  7296. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  7297. {
  7298. private $_errors=array(); // attribute name => array of errors
  7299. private $_validators; // validators
  7300. private $_scenario=''; // scenario
  7301. abstract public function attributeNames();
  7302. public function rules()
  7303. {
  7304. return array();
  7305. }
  7306. public function behaviors()
  7307. {
  7308. return array();
  7309. }
  7310. public function attributeLabels()
  7311. {
  7312. return array();
  7313. }
  7314. public function validate($attributes=null, $clearErrors=true)
  7315. {
  7316. if($clearErrors)
  7317. $this->clearErrors();
  7318. if($this->beforeValidate())
  7319. {
  7320. foreach($this->getValidators() as $validator)
  7321. $validator->validate($this,$attributes);
  7322. $this->afterValidate();
  7323. return !$this->hasErrors();
  7324. }
  7325. else
  7326. return false;
  7327. }
  7328. protected function afterConstruct()
  7329. {
  7330. if($this->hasEventHandler('onAfterConstruct'))
  7331. $this->onAfterConstruct(new CEvent($this));
  7332. }
  7333. protected function beforeValidate()
  7334. {
  7335. $event=new CModelEvent($this);
  7336. $this->onBeforeValidate($event);
  7337. return $event->isValid;
  7338. }
  7339. protected function afterValidate()
  7340. {
  7341. $this->onAfterValidate(new CEvent($this));
  7342. }
  7343. public function onAfterConstruct($event)
  7344. {
  7345. $this->raiseEvent('onAfterConstruct',$event);
  7346. }
  7347. public function onBeforeValidate($event)
  7348. {
  7349. $this->raiseEvent('onBeforeValidate',$event);
  7350. }
  7351. public function onAfterValidate($event)
  7352. {
  7353. $this->raiseEvent('onAfterValidate',$event);
  7354. }
  7355. public function getValidatorList()
  7356. {
  7357. if($this->_validators===null)
  7358. $this->_validators=$this->createValidators();
  7359. return $this->_validators;
  7360. }
  7361. public function getValidators($attribute=null)
  7362. {
  7363. if($this->_validators===null)
  7364. $this->_validators=$this->createValidators();
  7365. $validators=array();
  7366. $scenario=$this->getScenario();
  7367. foreach($this->_validators as $validator)
  7368. {
  7369. if($validator->applyTo($scenario))
  7370. {
  7371. if($attribute===null || in_array($attribute,$validator->attributes,true))
  7372. $validators[]=$validator;
  7373. }
  7374. }
  7375. return $validators;
  7376. }
  7377. public function createValidators()
  7378. {
  7379. $validators=new CList;
  7380. foreach($this->rules() as $rule)
  7381. {
  7382. if(isset($rule[0],$rule[1])) // attributes, validator name
  7383. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  7384. else
  7385. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  7386. array('{class}'=>get_class($this))));
  7387. }
  7388. return $validators;
  7389. }
  7390. public function isAttributeRequired($attribute)
  7391. {
  7392. foreach($this->getValidators($attribute) as $validator)
  7393. {
  7394. if($validator instanceof CRequiredValidator)
  7395. return true;
  7396. }
  7397. return false;
  7398. }
  7399. public function isAttributeSafe($attribute)
  7400. {
  7401. $attributes=$this->getSafeAttributeNames();
  7402. return in_array($attribute,$attributes);
  7403. }
  7404. public function getAttributeLabel($attribute)
  7405. {
  7406. $labels=$this->attributeLabels();
  7407. if(isset($labels[$attribute]))
  7408. return $labels[$attribute];
  7409. else
  7410. return $this->generateAttributeLabel($attribute);
  7411. }
  7412. public function hasErrors($attribute=null)
  7413. {
  7414. if($attribute===null)
  7415. return $this->_errors!==array();
  7416. else
  7417. return isset($this->_errors[$attribute]);
  7418. }
  7419. public function getErrors($attribute=null)
  7420. {
  7421. if($attribute===null)
  7422. return $this->_errors;
  7423. else
  7424. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  7425. }
  7426. public function getError($attribute)
  7427. {
  7428. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  7429. }
  7430. public function addError($attribute,$error)
  7431. {
  7432. $this->_errors[$attribute][]=$error;
  7433. }
  7434. public function addErrors($errors)
  7435. {
  7436. foreach($errors as $attribute=>$error)
  7437. {
  7438. if(is_array($error))
  7439. {
  7440. foreach($error as $e)
  7441. $this->addError($attribute, $e);
  7442. }
  7443. else
  7444. $this->addError($attribute, $error);
  7445. }
  7446. }
  7447. public function clearErrors($attribute=null)
  7448. {
  7449. if($attribute===null)
  7450. $this->_errors=array();
  7451. else
  7452. unset($this->_errors[$attribute]);
  7453. }
  7454. public function generateAttributeLabel($name)
  7455. {
  7456. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  7457. }
  7458. public function getAttributes($names=null)
  7459. {
  7460. $values=array();
  7461. foreach($this->attributeNames() as $name)
  7462. $values[$name]=$this->$name;
  7463. if(is_array($names))
  7464. {
  7465. $values2=array();
  7466. foreach($names as $name)
  7467. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  7468. return $values2;
  7469. }
  7470. else
  7471. return $values;
  7472. }
  7473. public function setAttributes($values,$safeOnly=true)
  7474. {
  7475. if(!is_array($values))
  7476. return;
  7477. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  7478. foreach($values as $name=>$value)
  7479. {
  7480. if(isset($attributes[$name]))
  7481. $this->$name=$value;
  7482. elseif($safeOnly)
  7483. $this->onUnsafeAttribute($name,$value);
  7484. }
  7485. }
  7486. public function unsetAttributes($names=null)
  7487. {
  7488. if($names===null)
  7489. $names=$this->attributeNames();
  7490. foreach($names as $name)
  7491. $this->$name=null;
  7492. }
  7493. public function onUnsafeAttribute($name,$value)
  7494. {
  7495. if(YII_DEBUG)
  7496. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  7497. }
  7498. public function getScenario()
  7499. {
  7500. return $this->_scenario;
  7501. }
  7502. public function setScenario($value)
  7503. {
  7504. $this->_scenario=$value;
  7505. }
  7506. public function getSafeAttributeNames()
  7507. {
  7508. $attributes=array();
  7509. $unsafe=array();
  7510. foreach($this->getValidators() as $validator)
  7511. {
  7512. if(!$validator->safe)
  7513. {
  7514. foreach($validator->attributes as $name)
  7515. $unsafe[]=$name;
  7516. }
  7517. else
  7518. {
  7519. foreach($validator->attributes as $name)
  7520. $attributes[$name]=true;
  7521. }
  7522. }
  7523. foreach($unsafe as $name)
  7524. unset($attributes[$name]);
  7525. return array_keys($attributes);
  7526. }
  7527. public function getIterator()
  7528. {
  7529. $attributes=$this->getAttributes();
  7530. return new CMapIterator($attributes);
  7531. }
  7532. public function offsetExists($offset)
  7533. {
  7534. return property_exists($this,$offset);
  7535. }
  7536. public function offsetGet($offset)
  7537. {
  7538. return $this->$offset;
  7539. }
  7540. public function offsetSet($offset,$item)
  7541. {
  7542. $this->$offset=$item;
  7543. }
  7544. public function offsetUnset($offset)
  7545. {
  7546. unset($this->$offset);
  7547. }
  7548. }
  7549. abstract class CActiveRecord extends CModel
  7550. {
  7551. const BELONGS_TO='CBelongsToRelation';
  7552. const HAS_ONE='CHasOneRelation';
  7553. const HAS_MANY='CHasManyRelation';
  7554. const MANY_MANY='CManyManyRelation';
  7555. const STAT='CStatRelation';
  7556. public static $db;
  7557. private static $_models=array(); // class name => model
  7558. private static $_md=array(); // class name => meta data
  7559. private $_new=false; // whether this instance is new or not
  7560. private $_attributes=array(); // attribute name => attribute value
  7561. private $_related=array(); // attribute name => related objects
  7562. private $_c; // query criteria (used by finder only)
  7563. private $_pk; // old primary key value
  7564. private $_alias='t'; // the table alias being used for query
  7565. public function __construct($scenario='insert')
  7566. {
  7567. if($scenario===null) // internally used by populateRecord() and model()
  7568. return;
  7569. $this->setScenario($scenario);
  7570. $this->setIsNewRecord(true);
  7571. $this->_attributes=$this->getMetaData()->attributeDefaults;
  7572. $this->init();
  7573. $this->attachBehaviors($this->behaviors());
  7574. $this->afterConstruct();
  7575. }
  7576. public function init()
  7577. {
  7578. }
  7579. public function cache($duration, $dependency=null, $queryCount=1)
  7580. {
  7581. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  7582. return $this;
  7583. }
  7584. public function __sleep()
  7585. {
  7586. return array_keys((array)$this);
  7587. }
  7588. public function __get($name)
  7589. {
  7590. if(isset($this->_attributes[$name]))
  7591. return $this->_attributes[$name];
  7592. elseif(isset($this->getMetaData()->columns[$name]))
  7593. return null;
  7594. elseif(isset($this->_related[$name]))
  7595. return $this->_related[$name];
  7596. elseif(isset($this->getMetaData()->relations[$name]))
  7597. return $this->getRelated($name);
  7598. else
  7599. return parent::__get($name);
  7600. }
  7601. public function __set($name,$value)
  7602. {
  7603. if($this->setAttribute($name,$value)===false)
  7604. {
  7605. if(isset($this->getMetaData()->relations[$name]))
  7606. $this->_related[$name]=$value;
  7607. else
  7608. parent::__set($name,$value);
  7609. }
  7610. }
  7611. public function __isset($name)
  7612. {
  7613. if(isset($this->_attributes[$name]))
  7614. return true;
  7615. elseif(isset($this->getMetaData()->columns[$name]))
  7616. return false;
  7617. elseif(isset($this->_related[$name]))
  7618. return true;
  7619. elseif(isset($this->getMetaData()->relations[$name]))
  7620. return $this->getRelated($name)!==null;
  7621. else
  7622. return parent::__isset($name);
  7623. }
  7624. public function __unset($name)
  7625. {
  7626. if(isset($this->getMetaData()->columns[$name]))
  7627. unset($this->_attributes[$name]);
  7628. elseif(isset($this->getMetaData()->relations[$name]))
  7629. unset($this->_related[$name]);
  7630. else
  7631. parent::__unset($name);
  7632. }
  7633. public function __call($name,$parameters)
  7634. {
  7635. if(isset($this->getMetaData()->relations[$name]))
  7636. {
  7637. if(empty($parameters))
  7638. return $this->getRelated($name,false);
  7639. else
  7640. return $this->getRelated($name,false,$parameters[0]);
  7641. }
  7642. $scopes=$this->scopes();
  7643. if(isset($scopes[$name]))
  7644. {
  7645. $this->getDbCriteria()->mergeWith($scopes[$name]);
  7646. return $this;
  7647. }
  7648. return parent::__call($name,$parameters);
  7649. }
  7650. public function getRelated($name,$refresh=false,$params=array())
  7651. {
  7652. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  7653. return $this->_related[$name];
  7654. $md=$this->getMetaData();
  7655. if(!isset($md->relations[$name]))
  7656. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  7657. array('{class}'=>get_class($this), '{name}'=>$name)));
  7658. $relation=$md->relations[$name];
  7659. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  7660. return $relation instanceof CHasOneRelation ? null : array();
  7661. if($params!==array()) // dynamic query
  7662. {
  7663. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7664. if($exists)
  7665. $save=$this->_related[$name];
  7666. if($params instanceof CDbCriteria)
  7667. $params = $params->toArray();
  7668. $r=array($name=>$params);
  7669. }
  7670. else
  7671. $r=$name;
  7672. unset($this->_related[$name]);
  7673. $finder=$this->getActiveFinder($r);
  7674. $finder->lazyFind($this);
  7675. if(!isset($this->_related[$name]))
  7676. {
  7677. if($relation instanceof CHasManyRelation)
  7678. $this->_related[$name]=array();
  7679. elseif($relation instanceof CStatRelation)
  7680. $this->_related[$name]=$relation->defaultValue;
  7681. else
  7682. $this->_related[$name]=null;
  7683. }
  7684. if($params!==array())
  7685. {
  7686. $results=$this->_related[$name];
  7687. if($exists)
  7688. $this->_related[$name]=$save;
  7689. else
  7690. unset($this->_related[$name]);
  7691. return $results;
  7692. }
  7693. else
  7694. return $this->_related[$name];
  7695. }
  7696. public function hasRelated($name)
  7697. {
  7698. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7699. }
  7700. public function getDbCriteria($createIfNull=true)
  7701. {
  7702. if($this->_c===null)
  7703. {
  7704. if(($c=$this->defaultScope())!==array() || $createIfNull)
  7705. $this->_c=new CDbCriteria($c);
  7706. }
  7707. return $this->_c;
  7708. }
  7709. public function setDbCriteria($criteria)
  7710. {
  7711. $this->_c=$criteria;
  7712. }
  7713. public function defaultScope()
  7714. {
  7715. return array();
  7716. }
  7717. public function resetScope($resetDefault=true)
  7718. {
  7719. if($resetDefault)
  7720. $this->_c=new CDbCriteria();
  7721. else
  7722. $this->_c=null;
  7723. return $this;
  7724. }
  7725. public static function model($className=__CLASS__)
  7726. {
  7727. if(isset(self::$_models[$className]))
  7728. return self::$_models[$className];
  7729. else
  7730. {
  7731. $model=self::$_models[$className]=new $className(null);
  7732. $model->attachBehaviors($model->behaviors());
  7733. return $model;
  7734. }
  7735. }
  7736. public function getMetaData()
  7737. {
  7738. $className=get_class($this);
  7739. if(!array_key_exists($className,self::$_md))
  7740. {
  7741. self::$_md[$className]=null; // preventing recursive invokes of {@link getMetaData()} via {@link __get()}
  7742. self::$_md[$className]=new CActiveRecordMetaData($this);
  7743. }
  7744. return self::$_md[$className];
  7745. }
  7746. public function refreshMetaData()
  7747. {
  7748. $className=get_class($this);
  7749. if(array_key_exists($className,self::$_md))
  7750. unset(self::$_md[$className]);
  7751. }
  7752. public function tableName()
  7753. {
  7754. $tableName = get_class($this);
  7755. if(($pos=strrpos($tableName,'\\')) !== false)
  7756. return substr($tableName,$pos+1);
  7757. return $tableName;
  7758. }
  7759. public function primaryKey()
  7760. {
  7761. }
  7762. public function relations()
  7763. {
  7764. return array();
  7765. }
  7766. public function scopes()
  7767. {
  7768. return array();
  7769. }
  7770. public function attributeNames()
  7771. {
  7772. return array_keys($this->getMetaData()->columns);
  7773. }
  7774. public function getAttributeLabel($attribute)
  7775. {
  7776. $labels=$this->attributeLabels();
  7777. if(isset($labels[$attribute]))
  7778. return $labels[$attribute];
  7779. elseif(strpos($attribute,'.')!==false)
  7780. {
  7781. $segs=explode('.',$attribute);
  7782. $name=array_pop($segs);
  7783. $model=$this;
  7784. foreach($segs as $seg)
  7785. {
  7786. $relations=$model->getMetaData()->relations;
  7787. if(isset($relations[$seg]))
  7788. $model=CActiveRecord::model($relations[$seg]->className);
  7789. else
  7790. break;
  7791. }
  7792. return $model->getAttributeLabel($name);
  7793. }
  7794. else
  7795. return $this->generateAttributeLabel($attribute);
  7796. }
  7797. public function getDbConnection()
  7798. {
  7799. if(self::$db!==null)
  7800. return self::$db;
  7801. else
  7802. {
  7803. self::$db=Yii::app()->getDb();
  7804. if(self::$db instanceof CDbConnection)
  7805. return self::$db;
  7806. else
  7807. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  7808. }
  7809. }
  7810. public function getActiveRelation($name)
  7811. {
  7812. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  7813. }
  7814. public function getTableSchema()
  7815. {
  7816. return $this->getMetaData()->tableSchema;
  7817. }
  7818. public function getCommandBuilder()
  7819. {
  7820. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  7821. }
  7822. public function hasAttribute($name)
  7823. {
  7824. return isset($this->getMetaData()->columns[$name]);
  7825. }
  7826. public function getAttribute($name)
  7827. {
  7828. if(property_exists($this,$name))
  7829. return $this->$name;
  7830. elseif(isset($this->_attributes[$name]))
  7831. return $this->_attributes[$name];
  7832. }
  7833. public function setAttribute($name,$value)
  7834. {
  7835. if(property_exists($this,$name))
  7836. $this->$name=$value;
  7837. elseif(isset($this->getMetaData()->columns[$name]))
  7838. $this->_attributes[$name]=$value;
  7839. else
  7840. return false;
  7841. return true;
  7842. }
  7843. public function addRelatedRecord($name,$record,$index)
  7844. {
  7845. if($index!==false)
  7846. {
  7847. if(!isset($this->_related[$name]))
  7848. $this->_related[$name]=array();
  7849. if($record instanceof CActiveRecord)
  7850. {
  7851. if($index===true)
  7852. $this->_related[$name][]=$record;
  7853. else
  7854. $this->_related[$name][$index]=$record;
  7855. }
  7856. }
  7857. elseif(!isset($this->_related[$name]))
  7858. $this->_related[$name]=$record;
  7859. }
  7860. public function getAttributes($names=true)
  7861. {
  7862. $attributes=$this->_attributes;
  7863. foreach($this->getMetaData()->columns as $name=>$column)
  7864. {
  7865. if(property_exists($this,$name))
  7866. $attributes[$name]=$this->$name;
  7867. elseif($names===true && !isset($attributes[$name]))
  7868. $attributes[$name]=null;
  7869. }
  7870. if(is_array($names))
  7871. {
  7872. $attrs=array();
  7873. foreach($names as $name)
  7874. {
  7875. if(property_exists($this,$name))
  7876. $attrs[$name]=$this->$name;
  7877. else
  7878. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  7879. }
  7880. return $attrs;
  7881. }
  7882. else
  7883. return $attributes;
  7884. }
  7885. public function save($runValidation=true,$attributes=null)
  7886. {
  7887. if(!$runValidation || $this->validate($attributes))
  7888. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  7889. else
  7890. return false;
  7891. }
  7892. public function getIsNewRecord()
  7893. {
  7894. return $this->_new;
  7895. }
  7896. public function setIsNewRecord($value)
  7897. {
  7898. $this->_new=$value;
  7899. }
  7900. public function onBeforeSave($event)
  7901. {
  7902. $this->raiseEvent('onBeforeSave',$event);
  7903. }
  7904. public function onAfterSave($event)
  7905. {
  7906. $this->raiseEvent('onAfterSave',$event);
  7907. }
  7908. public function onBeforeDelete($event)
  7909. {
  7910. $this->raiseEvent('onBeforeDelete',$event);
  7911. }
  7912. public function onAfterDelete($event)
  7913. {
  7914. $this->raiseEvent('onAfterDelete',$event);
  7915. }
  7916. public function onBeforeFind($event)
  7917. {
  7918. $this->raiseEvent('onBeforeFind',$event);
  7919. }
  7920. public function onAfterFind($event)
  7921. {
  7922. $this->raiseEvent('onAfterFind',$event);
  7923. }
  7924. public function getActiveFinder($with)
  7925. {
  7926. return new CActiveFinder($this,$with);
  7927. }
  7928. public function onBeforeCount($event)
  7929. {
  7930. $this->raiseEvent('onBeforeCount',$event);
  7931. }
  7932. protected function beforeSave()
  7933. {
  7934. if($this->hasEventHandler('onBeforeSave'))
  7935. {
  7936. $event=new CModelEvent($this);
  7937. $this->onBeforeSave($event);
  7938. return $event->isValid;
  7939. }
  7940. else
  7941. return true;
  7942. }
  7943. protected function afterSave()
  7944. {
  7945. if($this->hasEventHandler('onAfterSave'))
  7946. $this->onAfterSave(new CEvent($this));
  7947. }
  7948. protected function beforeDelete()
  7949. {
  7950. if($this->hasEventHandler('onBeforeDelete'))
  7951. {
  7952. $event=new CModelEvent($this);
  7953. $this->onBeforeDelete($event);
  7954. return $event->isValid;
  7955. }
  7956. else
  7957. return true;
  7958. }
  7959. protected function afterDelete()
  7960. {
  7961. if($this->hasEventHandler('onAfterDelete'))
  7962. $this->onAfterDelete(new CEvent($this));
  7963. }
  7964. protected function beforeFind()
  7965. {
  7966. if($this->hasEventHandler('onBeforeFind'))
  7967. {
  7968. $event=new CModelEvent($this);
  7969. $this->onBeforeFind($event);
  7970. }
  7971. }
  7972. protected function beforeCount()
  7973. {
  7974. if($this->hasEventHandler('onBeforeCount'))
  7975. $this->onBeforeCount(new CEvent($this));
  7976. }
  7977. protected function afterFind()
  7978. {
  7979. if($this->hasEventHandler('onAfterFind'))
  7980. $this->onAfterFind(new CEvent($this));
  7981. }
  7982. public function beforeFindInternal()
  7983. {
  7984. $this->beforeFind();
  7985. }
  7986. public function afterFindInternal()
  7987. {
  7988. $this->afterFind();
  7989. }
  7990. public function insert($attributes=null)
  7991. {
  7992. if(!$this->getIsNewRecord())
  7993. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  7994. if($this->beforeSave())
  7995. {
  7996. $builder=$this->getCommandBuilder();
  7997. $table=$this->getTableSchema();
  7998. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  7999. if($command->execute())
  8000. {
  8001. $primaryKey=$table->primaryKey;
  8002. if($table->sequenceName!==null)
  8003. {
  8004. if(is_string($primaryKey) && $this->$primaryKey===null)
  8005. $this->$primaryKey=$builder->getLastInsertID($table);
  8006. elseif(is_array($primaryKey))
  8007. {
  8008. foreach($primaryKey as $pk)
  8009. {
  8010. if($this->$pk===null)
  8011. {
  8012. $this->$pk=$builder->getLastInsertID($table);
  8013. break;
  8014. }
  8015. }
  8016. }
  8017. }
  8018. $this->_pk=$this->getPrimaryKey();
  8019. $this->afterSave();
  8020. $this->setIsNewRecord(false);
  8021. $this->setScenario('update');
  8022. return true;
  8023. }
  8024. }
  8025. return false;
  8026. }
  8027. public function update($attributes=null)
  8028. {
  8029. if($this->getIsNewRecord())
  8030. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  8031. if($this->beforeSave())
  8032. {
  8033. if($this->_pk===null)
  8034. $this->_pk=$this->getPrimaryKey();
  8035. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  8036. $this->_pk=$this->getPrimaryKey();
  8037. $this->afterSave();
  8038. return true;
  8039. }
  8040. else
  8041. return false;
  8042. }
  8043. public function saveAttributes($attributes)
  8044. {
  8045. if(!$this->getIsNewRecord())
  8046. {
  8047. $values=array();
  8048. foreach($attributes as $name=>$value)
  8049. {
  8050. if(is_integer($name))
  8051. $values[$value]=$this->$value;
  8052. else
  8053. $values[$name]=$this->$name=$value;
  8054. }
  8055. if($this->_pk===null)
  8056. $this->_pk=$this->getPrimaryKey();
  8057. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  8058. {
  8059. $this->_pk=$this->getPrimaryKey();
  8060. return true;
  8061. }
  8062. else
  8063. return false;
  8064. }
  8065. else
  8066. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  8067. }
  8068. public function saveCounters($counters)
  8069. {
  8070. $builder=$this->getCommandBuilder();
  8071. $table=$this->getTableSchema();
  8072. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  8073. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  8074. if($command->execute())
  8075. {
  8076. foreach($counters as $name=>$value)
  8077. $this->$name=$this->$name+$value;
  8078. return true;
  8079. }
  8080. else
  8081. return false;
  8082. }
  8083. public function delete()
  8084. {
  8085. if(!$this->getIsNewRecord())
  8086. {
  8087. if($this->beforeDelete())
  8088. {
  8089. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  8090. $this->afterDelete();
  8091. return $result;
  8092. }
  8093. else
  8094. return false;
  8095. }
  8096. else
  8097. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  8098. }
  8099. public function refresh()
  8100. {
  8101. if(($record=$this->findByPk($this->getPrimaryKey()))!==null)
  8102. {
  8103. $this->_attributes=array();
  8104. $this->_related=array();
  8105. foreach($this->getMetaData()->columns as $name=>$column)
  8106. {
  8107. if(property_exists($this,$name))
  8108. $this->$name=$record->$name;
  8109. else
  8110. $this->_attributes[$name]=$record->$name;
  8111. }
  8112. return true;
  8113. }
  8114. else
  8115. return false;
  8116. }
  8117. public function equals($record)
  8118. {
  8119. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  8120. }
  8121. public function getPrimaryKey()
  8122. {
  8123. $table=$this->getTableSchema();
  8124. if(is_string($table->primaryKey))
  8125. return $this->{$table->primaryKey};
  8126. elseif(is_array($table->primaryKey))
  8127. {
  8128. $values=array();
  8129. foreach($table->primaryKey as $name)
  8130. $values[$name]=$this->$name;
  8131. return $values;
  8132. }
  8133. else
  8134. return null;
  8135. }
  8136. public function setPrimaryKey($value)
  8137. {
  8138. $this->_pk=$this->getPrimaryKey();
  8139. $table=$this->getTableSchema();
  8140. if(is_string($table->primaryKey))
  8141. $this->{$table->primaryKey}=$value;
  8142. elseif(is_array($table->primaryKey))
  8143. {
  8144. foreach($table->primaryKey as $name)
  8145. $this->$name=$value[$name];
  8146. }
  8147. }
  8148. public function getOldPrimaryKey()
  8149. {
  8150. return $this->_pk;
  8151. }
  8152. public function setOldPrimaryKey($value)
  8153. {
  8154. $this->_pk=$value;
  8155. }
  8156. protected function query($criteria,$all=false)
  8157. {
  8158. $this->beforeFind();
  8159. $this->applyScopes($criteria);
  8160. if(empty($criteria->with))
  8161. {
  8162. if(!$all)
  8163. $criteria->limit=1;
  8164. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  8165. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  8166. }
  8167. else
  8168. {
  8169. $finder=$this->getActiveFinder($criteria->with);
  8170. return $finder->query($criteria,$all);
  8171. }
  8172. }
  8173. public function applyScopes(&$criteria)
  8174. {
  8175. if(!empty($criteria->scopes))
  8176. {
  8177. $scs=$this->scopes();
  8178. $c=$this->getDbCriteria();
  8179. foreach((array)$criteria->scopes as $k=>$v)
  8180. {
  8181. if(is_integer($k))
  8182. {
  8183. if(is_string($v))
  8184. {
  8185. if(isset($scs[$v]))
  8186. {
  8187. $c->mergeWith($scs[$v],true);
  8188. continue;
  8189. }
  8190. $scope=$v;
  8191. $params=array();
  8192. }
  8193. elseif(is_array($v))
  8194. {
  8195. $scope=key($v);
  8196. $params=current($v);
  8197. }
  8198. }
  8199. elseif(is_string($k))
  8200. {
  8201. $scope=$k;
  8202. $params=$v;
  8203. }
  8204. call_user_func_array(array($this,$scope),(array)$params);
  8205. }
  8206. }
  8207. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  8208. {
  8209. $c->mergeWith($criteria);
  8210. $criteria=$c;
  8211. $this->resetScope(false);
  8212. }
  8213. }
  8214. public function getTableAlias($quote=false, $checkScopes=true)
  8215. {
  8216. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  8217. $alias=$criteria->alias;
  8218. else
  8219. $alias=$this->_alias;
  8220. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  8221. }
  8222. public function setTableAlias($alias)
  8223. {
  8224. $this->_alias=$alias;
  8225. }
  8226. public function find($condition='',$params=array())
  8227. {
  8228. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  8229. return $this->query($criteria);
  8230. }
  8231. public function findAll($condition='',$params=array())
  8232. {
  8233. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  8234. return $this->query($criteria,true);
  8235. }
  8236. public function findByPk($pk,$condition='',$params=array())
  8237. {
  8238. $prefix=$this->getTableAlias(true).'.';
  8239. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  8240. return $this->query($criteria);
  8241. }
  8242. public function findAllByPk($pk,$condition='',$params=array())
  8243. {
  8244. $prefix=$this->getTableAlias(true).'.';
  8245. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  8246. return $this->query($criteria,true);
  8247. }
  8248. public function findByAttributes($attributes,$condition='',$params=array())
  8249. {
  8250. $prefix=$this->getTableAlias(true).'.';
  8251. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8252. return $this->query($criteria);
  8253. }
  8254. public function findAllByAttributes($attributes,$condition='',$params=array())
  8255. {
  8256. $prefix=$this->getTableAlias(true).'.';
  8257. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8258. return $this->query($criteria,true);
  8259. }
  8260. public function findBySql($sql,$params=array())
  8261. {
  8262. $this->beforeFind();
  8263. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  8264. {
  8265. $this->resetScope(false);
  8266. $finder=$this->getActiveFinder($criteria->with);
  8267. return $finder->findBySql($sql,$params);
  8268. }
  8269. else
  8270. {
  8271. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  8272. return $this->populateRecord($command->queryRow());
  8273. }
  8274. }
  8275. public function findAllBySql($sql,$params=array())
  8276. {
  8277. $this->beforeFind();
  8278. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  8279. {
  8280. $this->resetScope(false);
  8281. $finder=$this->getActiveFinder($criteria->with);
  8282. return $finder->findAllBySql($sql,$params);
  8283. }
  8284. else
  8285. {
  8286. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  8287. return $this->populateRecords($command->queryAll());
  8288. }
  8289. }
  8290. public function count($condition='',$params=array())
  8291. {
  8292. $this->beforeCount();
  8293. $builder=$this->getCommandBuilder();
  8294. $criteria=$builder->createCriteria($condition,$params);
  8295. $this->applyScopes($criteria);
  8296. if(empty($criteria->with))
  8297. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  8298. else
  8299. {
  8300. $finder=$this->getActiveFinder($criteria->with);
  8301. return $finder->count($criteria);
  8302. }
  8303. }
  8304. public function countByAttributes($attributes,$condition='',$params=array())
  8305. {
  8306. $prefix=$this->getTableAlias(true).'.';
  8307. $builder=$this->getCommandBuilder();
  8308. $this->beforeCount();
  8309. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8310. $this->applyScopes($criteria);
  8311. if(empty($criteria->with))
  8312. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  8313. else
  8314. {
  8315. $finder=$this->getActiveFinder($criteria->with);
  8316. return $finder->count($criteria);
  8317. }
  8318. }
  8319. public function countBySql($sql,$params=array())
  8320. {
  8321. $this->beforeCount();
  8322. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  8323. }
  8324. public function exists($condition='',$params=array())
  8325. {
  8326. $builder=$this->getCommandBuilder();
  8327. $criteria=$builder->createCriteria($condition,$params);
  8328. $table=$this->getTableSchema();
  8329. $criteria->select='1';
  8330. $criteria->limit=1;
  8331. $this->applyScopes($criteria);
  8332. if(empty($criteria->with))
  8333. return $builder->createFindCommand($table,$criteria,$this->getTableAlias(false, false))->queryRow()!==false;
  8334. else
  8335. {
  8336. $criteria->select='*';
  8337. $finder=$this->getActiveFinder($criteria->with);
  8338. return $finder->count($criteria)>0;
  8339. }
  8340. }
  8341. public function with()
  8342. {
  8343. if(func_num_args()>0)
  8344. {
  8345. $with=func_get_args();
  8346. if(is_array($with[0])) // the parameter is given as an array
  8347. $with=$with[0];
  8348. if(!empty($with))
  8349. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  8350. }
  8351. return $this;
  8352. }
  8353. public function together()
  8354. {
  8355. $this->getDbCriteria()->together=true;
  8356. return $this;
  8357. }
  8358. public function updateByPk($pk,$attributes,$condition='',$params=array())
  8359. {
  8360. $builder=$this->getCommandBuilder();
  8361. $table=$this->getTableSchema();
  8362. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  8363. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  8364. return $command->execute();
  8365. }
  8366. public function updateAll($attributes,$condition='',$params=array())
  8367. {
  8368. $builder=$this->getCommandBuilder();
  8369. $criteria=$builder->createCriteria($condition,$params);
  8370. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  8371. return $command->execute();
  8372. }
  8373. public function updateCounters($counters,$condition='',$params=array())
  8374. {
  8375. $builder=$this->getCommandBuilder();
  8376. $criteria=$builder->createCriteria($condition,$params);
  8377. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  8378. return $command->execute();
  8379. }
  8380. public function deleteByPk($pk,$condition='',$params=array())
  8381. {
  8382. $builder=$this->getCommandBuilder();
  8383. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  8384. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  8385. return $command->execute();
  8386. }
  8387. public function deleteAll($condition='',$params=array())
  8388. {
  8389. $builder=$this->getCommandBuilder();
  8390. $criteria=$builder->createCriteria($condition,$params);
  8391. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  8392. return $command->execute();
  8393. }
  8394. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  8395. {
  8396. $builder=$this->getCommandBuilder();
  8397. $table=$this->getTableSchema();
  8398. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  8399. $command=$builder->createDeleteCommand($table,$criteria);
  8400. return $command->execute();
  8401. }
  8402. public function populateRecord($attributes,$callAfterFind=true)
  8403. {
  8404. if($attributes!==false)
  8405. {
  8406. $record=$this->instantiate($attributes);
  8407. $record->setScenario('update');
  8408. $record->init();
  8409. $md=$record->getMetaData();
  8410. foreach($attributes as $name=>$value)
  8411. {
  8412. if(property_exists($record,$name))
  8413. $record->$name=$value;
  8414. elseif(isset($md->columns[$name]))
  8415. $record->_attributes[$name]=$value;
  8416. }
  8417. $record->_pk=$record->getPrimaryKey();
  8418. $record->attachBehaviors($record->behaviors());
  8419. if($callAfterFind)
  8420. $record->afterFind();
  8421. return $record;
  8422. }
  8423. else
  8424. return null;
  8425. }
  8426. public function populateRecords($data,$callAfterFind=true,$index=null)
  8427. {
  8428. $records=array();
  8429. foreach($data as $attributes)
  8430. {
  8431. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  8432. {
  8433. if($index===null)
  8434. $records[]=$record;
  8435. else
  8436. $records[$record->$index]=$record;
  8437. }
  8438. }
  8439. return $records;
  8440. }
  8441. protected function instantiate($attributes)
  8442. {
  8443. $class=get_class($this);
  8444. $model=new $class(null);
  8445. return $model;
  8446. }
  8447. public function offsetExists($offset)
  8448. {
  8449. return $this->__isset($offset);
  8450. }
  8451. }
  8452. class CBaseActiveRelation extends CComponent
  8453. {
  8454. public $name;
  8455. public $className;
  8456. public $foreignKey;
  8457. public $select='*';
  8458. public $condition='';
  8459. public $params=array();
  8460. public $group='';
  8461. public $join='';
  8462. public $joinOptions='';
  8463. public $having='';
  8464. public $order='';
  8465. public function __construct($name,$className,$foreignKey,$options=array())
  8466. {
  8467. $this->name=$name;
  8468. $this->className=$className;
  8469. $this->foreignKey=$foreignKey;
  8470. foreach($options as $name=>$value)
  8471. $this->$name=$value;
  8472. }
  8473. public function mergeWith($criteria,$fromScope=false)
  8474. {
  8475. if($criteria instanceof CDbCriteria)
  8476. $criteria=$criteria->toArray();
  8477. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  8478. {
  8479. if($this->select==='*'||$this->select===false)
  8480. $this->select=$criteria['select'];
  8481. elseif($criteria['select']===false)
  8482. $this->select=false;
  8483. elseif($criteria['select']!=='*')
  8484. {
  8485. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  8486. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  8487. $this->select=array_merge($select1,array_diff($select2,$select1));
  8488. }
  8489. }
  8490. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  8491. {
  8492. if($this->condition==='')
  8493. $this->condition=$criteria['condition'];
  8494. elseif($criteria['condition']!=='')
  8495. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  8496. }
  8497. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  8498. $this->params=array_merge($this->params,$criteria['params']);
  8499. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  8500. {
  8501. if($this->order==='')
  8502. $this->order=$criteria['order'];
  8503. elseif($criteria['order']!=='')
  8504. $this->order=$criteria['order'].', '.$this->order;
  8505. }
  8506. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  8507. {
  8508. if($this->group==='')
  8509. $this->group=$criteria['group'];
  8510. elseif($criteria['group']!=='')
  8511. $this->group.=', '.$criteria['group'];
  8512. }
  8513. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  8514. {
  8515. if($this->join==='')
  8516. $this->join=$criteria['join'];
  8517. elseif($criteria['join']!=='')
  8518. $this->join.=' '.$criteria['join'];
  8519. }
  8520. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  8521. {
  8522. if($this->having==='')
  8523. $this->having=$criteria['having'];
  8524. elseif($criteria['having']!=='')
  8525. $this->having="({$this->having}) AND ({$criteria['having']})";
  8526. }
  8527. }
  8528. }
  8529. class CStatRelation extends CBaseActiveRelation
  8530. {
  8531. public $select='COUNT(*)';
  8532. public $defaultValue=0;
  8533. public $scopes;
  8534. public function mergeWith($criteria,$fromScope=false)
  8535. {
  8536. if($criteria instanceof CDbCriteria)
  8537. $criteria=$criteria->toArray();
  8538. parent::mergeWith($criteria,$fromScope);
  8539. if(isset($criteria['defaultValue']))
  8540. $this->defaultValue=$criteria['defaultValue'];
  8541. }
  8542. }
  8543. class CActiveRelation extends CBaseActiveRelation
  8544. {
  8545. public $joinType='LEFT OUTER JOIN';
  8546. public $on='';
  8547. public $alias;
  8548. public $with=array();
  8549. public $together;
  8550. public $scopes;
  8551. public $through;
  8552. public function mergeWith($criteria,$fromScope=false)
  8553. {
  8554. if($criteria instanceof CDbCriteria)
  8555. $criteria=$criteria->toArray();
  8556. if($fromScope)
  8557. {
  8558. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  8559. {
  8560. if($this->on==='')
  8561. $this->on=$criteria['condition'];
  8562. elseif($criteria['condition']!=='')
  8563. $this->on="({$this->on}) AND ({$criteria['condition']})";
  8564. }
  8565. unset($criteria['condition']);
  8566. }
  8567. parent::mergeWith($criteria);
  8568. if(isset($criteria['joinType']))
  8569. $this->joinType=$criteria['joinType'];
  8570. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  8571. {
  8572. if($this->on==='')
  8573. $this->on=$criteria['on'];
  8574. elseif($criteria['on']!=='')
  8575. $this->on="({$this->on}) AND ({$criteria['on']})";
  8576. }
  8577. if(isset($criteria['with']))
  8578. $this->with=$criteria['with'];
  8579. if(isset($criteria['alias']))
  8580. $this->alias=$criteria['alias'];
  8581. if(isset($criteria['together']))
  8582. $this->together=$criteria['together'];
  8583. }
  8584. }
  8585. class CBelongsToRelation extends CActiveRelation
  8586. {
  8587. }
  8588. class CHasOneRelation extends CActiveRelation
  8589. {
  8590. }
  8591. class CHasManyRelation extends CActiveRelation
  8592. {
  8593. public $limit=-1;
  8594. public $offset=-1;
  8595. public $index;
  8596. public function mergeWith($criteria,$fromScope=false)
  8597. {
  8598. if($criteria instanceof CDbCriteria)
  8599. $criteria=$criteria->toArray();
  8600. parent::mergeWith($criteria,$fromScope);
  8601. if(isset($criteria['limit']) && $criteria['limit']>0)
  8602. $this->limit=$criteria['limit'];
  8603. if(isset($criteria['offset']) && $criteria['offset']>=0)
  8604. $this->offset=$criteria['offset'];
  8605. if(isset($criteria['index']))
  8606. $this->index=$criteria['index'];
  8607. }
  8608. }
  8609. class CManyManyRelation extends CHasManyRelation
  8610. {
  8611. private $_junctionTableName=null;
  8612. private $_junctionForeignKeys=null;
  8613. public function getJunctionTableName()
  8614. {
  8615. if ($this->_junctionTableName===null)
  8616. $this->initJunctionData();
  8617. return $this->_junctionTableName;
  8618. }
  8619. public function getJunctionForeignKeys()
  8620. {
  8621. if ($this->_junctionForeignKeys===null)
  8622. $this->initJunctionData();
  8623. return $this->_junctionForeignKeys;
  8624. }
  8625. private function initJunctionData()
  8626. {
  8627. if(!preg_match('/^\s*(.*?)\((.*)\)\s*$/',$this->foreignKey,$matches))
  8628. 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,...)".',
  8629. array('{class}'=>$this->className,'{relation}'=>$this->name)));
  8630. $this->_junctionTableName=$matches[1];
  8631. $this->_junctionForeignKeys=preg_split('/\s*,\s*/',$matches[2],-1,PREG_SPLIT_NO_EMPTY);
  8632. }
  8633. }
  8634. class CActiveRecordMetaData
  8635. {
  8636. public $tableSchema;
  8637. public $columns;
  8638. public $relations=array();
  8639. public $attributeDefaults=array();
  8640. private $_modelClassName;
  8641. public function __construct($model)
  8642. {
  8643. $this->_modelClassName=get_class($model);
  8644. $tableName=$model->tableName();
  8645. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  8646. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  8647. array('{class}'=>$this->_modelClassName,'{table}'=>$tableName)));
  8648. if(($modelPk=$model->primaryKey())!==null || $table->primaryKey===null)
  8649. {
  8650. $table->primaryKey=$modelPk;
  8651. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  8652. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  8653. elseif(is_array($table->primaryKey))
  8654. {
  8655. foreach($table->primaryKey as $name)
  8656. {
  8657. if(isset($table->columns[$name]))
  8658. $table->columns[$name]->isPrimaryKey=true;
  8659. }
  8660. }
  8661. }
  8662. $this->tableSchema=$table;
  8663. $this->columns=$table->columns;
  8664. foreach($table->columns as $name=>$column)
  8665. {
  8666. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  8667. $this->attributeDefaults[$name]=$column->defaultValue;
  8668. }
  8669. foreach($model->relations() as $name=>$config)
  8670. {
  8671. $this->addRelation($name,$config);
  8672. }
  8673. }
  8674. public function addRelation($name,$config)
  8675. {
  8676. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  8677. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  8678. else
  8679. 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)));
  8680. }
  8681. public function hasRelation($name)
  8682. {
  8683. return isset($this->relations[$name]);
  8684. }
  8685. public function removeRelation($name)
  8686. {
  8687. unset($this->relations[$name]);
  8688. }
  8689. }
  8690. class CDbConnection extends CApplicationComponent
  8691. {
  8692. public $connectionString;
  8693. public $username='';
  8694. public $password='';
  8695. public $schemaCachingDuration=0;
  8696. public $schemaCachingExclude=array();
  8697. public $schemaCacheID='cache';
  8698. public $queryCachingDuration=0;
  8699. public $queryCachingDependency;
  8700. public $queryCachingCount=0;
  8701. public $queryCacheID='cache';
  8702. public $autoConnect=true;
  8703. public $charset;
  8704. public $emulatePrepare;
  8705. public $enableParamLogging=false;
  8706. public $enableProfiling=false;
  8707. public $tablePrefix;
  8708. public $initSQLs;
  8709. public $driverMap=array(
  8710. 'cubrid'=>'CCubridSchema', // CUBRID
  8711. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  8712. 'mysqli'=>'CMysqlSchema', // MySQL
  8713. 'mysql'=>'CMysqlSchema', // MySQL,MariaDB
  8714. 'sqlite'=>'CSqliteSchema', // sqlite 3
  8715. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  8716. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  8717. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  8718. 'sqlsrv'=>'CMssqlSchema', // Mssql
  8719. 'oci'=>'COciSchema', // Oracle driver
  8720. );
  8721. public $pdoClass = 'PDO';
  8722. private $_driverName;
  8723. private $_attributes=array();
  8724. private $_active=false;
  8725. private $_pdo;
  8726. private $_transaction;
  8727. private $_schema;
  8728. public function __construct($dsn='',$username='',$password='')
  8729. {
  8730. $this->connectionString=$dsn;
  8731. $this->username=$username;
  8732. $this->password=$password;
  8733. }
  8734. public function __sleep()
  8735. {
  8736. $this->close();
  8737. return array_keys(get_object_vars($this));
  8738. }
  8739. public static function getAvailableDrivers()
  8740. {
  8741. return PDO::getAvailableDrivers();
  8742. }
  8743. public function init()
  8744. {
  8745. parent::init();
  8746. if($this->autoConnect)
  8747. $this->setActive(true);
  8748. }
  8749. public function getActive()
  8750. {
  8751. return $this->_active;
  8752. }
  8753. public function setActive($value)
  8754. {
  8755. if($value!=$this->_active)
  8756. {
  8757. if($value)
  8758. $this->open();
  8759. else
  8760. $this->close();
  8761. }
  8762. }
  8763. public function cache($duration, $dependency=null, $queryCount=1)
  8764. {
  8765. $this->queryCachingDuration=$duration;
  8766. $this->queryCachingDependency=$dependency;
  8767. $this->queryCachingCount=$queryCount;
  8768. return $this;
  8769. }
  8770. protected function open()
  8771. {
  8772. if($this->_pdo===null)
  8773. {
  8774. if(empty($this->connectionString))
  8775. throw new CDbException('CDbConnection.connectionString cannot be empty.');
  8776. try
  8777. {
  8778. $this->_pdo=$this->createPdoInstance();
  8779. $this->initConnection($this->_pdo);
  8780. $this->_active=true;
  8781. }
  8782. catch(PDOException $e)
  8783. {
  8784. if(YII_DEBUG)
  8785. {
  8786. throw new CDbException('CDbConnection failed to open the DB connection: '.
  8787. $e->getMessage(),(int)$e->getCode(),$e->errorInfo);
  8788. }
  8789. else
  8790. {
  8791. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  8792. throw new CDbException('CDbConnection failed to open the DB connection.',(int)$e->getCode(),$e->errorInfo);
  8793. }
  8794. }
  8795. }
  8796. }
  8797. protected function close()
  8798. {
  8799. $this->_pdo=null;
  8800. $this->_active=false;
  8801. $this->_schema=null;
  8802. }
  8803. protected function createPdoInstance()
  8804. {
  8805. $pdoClass=$this->pdoClass;
  8806. if(($driver=$this->getDriverName())!==null)
  8807. {
  8808. if($driver==='mssql' || $driver==='dblib')
  8809. $pdoClass='CMssqlPdoAdapter';
  8810. elseif($driver==='sqlsrv')
  8811. $pdoClass='CMssqlSqlsrvPdoAdapter';
  8812. }
  8813. if(!class_exists($pdoClass))
  8814. throw new CDbException(Yii::t('yii','CDbConnection is unable to find PDO class "{className}". Make sure PDO is installed correctly.',
  8815. array('{className}'=>$pdoClass)));
  8816. @$instance=new $pdoClass($this->connectionString,$this->username,$this->password,$this->_attributes);
  8817. if(!$instance)
  8818. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'));
  8819. return $instance;
  8820. }
  8821. protected function initConnection($pdo)
  8822. {
  8823. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  8824. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  8825. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  8826. if($this->charset!==null)
  8827. {
  8828. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  8829. if(in_array($driver,array('pgsql','mysql','mysqli')))
  8830. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  8831. }
  8832. if($this->initSQLs!==null)
  8833. {
  8834. foreach($this->initSQLs as $sql)
  8835. $pdo->exec($sql);
  8836. }
  8837. }
  8838. public function getPdoInstance()
  8839. {
  8840. return $this->_pdo;
  8841. }
  8842. public function createCommand($query=null)
  8843. {
  8844. $this->setActive(true);
  8845. return new CDbCommand($this,$query);
  8846. }
  8847. public function getCurrentTransaction()
  8848. {
  8849. if($this->_transaction!==null)
  8850. {
  8851. if($this->_transaction->getActive())
  8852. return $this->_transaction;
  8853. }
  8854. return null;
  8855. }
  8856. public function beginTransaction()
  8857. {
  8858. $this->setActive(true);
  8859. $this->_pdo->beginTransaction();
  8860. return $this->_transaction=new CDbTransaction($this);
  8861. }
  8862. public function getSchema()
  8863. {
  8864. if($this->_schema!==null)
  8865. return $this->_schema;
  8866. else
  8867. {
  8868. $driver=$this->getDriverName();
  8869. if(isset($this->driverMap[$driver]))
  8870. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  8871. else
  8872. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  8873. array('{driver}'=>$driver)));
  8874. }
  8875. }
  8876. public function getCommandBuilder()
  8877. {
  8878. return $this->getSchema()->getCommandBuilder();
  8879. }
  8880. public function getLastInsertID($sequenceName='')
  8881. {
  8882. $this->setActive(true);
  8883. return $this->_pdo->lastInsertId($sequenceName);
  8884. }
  8885. public function quoteValue($str)
  8886. {
  8887. if(is_int($str) || is_float($str))
  8888. return $str;
  8889. $this->setActive(true);
  8890. return $this->quoteValueInternal($str, PDO::PARAM_STR);
  8891. }
  8892. public function quoteValueWithType($value, $type)
  8893. {
  8894. $this->setActive(true);
  8895. return $this->quoteValueInternal($value, $type);
  8896. }
  8897. private function quoteValueInternal($value, $type)
  8898. {
  8899. if(mb_stripos($this->connectionString, 'odbc:')===false)
  8900. {
  8901. if(($quoted=$this->_pdo->quote($value, $type))!==false)
  8902. return $quoted;
  8903. }
  8904. // fallback for drivers that don't support quote (e.g. oci and odbc)
  8905. return "'" . addcslashes(str_replace("'", "''", $value), "\000\n\r\\\032") . "'";
  8906. }
  8907. public function quoteTableName($name)
  8908. {
  8909. return $this->getSchema()->quoteTableName($name);
  8910. }
  8911. public function quoteColumnName($name)
  8912. {
  8913. return $this->getSchema()->quoteColumnName($name);
  8914. }
  8915. public function getPdoType($type)
  8916. {
  8917. static $map=array
  8918. (
  8919. 'boolean'=>PDO::PARAM_BOOL,
  8920. 'integer'=>PDO::PARAM_INT,
  8921. 'string'=>PDO::PARAM_STR,
  8922. 'resource'=>PDO::PARAM_LOB,
  8923. 'NULL'=>PDO::PARAM_NULL,
  8924. );
  8925. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  8926. }
  8927. public function getColumnCase()
  8928. {
  8929. return $this->getAttribute(PDO::ATTR_CASE);
  8930. }
  8931. public function setColumnCase($value)
  8932. {
  8933. $this->setAttribute(PDO::ATTR_CASE,$value);
  8934. }
  8935. public function getNullConversion()
  8936. {
  8937. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  8938. }
  8939. public function setNullConversion($value)
  8940. {
  8941. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  8942. }
  8943. public function getAutoCommit()
  8944. {
  8945. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  8946. }
  8947. public function setAutoCommit($value)
  8948. {
  8949. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  8950. }
  8951. public function getPersistent()
  8952. {
  8953. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  8954. }
  8955. public function setPersistent($value)
  8956. {
  8957. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  8958. }
  8959. public function getDriverName()
  8960. {
  8961. if($this->_driverName!==null)
  8962. return $this->_driverName;
  8963. elseif(($pos=strpos($this->connectionString,':'))!==false)
  8964. return $this->_driverName=strtolower(substr($this->connectionString,0,$pos));
  8965. //return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  8966. }
  8967. public function setDriverName($driverName)
  8968. {
  8969. $this->_driverName=strtolower($driverName);
  8970. }
  8971. public function getClientVersion()
  8972. {
  8973. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  8974. }
  8975. public function getConnectionStatus()
  8976. {
  8977. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  8978. }
  8979. public function getPrefetch()
  8980. {
  8981. return $this->getAttribute(PDO::ATTR_PREFETCH);
  8982. }
  8983. public function getServerInfo()
  8984. {
  8985. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  8986. }
  8987. public function getServerVersion()
  8988. {
  8989. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  8990. }
  8991. public function getTimeout()
  8992. {
  8993. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  8994. }
  8995. public function getAttribute($name)
  8996. {
  8997. $this->setActive(true);
  8998. return $this->_pdo->getAttribute($name);
  8999. }
  9000. public function setAttribute($name,$value)
  9001. {
  9002. if($this->_pdo instanceof PDO)
  9003. $this->_pdo->setAttribute($name,$value);
  9004. else
  9005. $this->_attributes[$name]=$value;
  9006. }
  9007. public function getAttributes()
  9008. {
  9009. return $this->_attributes;
  9010. }
  9011. public function setAttributes($values)
  9012. {
  9013. foreach($values as $name=>$value)
  9014. $this->_attributes[$name]=$value;
  9015. }
  9016. public function getStats()
  9017. {
  9018. $logger=Yii::getLogger();
  9019. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  9020. $count=count($timings);
  9021. $time=array_sum($timings);
  9022. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  9023. $count+=count($timings);
  9024. $time+=array_sum($timings);
  9025. return array($count,$time);
  9026. }
  9027. }
  9028. abstract class CDbSchema extends CComponent
  9029. {
  9030. public $columnTypes=array();
  9031. private $_tableNames=array();
  9032. private $_tables=array();
  9033. private $_connection;
  9034. private $_builder;
  9035. private $_cacheExclude=array();
  9036. abstract protected function loadTable($name);
  9037. public function __construct($conn)
  9038. {
  9039. $this->_connection=$conn;
  9040. foreach($conn->schemaCachingExclude as $name)
  9041. $this->_cacheExclude[$name]=true;
  9042. }
  9043. public function getDbConnection()
  9044. {
  9045. return $this->_connection;
  9046. }
  9047. public function getTable($name,$refresh=false)
  9048. {
  9049. if($refresh===false && isset($this->_tables[$name]))
  9050. return $this->_tables[$name];
  9051. else
  9052. {
  9053. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  9054. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  9055. else
  9056. $realName=$name;
  9057. // temporarily disable query caching
  9058. if($this->_connection->queryCachingDuration>0)
  9059. {
  9060. $qcDuration=$this->_connection->queryCachingDuration;
  9061. $this->_connection->queryCachingDuration=0;
  9062. }
  9063. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  9064. {
  9065. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  9066. $table=$cache->get($key);
  9067. if($refresh===true || $table===false)
  9068. {
  9069. $table=$this->loadTable($realName);
  9070. if($table!==null)
  9071. $cache->set($key,$table,$duration);
  9072. }
  9073. $this->_tables[$name]=$table;
  9074. }
  9075. else
  9076. $this->_tables[$name]=$table=$this->loadTable($realName);
  9077. if(isset($qcDuration)) // re-enable query caching
  9078. $this->_connection->queryCachingDuration=$qcDuration;
  9079. return $table;
  9080. }
  9081. }
  9082. public function getTables($schema='')
  9083. {
  9084. $tables=array();
  9085. foreach($this->getTableNames($schema) as $name)
  9086. {
  9087. if(($table=$this->getTable($name))!==null)
  9088. $tables[$name]=$table;
  9089. }
  9090. return $tables;
  9091. }
  9092. public function getTableNames($schema='')
  9093. {
  9094. if(!isset($this->_tableNames[$schema]))
  9095. $this->_tableNames[$schema]=$this->findTableNames($schema);
  9096. return $this->_tableNames[$schema];
  9097. }
  9098. public function getCommandBuilder()
  9099. {
  9100. if($this->_builder!==null)
  9101. return $this->_builder;
  9102. else
  9103. return $this->_builder=$this->createCommandBuilder();
  9104. }
  9105. public function refresh()
  9106. {
  9107. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  9108. {
  9109. foreach(array_keys($this->_tables) as $name)
  9110. {
  9111. if(!isset($this->_cacheExclude[$name]))
  9112. {
  9113. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  9114. $cache->delete($key);
  9115. }
  9116. }
  9117. }
  9118. $this->_tables=array();
  9119. $this->_tableNames=array();
  9120. $this->_builder=null;
  9121. }
  9122. public function quoteTableName($name)
  9123. {
  9124. if(strpos($name,'.')===false)
  9125. return $this->quoteSimpleTableName($name);
  9126. $parts=explode('.',$name);
  9127. foreach($parts as $i=>$part)
  9128. $parts[$i]=$this->quoteSimpleTableName($part);
  9129. return implode('.',$parts);
  9130. }
  9131. public function quoteSimpleTableName($name)
  9132. {
  9133. return "'".$name."'";
  9134. }
  9135. public function quoteColumnName($name)
  9136. {
  9137. if(($pos=strrpos($name,'.'))!==false)
  9138. {
  9139. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  9140. $name=substr($name,$pos+1);
  9141. }
  9142. else
  9143. $prefix='';
  9144. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  9145. }
  9146. public function quoteSimpleColumnName($name)
  9147. {
  9148. return '"'.$name.'"';
  9149. }
  9150. public function compareTableNames($name1,$name2)
  9151. {
  9152. $name1=str_replace(array('"','`',"'"),'',$name1);
  9153. $name2=str_replace(array('"','`',"'"),'',$name2);
  9154. if(($pos=strrpos($name1,'.'))!==false)
  9155. $name1=substr($name1,$pos+1);
  9156. if(($pos=strrpos($name2,'.'))!==false)
  9157. $name2=substr($name2,$pos+1);
  9158. if($this->_connection->tablePrefix!==null)
  9159. {
  9160. if(strpos($name1,'{')!==false)
  9161. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  9162. if(strpos($name2,'{')!==false)
  9163. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  9164. }
  9165. return $name1===$name2;
  9166. }
  9167. public function resetSequence($table,$value=null)
  9168. {
  9169. }
  9170. public function checkIntegrity($check=true,$schema='')
  9171. {
  9172. }
  9173. protected function createCommandBuilder()
  9174. {
  9175. return new CDbCommandBuilder($this);
  9176. }
  9177. protected function findTableNames($schema='')
  9178. {
  9179. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  9180. array('{class}'=>get_class($this))));
  9181. }
  9182. public function getColumnType($type)
  9183. {
  9184. if(isset($this->columnTypes[$type]))
  9185. return $this->columnTypes[$type];
  9186. elseif(($pos=strpos($type,' '))!==false)
  9187. {
  9188. $t=substr($type,0,$pos);
  9189. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  9190. }
  9191. else
  9192. return $type;
  9193. }
  9194. public function createTable($table,$columns,$options=null)
  9195. {
  9196. $cols=array();
  9197. foreach($columns as $name=>$type)
  9198. {
  9199. if(is_string($name))
  9200. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  9201. else
  9202. $cols[]="\t".$type;
  9203. }
  9204. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  9205. return $options===null ? $sql : $sql.' '.$options;
  9206. }
  9207. public function renameTable($table,$newName)
  9208. {
  9209. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  9210. }
  9211. public function dropTable($table)
  9212. {
  9213. return "DROP TABLE ".$this->quoteTableName($table);
  9214. }
  9215. public function truncateTable($table)
  9216. {
  9217. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  9218. }
  9219. public function addColumn($table,$column,$type)
  9220. {
  9221. return 'ALTER TABLE ' . $this->quoteTableName($table)
  9222. . ' ADD ' . $this->quoteColumnName($column) . ' '
  9223. . $this->getColumnType($type);
  9224. }
  9225. public function dropColumn($table,$column)
  9226. {
  9227. return "ALTER TABLE ".$this->quoteTableName($table)
  9228. ." DROP COLUMN ".$this->quoteColumnName($column);
  9229. }
  9230. public function renameColumn($table,$name,$newName)
  9231. {
  9232. return "ALTER TABLE ".$this->quoteTableName($table)
  9233. . " RENAME COLUMN ".$this->quoteColumnName($name)
  9234. . " TO ".$this->quoteColumnName($newName);
  9235. }
  9236. public function alterColumn($table,$column,$type)
  9237. {
  9238. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  9239. . $this->quoteColumnName($column) . ' '
  9240. . $this->quoteColumnName($column) . ' '
  9241. . $this->getColumnType($type);
  9242. }
  9243. public function addForeignKey($name,$table,$columns,$refTable,$refColumns,$delete=null,$update=null)
  9244. {
  9245. if(is_string($columns))
  9246. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9247. foreach($columns as $i=>$col)
  9248. $columns[$i]=$this->quoteColumnName($col);
  9249. if(is_string($refColumns))
  9250. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  9251. foreach($refColumns as $i=>$col)
  9252. $refColumns[$i]=$this->quoteColumnName($col);
  9253. $sql='ALTER TABLE '.$this->quoteTableName($table)
  9254. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  9255. .' FOREIGN KEY ('.implode(', ',$columns).')'
  9256. .' REFERENCES '.$this->quoteTableName($refTable)
  9257. .' ('.implode(', ',$refColumns).')';
  9258. if($delete!==null)
  9259. $sql.=' ON DELETE '.$delete;
  9260. if($update!==null)
  9261. $sql.=' ON UPDATE '.$update;
  9262. return $sql;
  9263. }
  9264. public function dropForeignKey($name,$table)
  9265. {
  9266. return 'ALTER TABLE '.$this->quoteTableName($table)
  9267. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  9268. }
  9269. public function createIndex($name,$table,$columns,$unique=false)
  9270. {
  9271. $cols=array();
  9272. if(is_string($columns))
  9273. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9274. foreach($columns as $col)
  9275. {
  9276. if(strpos($col,'(')!==false)
  9277. $cols[]=$col;
  9278. else
  9279. $cols[]=$this->quoteColumnName($col);
  9280. }
  9281. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  9282. . $this->quoteTableName($name).' ON '
  9283. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  9284. }
  9285. public function dropIndex($name,$table)
  9286. {
  9287. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  9288. }
  9289. public function addPrimaryKey($name,$table,$columns)
  9290. {
  9291. if(is_string($columns))
  9292. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9293. foreach($columns as $i=>$col)
  9294. $columns[$i]=$this->quoteColumnName($col);
  9295. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' ADD CONSTRAINT '
  9296. . $this->quoteColumnName($name) . ' PRIMARY KEY ('
  9297. . implode(', ',$columns). ' )';
  9298. }
  9299. public function dropPrimaryKey($name,$table)
  9300. {
  9301. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' DROP CONSTRAINT '
  9302. . $this->quoteColumnName($name);
  9303. }
  9304. }
  9305. class CSqliteSchema extends CDbSchema
  9306. {
  9307. public $columnTypes=array(
  9308. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  9309. 'bigpk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  9310. 'string' => 'varchar(255)',
  9311. 'text' => 'text',
  9312. 'integer' => 'integer',
  9313. 'bigint' => 'integer',
  9314. 'float' => 'float',
  9315. 'decimal' => 'decimal',
  9316. 'datetime' => 'datetime',
  9317. 'timestamp' => 'timestamp',
  9318. 'time' => 'time',
  9319. 'date' => 'date',
  9320. 'binary' => 'blob',
  9321. 'boolean' => 'tinyint(1)',
  9322. 'money' => 'decimal(19,4)',
  9323. );
  9324. public function resetSequence($table,$value=null)
  9325. {
  9326. if($table->sequenceName===null)
  9327. return;
  9328. if($value!==null)
  9329. $value=(int)($value)-1;
  9330. else
  9331. $value=(int)$this->getDbConnection()
  9332. ->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")
  9333. ->queryScalar();
  9334. try
  9335. {
  9336. // it's possible that 'sqlite_sequence' does not exist
  9337. $this->getDbConnection()
  9338. ->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")
  9339. ->execute();
  9340. }
  9341. catch(Exception $e)
  9342. {
  9343. }
  9344. }
  9345. public function checkIntegrity($check=true,$schema='')
  9346. {
  9347. $this->getDbConnection()->createCommand('PRAGMA foreign_keys='.(int)$check)->execute();
  9348. }
  9349. protected function findTableNames($schema='')
  9350. {
  9351. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  9352. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  9353. }
  9354. protected function createCommandBuilder()
  9355. {
  9356. return new CSqliteCommandBuilder($this);
  9357. }
  9358. protected function loadTable($name)
  9359. {
  9360. $table=new CDbTableSchema;
  9361. $table->name=$name;
  9362. $table->rawName=$this->quoteTableName($name);
  9363. if($this->findColumns($table))
  9364. {
  9365. $this->findConstraints($table);
  9366. return $table;
  9367. }
  9368. else
  9369. return null;
  9370. }
  9371. protected function findColumns($table)
  9372. {
  9373. $sql="PRAGMA table_info({$table->rawName})";
  9374. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  9375. if(empty($columns))
  9376. return false;
  9377. foreach($columns as $column)
  9378. {
  9379. $c=$this->createColumn($column);
  9380. $table->columns[$c->name]=$c;
  9381. if($c->isPrimaryKey)
  9382. {
  9383. if($table->primaryKey===null)
  9384. $table->primaryKey=$c->name;
  9385. elseif(is_string($table->primaryKey))
  9386. $table->primaryKey=array($table->primaryKey,$c->name);
  9387. else
  9388. $table->primaryKey[]=$c->name;
  9389. }
  9390. }
  9391. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  9392. {
  9393. $table->sequenceName='';
  9394. $table->columns[$table->primaryKey]->autoIncrement=true;
  9395. }
  9396. return true;
  9397. }
  9398. protected function findConstraints($table)
  9399. {
  9400. $foreignKeys=array();
  9401. $sql="PRAGMA foreign_key_list({$table->rawName})";
  9402. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  9403. foreach($keys as $key)
  9404. {
  9405. $column=$table->columns[$key['from']];
  9406. $column->isForeignKey=true;
  9407. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  9408. }
  9409. $table->foreignKeys=$foreignKeys;
  9410. }
  9411. protected function createColumn($column)
  9412. {
  9413. $c=new CSqliteColumnSchema;
  9414. $c->name=$column['name'];
  9415. $c->rawName=$this->quoteColumnName($c->name);
  9416. $c->allowNull=!$column['notnull'];
  9417. $c->isPrimaryKey=$column['pk']!=0;
  9418. $c->isForeignKey=false;
  9419. $c->comment=null; // SQLite does not support column comments at all
  9420. $c->init(strtolower($column['type']),$column['dflt_value']);
  9421. return $c;
  9422. }
  9423. public function renameTable($table, $newName)
  9424. {
  9425. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' RENAME TO ' . $this->quoteTableName($newName);
  9426. }
  9427. public function truncateTable($table)
  9428. {
  9429. return "DELETE FROM ".$this->quoteTableName($table);
  9430. }
  9431. public function dropColumn($table, $column)
  9432. {
  9433. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  9434. }
  9435. public function renameColumn($table, $name, $newName)
  9436. {
  9437. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  9438. }
  9439. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9440. {
  9441. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  9442. }
  9443. public function dropForeignKey($name, $table)
  9444. {
  9445. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  9446. }
  9447. public function alterColumn($table, $column, $type)
  9448. {
  9449. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  9450. }
  9451. public function dropIndex($name, $table)
  9452. {
  9453. return 'DROP INDEX '.$this->quoteTableName($name);
  9454. }
  9455. public function addPrimaryKey($name,$table,$columns)
  9456. {
  9457. throw new CDbException(Yii::t('yii', 'Adding a primary key after table has been created is not supported by SQLite.'));
  9458. }
  9459. public function dropPrimaryKey($name,$table)
  9460. {
  9461. throw new CDbException(Yii::t('yii', 'Removing a primary key after table has been created is not supported by SQLite.'));
  9462. }
  9463. }
  9464. class CDbTableSchema extends CComponent
  9465. {
  9466. public $name;
  9467. public $rawName;
  9468. public $primaryKey;
  9469. public $sequenceName;
  9470. public $foreignKeys=array();
  9471. public $columns=array();
  9472. public function getColumn($name)
  9473. {
  9474. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  9475. }
  9476. public function getColumnNames()
  9477. {
  9478. return array_keys($this->columns);
  9479. }
  9480. }
  9481. class CDbCommand extends CComponent
  9482. {
  9483. public $params=array();
  9484. private $_connection;
  9485. private $_text;
  9486. private $_statement;
  9487. private $_paramLog=array();
  9488. private $_query;
  9489. private $_fetchMode = array(PDO::FETCH_ASSOC);
  9490. public function __construct(CDbConnection $connection,$query=null)
  9491. {
  9492. $this->_connection=$connection;
  9493. if(is_array($query))
  9494. {
  9495. foreach($query as $name=>$value)
  9496. $this->$name=$value;
  9497. }
  9498. else
  9499. $this->setText($query);
  9500. }
  9501. public function __sleep()
  9502. {
  9503. $this->_statement=null;
  9504. return array_keys(get_object_vars($this));
  9505. }
  9506. public function setFetchMode($mode)
  9507. {
  9508. $params=func_get_args();
  9509. $this->_fetchMode = $params;
  9510. return $this;
  9511. }
  9512. public function reset()
  9513. {
  9514. $this->_text=null;
  9515. $this->_query=null;
  9516. $this->_statement=null;
  9517. $this->_paramLog=array();
  9518. $this->params=array();
  9519. return $this;
  9520. }
  9521. public function getText()
  9522. {
  9523. if($this->_text=='' && !empty($this->_query))
  9524. $this->setText($this->buildQuery($this->_query));
  9525. return $this->_text;
  9526. }
  9527. public function setText($value)
  9528. {
  9529. if($this->_connection->tablePrefix!==null && $value!='')
  9530. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  9531. else
  9532. $this->_text=$value;
  9533. $this->cancel();
  9534. return $this;
  9535. }
  9536. public function getConnection()
  9537. {
  9538. return $this->_connection;
  9539. }
  9540. public function getPdoStatement()
  9541. {
  9542. return $this->_statement;
  9543. }
  9544. public function prepare()
  9545. {
  9546. if($this->_statement==null)
  9547. {
  9548. try
  9549. {
  9550. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  9551. $this->_paramLog=array();
  9552. }
  9553. catch(Exception $e)
  9554. {
  9555. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9556. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9557. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  9558. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  9559. }
  9560. }
  9561. }
  9562. public function cancel()
  9563. {
  9564. $this->_statement=null;
  9565. }
  9566. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  9567. {
  9568. $this->prepare();
  9569. if($dataType===null)
  9570. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  9571. elseif($length===null)
  9572. $this->_statement->bindParam($name,$value,$dataType);
  9573. elseif($driverOptions===null)
  9574. $this->_statement->bindParam($name,$value,$dataType,$length);
  9575. else
  9576. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  9577. $this->_paramLog[$name]=&$value;
  9578. return $this;
  9579. }
  9580. public function bindValue($name, $value, $dataType=null)
  9581. {
  9582. $this->prepare();
  9583. if($dataType===null)
  9584. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  9585. else
  9586. $this->_statement->bindValue($name,$value,$dataType);
  9587. $this->_paramLog[$name]=$value;
  9588. return $this;
  9589. }
  9590. public function bindValues($values)
  9591. {
  9592. $this->prepare();
  9593. foreach($values as $name=>$value)
  9594. {
  9595. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  9596. $this->_paramLog[$name]=$value;
  9597. }
  9598. return $this;
  9599. }
  9600. public function execute($params=array())
  9601. {
  9602. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  9603. {
  9604. $p=array();
  9605. foreach($pars as $name=>$value)
  9606. $p[$name]=$name.'='.var_export($value,true);
  9607. $par='. Bound with ' .implode(', ',$p);
  9608. }
  9609. else
  9610. $par='';
  9611. try
  9612. {
  9613. if($this->_connection->enableProfiling)
  9614. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9615. $this->prepare();
  9616. if($params===array())
  9617. $this->_statement->execute();
  9618. else
  9619. $this->_statement->execute($params);
  9620. $n=$this->_statement->rowCount();
  9621. if($this->_connection->enableProfiling)
  9622. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9623. return $n;
  9624. }
  9625. catch(Exception $e)
  9626. {
  9627. if($this->_connection->enableProfiling)
  9628. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9629. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9630. $message=$e->getMessage();
  9631. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  9632. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9633. if(YII_DEBUG)
  9634. $message.='. The SQL statement executed was: '.$this->getText().$par;
  9635. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  9636. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  9637. }
  9638. }
  9639. public function query($params=array())
  9640. {
  9641. return $this->queryInternal('',0,$params);
  9642. }
  9643. public function queryAll($fetchAssociative=true,$params=array())
  9644. {
  9645. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  9646. }
  9647. public function queryRow($fetchAssociative=true,$params=array())
  9648. {
  9649. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  9650. }
  9651. public function queryScalar($params=array())
  9652. {
  9653. $result=$this->queryInternal('fetchColumn',0,$params);
  9654. if(is_resource($result) && get_resource_type($result)==='stream')
  9655. return stream_get_contents($result);
  9656. else
  9657. return $result;
  9658. }
  9659. public function queryColumn($params=array())
  9660. {
  9661. return $this->queryInternal('fetchAll',array(PDO::FETCH_COLUMN, 0),$params);
  9662. }
  9663. private function queryInternal($method,$mode,$params=array())
  9664. {
  9665. $params=array_merge($this->params,$params);
  9666. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  9667. {
  9668. $p=array();
  9669. foreach($pars as $name=>$value)
  9670. $p[$name]=$name.'='.var_export($value,true);
  9671. $par='. Bound with '.implode(', ',$p);
  9672. }
  9673. else
  9674. $par='';
  9675. if($this->_connection->queryCachingCount>0 && $method!==''
  9676. && $this->_connection->queryCachingDuration>0
  9677. && $this->_connection->queryCacheID!==false
  9678. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  9679. {
  9680. $this->_connection->queryCachingCount--;
  9681. $cacheKey='yii:dbquery'.':'.$method.':'.$this->_connection->connectionString.':'.$this->_connection->username;
  9682. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  9683. if(($result=$cache->get($cacheKey))!==false)
  9684. {
  9685. return $result[0];
  9686. }
  9687. }
  9688. try
  9689. {
  9690. if($this->_connection->enableProfiling)
  9691. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9692. $this->prepare();
  9693. if($params===array())
  9694. $this->_statement->execute();
  9695. else
  9696. $this->_statement->execute($params);
  9697. if($method==='')
  9698. $result=new CDbDataReader($this);
  9699. else
  9700. {
  9701. $mode=(array)$mode;
  9702. call_user_func_array(array($this->_statement, 'setFetchMode'), $mode);
  9703. $result=$this->_statement->$method();
  9704. $this->_statement->closeCursor();
  9705. }
  9706. if($this->_connection->enableProfiling)
  9707. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9708. if(isset($cache,$cacheKey))
  9709. $cache->set($cacheKey, array($result), $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  9710. return $result;
  9711. }
  9712. catch(Exception $e)
  9713. {
  9714. if($this->_connection->enableProfiling)
  9715. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9716. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9717. $message=$e->getMessage();
  9718. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  9719. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9720. if(YII_DEBUG)
  9721. $message.='. The SQL statement executed was: '.$this->getText().$par;
  9722. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  9723. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  9724. }
  9725. }
  9726. public function buildQuery($query)
  9727. {
  9728. $sql=!empty($query['distinct']) ? 'SELECT DISTINCT' : 'SELECT';
  9729. $sql.=' '.(!empty($query['select']) ? $query['select'] : '*');
  9730. if(!empty($query['from']))
  9731. $sql.="\nFROM ".$query['from'];
  9732. if(!empty($query['join']))
  9733. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  9734. if(!empty($query['where']))
  9735. $sql.="\nWHERE ".$query['where'];
  9736. if(!empty($query['group']))
  9737. $sql.="\nGROUP BY ".$query['group'];
  9738. if(!empty($query['having']))
  9739. $sql.="\nHAVING ".$query['having'];
  9740. if(!empty($query['union']))
  9741. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  9742. if(!empty($query['order']))
  9743. $sql.="\nORDER BY ".$query['order'];
  9744. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  9745. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  9746. if($limit>=0 || $offset>0)
  9747. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  9748. return $sql;
  9749. }
  9750. public function select($columns='*', $option='')
  9751. {
  9752. if(is_string($columns) && strpos($columns,'(')!==false)
  9753. $this->_query['select']=$columns;
  9754. else
  9755. {
  9756. if(!is_array($columns))
  9757. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9758. foreach($columns as $i=>$column)
  9759. {
  9760. if(is_object($column))
  9761. $columns[$i]=(string)$column;
  9762. elseif(strpos($column,'(')===false)
  9763. {
  9764. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  9765. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  9766. else
  9767. $columns[$i]=$this->_connection->quoteColumnName($column);
  9768. }
  9769. }
  9770. $this->_query['select']=implode(', ',$columns);
  9771. }
  9772. if($option!='')
  9773. $this->_query['select']=$option.' '.$this->_query['select'];
  9774. return $this;
  9775. }
  9776. public function getSelect()
  9777. {
  9778. return isset($this->_query['select']) ? $this->_query['select'] : '';
  9779. }
  9780. public function setSelect($value)
  9781. {
  9782. $this->select($value);
  9783. }
  9784. public function selectDistinct($columns='*')
  9785. {
  9786. $this->_query['distinct']=true;
  9787. return $this->select($columns);
  9788. }
  9789. public function getDistinct()
  9790. {
  9791. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  9792. }
  9793. public function setDistinct($value)
  9794. {
  9795. $this->_query['distinct']=$value;
  9796. }
  9797. public function from($tables)
  9798. {
  9799. if(is_string($tables) && strpos($tables,'(')!==false)
  9800. $this->_query['from']=$tables;
  9801. else
  9802. {
  9803. if(!is_array($tables))
  9804. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  9805. foreach($tables as $i=>$table)
  9806. {
  9807. if(strpos($table,'(')===false)
  9808. {
  9809. if(preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/',$table,$matches)) // with alias
  9810. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9811. else
  9812. $tables[$i]=$this->_connection->quoteTableName($table);
  9813. }
  9814. }
  9815. $this->_query['from']=implode(', ',$tables);
  9816. }
  9817. return $this;
  9818. }
  9819. public function getFrom()
  9820. {
  9821. return isset($this->_query['from']) ? $this->_query['from'] : '';
  9822. }
  9823. public function setFrom($value)
  9824. {
  9825. $this->from($value);
  9826. }
  9827. public function where($conditions, $params=array())
  9828. {
  9829. $this->_query['where']=$this->processConditions($conditions);
  9830. foreach($params as $name=>$value)
  9831. $this->params[$name]=$value;
  9832. return $this;
  9833. }
  9834. public function andWhere($conditions,$params=array())
  9835. {
  9836. if(isset($this->_query['where']))
  9837. $this->_query['where']=$this->processConditions(array('AND',$this->_query['where'],$conditions));
  9838. else
  9839. $this->_query['where']=$this->processConditions($conditions);
  9840. foreach($params as $name=>$value)
  9841. $this->params[$name]=$value;
  9842. return $this;
  9843. }
  9844. public function orWhere($conditions,$params=array())
  9845. {
  9846. if(isset($this->_query['where']))
  9847. $this->_query['where']=$this->processConditions(array('OR',$this->_query['where'],$conditions));
  9848. else
  9849. $this->_query['where']=$this->processConditions($conditions);
  9850. foreach($params as $name=>$value)
  9851. $this->params[$name]=$value;
  9852. return $this;
  9853. }
  9854. public function getWhere()
  9855. {
  9856. return isset($this->_query['where']) ? $this->_query['where'] : '';
  9857. }
  9858. public function setWhere($value)
  9859. {
  9860. $this->where($value);
  9861. }
  9862. public function join($table, $conditions, $params=array())
  9863. {
  9864. return $this->joinInternal('join', $table, $conditions, $params);
  9865. }
  9866. public function getJoin()
  9867. {
  9868. return isset($this->_query['join']) ? $this->_query['join'] : '';
  9869. }
  9870. public function setJoin($value)
  9871. {
  9872. $this->_query['join']=$value;
  9873. }
  9874. public function leftJoin($table, $conditions, $params=array())
  9875. {
  9876. return $this->joinInternal('left join', $table, $conditions, $params);
  9877. }
  9878. public function rightJoin($table, $conditions, $params=array())
  9879. {
  9880. return $this->joinInternal('right join', $table, $conditions, $params);
  9881. }
  9882. public function crossJoin($table)
  9883. {
  9884. return $this->joinInternal('cross join', $table);
  9885. }
  9886. public function naturalJoin($table)
  9887. {
  9888. return $this->joinInternal('natural join', $table);
  9889. }
  9890. public function naturalLeftJoin($table)
  9891. {
  9892. return $this->joinInternal('natural left join', $table);
  9893. }
  9894. public function naturalRightJoin($table)
  9895. {
  9896. return $this->joinInternal('natural right join', $table);
  9897. }
  9898. public function group($columns)
  9899. {
  9900. if(is_string($columns) && strpos($columns,'(')!==false)
  9901. $this->_query['group']=$columns;
  9902. else
  9903. {
  9904. if(!is_array($columns))
  9905. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9906. foreach($columns as $i=>$column)
  9907. {
  9908. if(is_object($column))
  9909. $columns[$i]=(string)$column;
  9910. elseif(strpos($column,'(')===false)
  9911. $columns[$i]=$this->_connection->quoteColumnName($column);
  9912. }
  9913. $this->_query['group']=implode(', ',$columns);
  9914. }
  9915. return $this;
  9916. }
  9917. public function getGroup()
  9918. {
  9919. return isset($this->_query['group']) ? $this->_query['group'] : '';
  9920. }
  9921. public function setGroup($value)
  9922. {
  9923. $this->group($value);
  9924. }
  9925. public function having($conditions, $params=array())
  9926. {
  9927. $this->_query['having']=$this->processConditions($conditions);
  9928. foreach($params as $name=>$value)
  9929. $this->params[$name]=$value;
  9930. return $this;
  9931. }
  9932. public function getHaving()
  9933. {
  9934. return isset($this->_query['having']) ? $this->_query['having'] : '';
  9935. }
  9936. public function setHaving($value)
  9937. {
  9938. $this->having($value);
  9939. }
  9940. public function order($columns)
  9941. {
  9942. if(is_string($columns) && strpos($columns,'(')!==false)
  9943. $this->_query['order']=$columns;
  9944. else
  9945. {
  9946. if(!is_array($columns))
  9947. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9948. foreach($columns as $i=>$column)
  9949. {
  9950. if(is_object($column))
  9951. $columns[$i]=(string)$column;
  9952. elseif(strpos($column,'(')===false)
  9953. {
  9954. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  9955. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  9956. else
  9957. $columns[$i]=$this->_connection->quoteColumnName($column);
  9958. }
  9959. }
  9960. $this->_query['order']=implode(', ',$columns);
  9961. }
  9962. return $this;
  9963. }
  9964. public function getOrder()
  9965. {
  9966. return isset($this->_query['order']) ? $this->_query['order'] : '';
  9967. }
  9968. public function setOrder($value)
  9969. {
  9970. $this->order($value);
  9971. }
  9972. public function limit($limit, $offset=null)
  9973. {
  9974. $this->_query['limit']=(int)$limit;
  9975. if($offset!==null)
  9976. $this->offset($offset);
  9977. return $this;
  9978. }
  9979. public function getLimit()
  9980. {
  9981. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  9982. }
  9983. public function setLimit($value)
  9984. {
  9985. $this->limit($value);
  9986. }
  9987. public function offset($offset)
  9988. {
  9989. $this->_query['offset']=(int)$offset;
  9990. return $this;
  9991. }
  9992. public function getOffset()
  9993. {
  9994. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  9995. }
  9996. public function setOffset($value)
  9997. {
  9998. $this->offset($value);
  9999. }
  10000. public function union($sql)
  10001. {
  10002. if(isset($this->_query['union']) && is_string($this->_query['union']))
  10003. $this->_query['union']=array($this->_query['union']);
  10004. $this->_query['union'][]=$sql;
  10005. return $this;
  10006. }
  10007. public function getUnion()
  10008. {
  10009. return isset($this->_query['union']) ? $this->_query['union'] : '';
  10010. }
  10011. public function setUnion($value)
  10012. {
  10013. $this->_query['union']=$value;
  10014. }
  10015. public function insert($table, $columns)
  10016. {
  10017. $params=array();
  10018. $names=array();
  10019. $placeholders=array();
  10020. foreach($columns as $name=>$value)
  10021. {
  10022. $names[]=$this->_connection->quoteColumnName($name);
  10023. if($value instanceof CDbExpression)
  10024. {
  10025. $placeholders[] = $value->expression;
  10026. foreach($value->params as $n => $v)
  10027. $params[$n] = $v;
  10028. }
  10029. else
  10030. {
  10031. $placeholders[] = ':' . $name;
  10032. $params[':' . $name] = $value;
  10033. }
  10034. }
  10035. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  10036. . ' (' . implode(', ',$names) . ') VALUES ('
  10037. . implode(', ', $placeholders) . ')';
  10038. return $this->setText($sql)->execute($params);
  10039. }
  10040. public function update($table, $columns, $conditions='', $params=array())
  10041. {
  10042. $lines=array();
  10043. foreach($columns as $name=>$value)
  10044. {
  10045. if($value instanceof CDbExpression)
  10046. {
  10047. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  10048. foreach($value->params as $n => $v)
  10049. $params[$n] = $v;
  10050. }
  10051. else
  10052. {
  10053. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  10054. $params[':' . $name]=$value;
  10055. }
  10056. }
  10057. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  10058. if(($where=$this->processConditions($conditions))!='')
  10059. $sql.=' WHERE '.$where;
  10060. return $this->setText($sql)->execute($params);
  10061. }
  10062. public function delete($table, $conditions='', $params=array())
  10063. {
  10064. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  10065. if(($where=$this->processConditions($conditions))!='')
  10066. $sql.=' WHERE '.$where;
  10067. return $this->setText($sql)->execute($params);
  10068. }
  10069. public function createTable($table, $columns, $options=null)
  10070. {
  10071. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  10072. }
  10073. public function renameTable($table, $newName)
  10074. {
  10075. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  10076. }
  10077. public function dropTable($table)
  10078. {
  10079. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  10080. }
  10081. public function truncateTable($table)
  10082. {
  10083. $schema=$this->getConnection()->getSchema();
  10084. $n=$this->setText($schema->truncateTable($table))->execute();
  10085. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  10086. $schema->resetSequence($schema->getTable($table));
  10087. return $n;
  10088. }
  10089. public function addColumn($table, $column, $type)
  10090. {
  10091. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  10092. }
  10093. public function dropColumn($table, $column)
  10094. {
  10095. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  10096. }
  10097. public function renameColumn($table, $name, $newName)
  10098. {
  10099. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  10100. }
  10101. public function alterColumn($table, $column, $type)
  10102. {
  10103. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  10104. }
  10105. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  10106. {
  10107. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  10108. }
  10109. public function dropForeignKey($name, $table)
  10110. {
  10111. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  10112. }
  10113. public function createIndex($name, $table, $columns, $unique=false)
  10114. {
  10115. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $columns, $unique))->execute();
  10116. }
  10117. public function dropIndex($name, $table)
  10118. {
  10119. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  10120. }
  10121. private function processConditions($conditions)
  10122. {
  10123. if(!is_array($conditions))
  10124. return $conditions;
  10125. elseif($conditions===array())
  10126. return '';
  10127. $n=count($conditions);
  10128. $operator=strtoupper($conditions[0]);
  10129. if($operator==='OR' || $operator==='AND')
  10130. {
  10131. $parts=array();
  10132. for($i=1;$i<$n;++$i)
  10133. {
  10134. $condition=$this->processConditions($conditions[$i]);
  10135. if($condition!=='')
  10136. $parts[]='('.$condition.')';
  10137. }
  10138. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  10139. }
  10140. if(!isset($conditions[1],$conditions[2]))
  10141. return '';
  10142. $column=$conditions[1];
  10143. if(strpos($column,'(')===false)
  10144. $column=$this->_connection->quoteColumnName($column);
  10145. $values=$conditions[2];
  10146. if(!is_array($values))
  10147. $values=array($values);
  10148. if($operator==='IN' || $operator==='NOT IN')
  10149. {
  10150. if($values===array())
  10151. return $operator==='IN' ? '0=1' : '';
  10152. foreach($values as $i=>$value)
  10153. {
  10154. if(is_string($value))
  10155. $values[$i]=$this->_connection->quoteValue($value);
  10156. else
  10157. $values[$i]=(string)$value;
  10158. }
  10159. return $column.' '.$operator.' ('.implode(', ',$values).')';
  10160. }
  10161. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  10162. {
  10163. if($values===array())
  10164. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  10165. if($operator==='LIKE' || $operator==='NOT LIKE')
  10166. $andor=' AND ';
  10167. else
  10168. {
  10169. $andor=' OR ';
  10170. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  10171. }
  10172. $expressions=array();
  10173. foreach($values as $value)
  10174. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  10175. return implode($andor,$expressions);
  10176. }
  10177. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  10178. }
  10179. private function joinInternal($type, $table, $conditions='', $params=array())
  10180. {
  10181. if(strpos($table,'(')===false)
  10182. {
  10183. if(preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/',$table,$matches)) // with alias
  10184. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  10185. else
  10186. $table=$this->_connection->quoteTableName($table);
  10187. }
  10188. $conditions=$this->processConditions($conditions);
  10189. if($conditions!='')
  10190. $conditions=' ON '.$conditions;
  10191. if(isset($this->_query['join']) && is_string($this->_query['join']))
  10192. $this->_query['join']=array($this->_query['join']);
  10193. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  10194. foreach($params as $name=>$value)
  10195. $this->params[$name]=$value;
  10196. return $this;
  10197. }
  10198. public function addPrimaryKey($name,$table,$columns)
  10199. {
  10200. return $this->setText($this->getConnection()->getSchema()->addPrimaryKey($name,$table,$columns))->execute();
  10201. }
  10202. public function dropPrimaryKey($name,$table)
  10203. {
  10204. return $this->setText($this->getConnection()->getSchema()->dropPrimaryKey($name,$table))->execute();
  10205. }
  10206. }
  10207. class CDbColumnSchema extends CComponent
  10208. {
  10209. public $name;
  10210. public $rawName;
  10211. public $allowNull;
  10212. public $dbType;
  10213. public $type;
  10214. public $defaultValue;
  10215. public $size;
  10216. public $precision;
  10217. public $scale;
  10218. public $isPrimaryKey;
  10219. public $isForeignKey;
  10220. public $autoIncrement=false;
  10221. public $comment='';
  10222. public function init($dbType, $defaultValue)
  10223. {
  10224. $this->dbType=$dbType;
  10225. $this->extractType($dbType);
  10226. $this->extractLimit($dbType);
  10227. if($defaultValue!==null)
  10228. $this->extractDefault($defaultValue);
  10229. }
  10230. protected function extractType($dbType)
  10231. {
  10232. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  10233. $this->type='integer';
  10234. elseif(stripos($dbType,'bool')!==false)
  10235. $this->type='boolean';
  10236. elseif(preg_match('/(real|floa|doub)/i',$dbType))
  10237. $this->type='double';
  10238. else
  10239. $this->type='string';
  10240. }
  10241. protected function extractLimit($dbType)
  10242. {
  10243. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  10244. {
  10245. $values=explode(',',$matches[1]);
  10246. $this->size=$this->precision=(int)$values[0];
  10247. if(isset($values[1]))
  10248. $this->scale=(int)$values[1];
  10249. }
  10250. }
  10251. protected function extractDefault($defaultValue)
  10252. {
  10253. $this->defaultValue=$this->typecast($defaultValue);
  10254. }
  10255. public function typecast($value)
  10256. {
  10257. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  10258. return $value;
  10259. if($value==='' && $this->allowNull)
  10260. return $this->type==='string' ? '' : null;
  10261. switch($this->type)
  10262. {
  10263. case 'string': return (string)$value;
  10264. case 'integer': return (integer)$value;
  10265. case 'boolean': return (boolean)$value;
  10266. case 'double':
  10267. default: return $value;
  10268. }
  10269. }
  10270. }
  10271. class CSqliteColumnSchema extends CDbColumnSchema
  10272. {
  10273. protected function extractDefault($defaultValue)
  10274. {
  10275. if($this->dbType==='timestamp' && $defaultValue==='CURRENT_TIMESTAMP')
  10276. $this->defaultValue=null;
  10277. else
  10278. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  10279. if($this->type==='string' && $this->defaultValue!==null) // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  10280. $this->defaultValue=trim($this->defaultValue,"'\"");
  10281. }
  10282. }
  10283. abstract class CValidator extends CComponent
  10284. {
  10285. public static $builtInValidators=array(
  10286. 'required'=>'CRequiredValidator',
  10287. 'filter'=>'CFilterValidator',
  10288. 'match'=>'CRegularExpressionValidator',
  10289. 'email'=>'CEmailValidator',
  10290. 'url'=>'CUrlValidator',
  10291. 'unique'=>'CUniqueValidator',
  10292. 'compare'=>'CCompareValidator',
  10293. 'length'=>'CStringValidator',
  10294. 'in'=>'CRangeValidator',
  10295. 'numerical'=>'CNumberValidator',
  10296. 'captcha'=>'CCaptchaValidator',
  10297. 'type'=>'CTypeValidator',
  10298. 'file'=>'CFileValidator',
  10299. 'default'=>'CDefaultValueValidator',
  10300. 'exist'=>'CExistValidator',
  10301. 'boolean'=>'CBooleanValidator',
  10302. 'safe'=>'CSafeValidator',
  10303. 'unsafe'=>'CUnsafeValidator',
  10304. 'date'=>'CDateValidator',
  10305. );
  10306. public $attributes;
  10307. public $message;
  10308. public $skipOnError=false;
  10309. public $on;
  10310. public $except;
  10311. public $safe=true;
  10312. public $enableClientValidation=true;
  10313. abstract protected function validateAttribute($object,$attribute);
  10314. public static function createValidator($name,$object,$attributes,$params=array())
  10315. {
  10316. if(is_string($attributes))
  10317. $attributes=preg_split('/\s*,\s*/',trim($attributes, " \t\n\r\0\x0B,"),-1,PREG_SPLIT_NO_EMPTY);
  10318. if(isset($params['on']))
  10319. {
  10320. if(is_array($params['on']))
  10321. $on=$params['on'];
  10322. else
  10323. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  10324. }
  10325. else
  10326. $on=array();
  10327. if(isset($params['except']))
  10328. {
  10329. if(is_array($params['except']))
  10330. $except=$params['except'];
  10331. else
  10332. $except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
  10333. }
  10334. else
  10335. $except=array();
  10336. if(method_exists($object,$name))
  10337. {
  10338. $validator=new CInlineValidator;
  10339. $validator->attributes=$attributes;
  10340. $validator->method=$name;
  10341. if(isset($params['clientValidate']))
  10342. {
  10343. $validator->clientValidate=$params['clientValidate'];
  10344. unset($params['clientValidate']);
  10345. }
  10346. $validator->params=$params;
  10347. if(isset($params['skipOnError']))
  10348. $validator->skipOnError=$params['skipOnError'];
  10349. }
  10350. else
  10351. {
  10352. $params['attributes']=$attributes;
  10353. if(isset(self::$builtInValidators[$name]))
  10354. $className=Yii::import(self::$builtInValidators[$name],true);
  10355. else
  10356. $className=Yii::import($name,true);
  10357. $validator=new $className;
  10358. foreach($params as $name=>$value)
  10359. $validator->$name=$value;
  10360. }
  10361. $validator->on=empty($on) ? array() : array_combine($on,$on);
  10362. $validator->except=empty($except) ? array() : array_combine($except,$except);
  10363. return $validator;
  10364. }
  10365. public function validate($object,$attributes=null)
  10366. {
  10367. if(is_array($attributes))
  10368. $attributes=array_intersect($this->attributes,$attributes);
  10369. else
  10370. $attributes=$this->attributes;
  10371. foreach($attributes as $attribute)
  10372. {
  10373. if(!$this->skipOnError || !$object->hasErrors($attribute))
  10374. $this->validateAttribute($object,$attribute);
  10375. }
  10376. }
  10377. public function clientValidateAttribute($object,$attribute)
  10378. {
  10379. }
  10380. public function applyTo($scenario)
  10381. {
  10382. if(isset($this->except[$scenario]))
  10383. return false;
  10384. return empty($this->on) || isset($this->on[$scenario]);
  10385. }
  10386. protected function addError($object,$attribute,$message,$params=array())
  10387. {
  10388. $params['{attribute}']=$object->getAttributeLabel($attribute);
  10389. $object->addError($attribute,strtr($message,$params));
  10390. }
  10391. protected function isEmpty($value,$trim=false)
  10392. {
  10393. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  10394. }
  10395. }
  10396. class CStringValidator extends CValidator
  10397. {
  10398. public $max;
  10399. public $min;
  10400. public $is;
  10401. public $tooShort;
  10402. public $tooLong;
  10403. public $allowEmpty=true;
  10404. public $encoding;
  10405. protected function validateAttribute($object,$attribute)
  10406. {
  10407. $value=$object->$attribute;
  10408. if($this->allowEmpty && $this->isEmpty($value))
  10409. return;
  10410. if(is_array($value))
  10411. {
  10412. // https://github.com/yiisoft/yii/issues/1955
  10413. $this->addError($object,$attribute,Yii::t('yii','{attribute} is invalid.'));
  10414. return;
  10415. }
  10416. if(function_exists('mb_strlen') && $this->encoding!==false)
  10417. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  10418. else
  10419. $length=strlen($value);
  10420. if($this->min!==null && $length<$this->min)
  10421. {
  10422. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  10423. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  10424. }
  10425. if($this->max!==null && $length>$this->max)
  10426. {
  10427. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  10428. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  10429. }
  10430. if($this->is!==null && $length!==$this->is)
  10431. {
  10432. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  10433. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  10434. }
  10435. }
  10436. public function clientValidateAttribute($object,$attribute)
  10437. {
  10438. $label=$object->getAttributeLabel($attribute);
  10439. if(($message=$this->message)===null)
  10440. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  10441. $message=strtr($message, array(
  10442. '{attribute}'=>$label,
  10443. '{length}'=>$this->is,
  10444. ));
  10445. if(($tooShort=$this->tooShort)===null)
  10446. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  10447. $tooShort=strtr($tooShort, array(
  10448. '{attribute}'=>$label,
  10449. '{min}'=>$this->min,
  10450. ));
  10451. if(($tooLong=$this->tooLong)===null)
  10452. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  10453. $tooLong=strtr($tooLong, array(
  10454. '{attribute}'=>$label,
  10455. '{max}'=>$this->max,
  10456. ));
  10457. $js='';
  10458. if($this->min!==null)
  10459. {
  10460. $js.="
  10461. if(value.length<{$this->min}) {
  10462. messages.push(".CJSON::encode($tooShort).");
  10463. }
  10464. ";
  10465. }
  10466. if($this->max!==null)
  10467. {
  10468. $js.="
  10469. if(value.length>{$this->max}) {
  10470. messages.push(".CJSON::encode($tooLong).");
  10471. }
  10472. ";
  10473. }
  10474. if($this->is!==null)
  10475. {
  10476. $js.="
  10477. if(value.length!={$this->is}) {
  10478. messages.push(".CJSON::encode($message).");
  10479. }
  10480. ";
  10481. }
  10482. if($this->allowEmpty)
  10483. {
  10484. $js="
  10485. if(jQuery.trim(value)!='') {
  10486. $js
  10487. }
  10488. ";
  10489. }
  10490. return $js;
  10491. }
  10492. }
  10493. class CRequiredValidator extends CValidator
  10494. {
  10495. public $requiredValue;
  10496. public $strict=false;
  10497. public $trim=true;
  10498. protected function validateAttribute($object,$attribute)
  10499. {
  10500. $value=$object->$attribute;
  10501. if($this->requiredValue!==null)
  10502. {
  10503. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  10504. {
  10505. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  10506. array('{value}'=>$this->requiredValue));
  10507. $this->addError($object,$attribute,$message);
  10508. }
  10509. }
  10510. elseif($this->isEmpty($value,$this->trim))
  10511. {
  10512. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  10513. $this->addError($object,$attribute,$message);
  10514. }
  10515. }
  10516. public function clientValidateAttribute($object,$attribute)
  10517. {
  10518. $message=$this->message;
  10519. if($this->requiredValue!==null)
  10520. {
  10521. if($message===null)
  10522. $message=Yii::t('yii','{attribute} must be {value}.');
  10523. $message=strtr($message, array(
  10524. '{value}'=>$this->requiredValue,
  10525. '{attribute}'=>$object->getAttributeLabel($attribute),
  10526. ));
  10527. return "
  10528. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  10529. messages.push(".CJSON::encode($message).");
  10530. }
  10531. ";
  10532. }
  10533. else
  10534. {
  10535. if($message===null)
  10536. $message=Yii::t('yii','{attribute} cannot be blank.');
  10537. $message=strtr($message, array(
  10538. '{attribute}'=>$object->getAttributeLabel($attribute),
  10539. ));
  10540. if($this->trim)
  10541. $emptyCondition = "jQuery.trim(value)==''";
  10542. else
  10543. $emptyCondition = "value==''";
  10544. return "
  10545. if({$emptyCondition}) {
  10546. messages.push(".CJSON::encode($message).");
  10547. }
  10548. ";
  10549. }
  10550. }
  10551. }
  10552. class CNumberValidator extends CValidator
  10553. {
  10554. public $integerOnly=false;
  10555. public $allowEmpty=true;
  10556. public $max;
  10557. public $min;
  10558. public $tooBig;
  10559. public $tooSmall;
  10560. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  10561. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  10562. protected function validateAttribute($object,$attribute)
  10563. {
  10564. $value=$object->$attribute;
  10565. if($this->allowEmpty && $this->isEmpty($value))
  10566. return;
  10567. if(!is_numeric($value))
  10568. {
  10569. // https://github.com/yiisoft/yii/issues/1955
  10570. // https://github.com/yiisoft/yii/issues/1669
  10571. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  10572. $this->addError($object,$attribute,$message);
  10573. return;
  10574. }
  10575. if($this->integerOnly)
  10576. {
  10577. if(!preg_match($this->integerPattern,"$value"))
  10578. {
  10579. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  10580. $this->addError($object,$attribute,$message);
  10581. }
  10582. }
  10583. else
  10584. {
  10585. if(!preg_match($this->numberPattern,"$value"))
  10586. {
  10587. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  10588. $this->addError($object,$attribute,$message);
  10589. }
  10590. }
  10591. if($this->min!==null && $value<$this->min)
  10592. {
  10593. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  10594. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  10595. }
  10596. if($this->max!==null && $value>$this->max)
  10597. {
  10598. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  10599. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  10600. }
  10601. }
  10602. public function clientValidateAttribute($object,$attribute)
  10603. {
  10604. $label=$object->getAttributeLabel($attribute);
  10605. if(($message=$this->message)===null)
  10606. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  10607. $message=strtr($message, array(
  10608. '{attribute}'=>$label,
  10609. ));
  10610. if(($tooBig=$this->tooBig)===null)
  10611. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  10612. $tooBig=strtr($tooBig, array(
  10613. '{attribute}'=>$label,
  10614. '{max}'=>$this->max,
  10615. ));
  10616. if(($tooSmall=$this->tooSmall)===null)
  10617. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  10618. $tooSmall=strtr($tooSmall, array(
  10619. '{attribute}'=>$label,
  10620. '{min}'=>$this->min,
  10621. ));
  10622. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  10623. $js="
  10624. if(!value.match($pattern)) {
  10625. messages.push(".CJSON::encode($message).");
  10626. }
  10627. ";
  10628. if($this->min!==null)
  10629. {
  10630. $js.="
  10631. if(value<{$this->min}) {
  10632. messages.push(".CJSON::encode($tooSmall).");
  10633. }
  10634. ";
  10635. }
  10636. if($this->max!==null)
  10637. {
  10638. $js.="
  10639. if(value>{$this->max}) {
  10640. messages.push(".CJSON::encode($tooBig).");
  10641. }
  10642. ";
  10643. }
  10644. if($this->allowEmpty)
  10645. {
  10646. $js="
  10647. if(jQuery.trim(value)!='') {
  10648. $js
  10649. }
  10650. ";
  10651. }
  10652. return $js;
  10653. }
  10654. }
  10655. class CListIterator implements Iterator
  10656. {
  10657. private $_d;
  10658. private $_i;
  10659. public function __construct(&$data)
  10660. {
  10661. $this->_d=&$data;
  10662. $this->_i=0;
  10663. }
  10664. public function rewind()
  10665. {
  10666. $this->_i=0;
  10667. }
  10668. public function key()
  10669. {
  10670. return $this->_i;
  10671. }
  10672. public function current()
  10673. {
  10674. return $this->_d[$this->_i];
  10675. }
  10676. public function next()
  10677. {
  10678. $this->_i++;
  10679. }
  10680. public function valid()
  10681. {
  10682. return $this->_i<count($this->_d);
  10683. }
  10684. }
  10685. interface IApplicationComponent
  10686. {
  10687. public function init();
  10688. public function getIsInitialized();
  10689. }
  10690. interface ICache
  10691. {
  10692. public function get($id);
  10693. public function mget($ids);
  10694. public function set($id,$value,$expire=0,$dependency=null);
  10695. public function add($id,$value,$expire=0,$dependency=null);
  10696. public function delete($id);
  10697. public function flush();
  10698. }
  10699. interface ICacheDependency
  10700. {
  10701. public function evaluateDependency();
  10702. public function getHasChanged();
  10703. }
  10704. interface IStatePersister
  10705. {
  10706. public function load();
  10707. public function save($state);
  10708. }
  10709. interface IFilter
  10710. {
  10711. public function filter($filterChain);
  10712. }
  10713. interface IAction
  10714. {
  10715. public function getId();
  10716. public function getController();
  10717. }
  10718. interface IWebServiceProvider
  10719. {
  10720. public function beforeWebMethod($service);
  10721. public function afterWebMethod($service);
  10722. }
  10723. interface IViewRenderer
  10724. {
  10725. public function renderFile($context,$file,$data,$return);
  10726. }
  10727. interface IUserIdentity
  10728. {
  10729. public function authenticate();
  10730. public function getIsAuthenticated();
  10731. public function getId();
  10732. public function getName();
  10733. public function getPersistentStates();
  10734. }
  10735. interface IWebUser
  10736. {
  10737. public function getId();
  10738. public function getName();
  10739. public function getIsGuest();
  10740. public function checkAccess($operation,$params=array());
  10741. public function loginRequired();
  10742. }
  10743. interface IAuthManager
  10744. {
  10745. public function checkAccess($itemName,$userId,$params=array());
  10746. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  10747. public function removeAuthItem($name);
  10748. public function getAuthItems($type=null,$userId=null);
  10749. public function getAuthItem($name);
  10750. public function saveAuthItem($item,$oldName=null);
  10751. public function addItemChild($itemName,$childName);
  10752. public function removeItemChild($itemName,$childName);
  10753. public function hasItemChild($itemName,$childName);
  10754. public function getItemChildren($itemName);
  10755. public function assign($itemName,$userId,$bizRule=null,$data=null);
  10756. public function revoke($itemName,$userId);
  10757. public function isAssigned($itemName,$userId);
  10758. public function getAuthAssignment($itemName,$userId);
  10759. public function getAuthAssignments($userId);
  10760. public function saveAuthAssignment($assignment);
  10761. public function clearAll();
  10762. public function clearAuthAssignments();
  10763. public function save();
  10764. public function executeBizRule($bizRule,$params,$data);
  10765. }
  10766. interface IBehavior
  10767. {
  10768. public function attach($component);
  10769. public function detach($component);
  10770. public function getEnabled();
  10771. public function setEnabled($value);
  10772. }
  10773. interface IWidgetFactory
  10774. {
  10775. public function createWidget($owner,$className,$properties=array());
  10776. }
  10777. interface IDataProvider
  10778. {
  10779. public function getId();
  10780. public function getItemCount($refresh=false);
  10781. public function getTotalItemCount($refresh=false);
  10782. public function getData($refresh=false);
  10783. public function getKeys($refresh=false);
  10784. public function getSort();
  10785. public function getPagination();
  10786. }
  10787. interface ILogFilter
  10788. {
  10789. public function filter(&$logs);
  10790. }
  10791. ?>