PageRenderTime 112ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/yii/framework/yiilite.php

https://bitbucket.org/ddonthula/zurmo
PHP | 9814 lines | 9762 code | 2 blank | 50 comment | 742 complexity | 9520e0fa165bc53602c506c99869d23d MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, LGPL-3.0, LGPL-2.1, BSD-2-Clause
  1. <?php
  2. /**
  3. * Yii bootstrap file.
  4. *
  5. * This file is automatically generated using 'build lite' command.
  6. * It is the result of merging commonly used Yii class files with
  7. * comments and trace statements removed away.
  8. *
  9. * By using this file instead of yii.php, an Yii application may
  10. * improve performance due to the reduction of PHP parsing time.
  11. * The performance improvement is especially obvious when PHP APC extension
  12. * is enabled.
  13. *
  14. * DO NOT modify this file manually.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @link http://www.yiiframework.com/
  18. * @copyright Copyright &copy; 2008-2012 Yii Software LLC
  19. * @license http://www.yiiframework.com/license/
  20. * @version $Id: $
  21. * @since 1.0
  22. */
  23. defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME',microtime(true));
  24. defined('YII_DEBUG') or define('YII_DEBUG',false);
  25. defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',0);
  26. defined('YII_ENABLE_EXCEPTION_HANDLER') or define('YII_ENABLE_EXCEPTION_HANDLER',true);
  27. defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER',true);
  28. defined('YII_PATH') or define('YII_PATH',dirname(__FILE__));
  29. defined('YII_ZII_PATH') or define('YII_ZII_PATH',YII_PATH.DIRECTORY_SEPARATOR.'zii');
  30. class YiiBase
  31. {
  32. public static $classMap=array();
  33. public static $enableIncludePath=true;
  34. private static $_aliases=array('system'=>YII_PATH,'zii'=>YII_ZII_PATH); // alias => path
  35. private static $_imports=array(); // alias => class name or directory
  36. private static $_includePaths; // list of include paths
  37. private static $_app;
  38. private static $_logger;
  39. public static function getVersion()
  40. {
  41. return '1.1.12';
  42. }
  43. public static function createWebApplication($config=null)
  44. {
  45. return self::createApplication('CWebApplication',$config);
  46. }
  47. public static function createConsoleApplication($config=null)
  48. {
  49. return self::createApplication('CConsoleApplication',$config);
  50. }
  51. public static function createApplication($class,$config=null)
  52. {
  53. return new $class($config);
  54. }
  55. public static function app()
  56. {
  57. return self::$_app;
  58. }
  59. public static function setApplication($app)
  60. {
  61. if(self::$_app===null || $app===null)
  62. self::$_app=$app;
  63. else
  64. throw new CException(Yii::t('yii','Yii application can only be created once.'));
  65. }
  66. public static function getFrameworkPath()
  67. {
  68. return YII_PATH;
  69. }
  70. public static function createComponent($config)
  71. {
  72. if(is_string($config))
  73. {
  74. $type=$config;
  75. $config=array();
  76. }
  77. else if(isset($config['class']))
  78. {
  79. $type=$config['class'];
  80. unset($config['class']);
  81. }
  82. else
  83. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  84. if(!class_exists($type,false))
  85. $type=Yii::import($type,true);
  86. if(($n=func_num_args())>1)
  87. {
  88. $args=func_get_args();
  89. if($n===2)
  90. $object=new $type($args[1]);
  91. else if($n===3)
  92. $object=new $type($args[1],$args[2]);
  93. else if($n===4)
  94. $object=new $type($args[1],$args[2],$args[3]);
  95. else
  96. {
  97. unset($args[0]);
  98. $class=new ReflectionClass($type);
  99. // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
  100. // $object=$class->newInstanceArgs($args);
  101. $object=call_user_func_array(array($class,'newInstance'),$args);
  102. }
  103. }
  104. else
  105. $object=new $type;
  106. foreach($config as $key=>$value)
  107. $object->$key=$value;
  108. return $object;
  109. }
  110. public static function import($alias,$forceInclude=false)
  111. {
  112. if(isset(self::$_imports[$alias])) // previously imported
  113. return self::$_imports[$alias];
  114. if(class_exists($alias,false) || interface_exists($alias,false))
  115. return self::$_imports[$alias]=$alias;
  116. if(($pos=strrpos($alias,'\\'))!==false) // a class name in PHP 5.3 namespace format
  117. {
  118. $namespace=str_replace('\\','.',ltrim(substr($alias,0,$pos),'\\'));
  119. if(($path=self::getPathOfAlias($namespace))!==false)
  120. {
  121. $classFile=$path.DIRECTORY_SEPARATOR.substr($alias,$pos+1).'.php';
  122. if($forceInclude)
  123. {
  124. if(is_file($classFile))
  125. require($classFile);
  126. else
  127. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
  128. self::$_imports[$alias]=$alias;
  129. }
  130. else
  131. self::$classMap[$alias]=$classFile;
  132. return $alias;
  133. }
  134. else
  135. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory.',
  136. array('{alias}'=>$namespace)));
  137. }
  138. if(($pos=strrpos($alias,'.'))===false) // a simple class name
  139. {
  140. if($forceInclude && self::autoload($alias))
  141. self::$_imports[$alias]=$alias;
  142. return $alias;
  143. }
  144. $className=(string)substr($alias,$pos+1);
  145. $isClass=$className!=='*';
  146. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  147. return self::$_imports[$alias]=$className;
  148. if(($path=self::getPathOfAlias($alias))!==false)
  149. {
  150. if($isClass)
  151. {
  152. if($forceInclude)
  153. {
  154. if(is_file($path.'.php'))
  155. require($path.'.php');
  156. else
  157. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
  158. self::$_imports[$alias]=$className;
  159. }
  160. else
  161. self::$classMap[$className]=$path.'.php';
  162. return $className;
  163. }
  164. else // a directory
  165. {
  166. if(self::$_includePaths===null)
  167. {
  168. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  169. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  170. unset(self::$_includePaths[$pos]);
  171. }
  172. array_unshift(self::$_includePaths,$path);
  173. if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  174. self::$enableIncludePath=false;
  175. return self::$_imports[$alias]=$path;
  176. }
  177. }
  178. else
  179. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  180. array('{alias}'=>$alias)));
  181. }
  182. public static function getPathOfAlias($alias)
  183. {
  184. if(isset(self::$_aliases[$alias]))
  185. return self::$_aliases[$alias];
  186. else if(($pos=strpos($alias,'.'))!==false)
  187. {
  188. $rootAlias=substr($alias,0,$pos);
  189. if(isset(self::$_aliases[$rootAlias]))
  190. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  191. else if(self::$_app instanceof CWebApplication)
  192. {
  193. if(self::$_app->findModule($rootAlias)!==null)
  194. return self::getPathOfAlias($alias);
  195. }
  196. }
  197. return false;
  198. }
  199. public static function setPathOfAlias($alias,$path)
  200. {
  201. if(empty($path))
  202. unset(self::$_aliases[$alias]);
  203. else
  204. self::$_aliases[$alias]=rtrim($path,'\\/');
  205. }
  206. public static function autoload($className)
  207. {
  208. // use include so that the error PHP file may appear
  209. if(isset(self::$classMap[$className]))
  210. include(self::$classMap[$className]);
  211. else if(isset(self::$_coreClasses[$className]))
  212. include(YII_PATH.self::$_coreClasses[$className]);
  213. else
  214. {
  215. // include class file relying on include_path
  216. if(strpos($className,'\\')===false) // class without namespace
  217. {
  218. if(self::$enableIncludePath===false)
  219. {
  220. foreach(self::$_includePaths as $path)
  221. {
  222. $classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
  223. if(is_file($classFile))
  224. {
  225. include($classFile);
  226. if(YII_DEBUG && basename(realpath($classFile))!==$className.'.php')
  227. throw new CException(Yii::t('yii','Class name "{class}" does not match class file "{file}".', array(
  228. '{class}'=>$className,
  229. '{file}'=>$classFile,
  230. )));
  231. break;
  232. }
  233. }
  234. }
  235. else
  236. include($className.'.php');
  237. }
  238. else // class name with namespace in PHP 5.3
  239. {
  240. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  241. if(($path=self::getPathOfAlias($namespace))!==false)
  242. include($path.'.php');
  243. else
  244. return false;
  245. }
  246. return class_exists($className,false) || interface_exists($className,false);
  247. }
  248. return true;
  249. }
  250. public static function trace($msg,$category='application')
  251. {
  252. if(YII_DEBUG)
  253. self::log($msg,CLogger::LEVEL_TRACE,$category);
  254. }
  255. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  256. {
  257. if(self::$_logger===null)
  258. self::$_logger=new CLogger;
  259. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  260. {
  261. $traces=debug_backtrace();
  262. $count=0;
  263. foreach($traces as $trace)
  264. {
  265. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  266. {
  267. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  268. if(++$count>=YII_TRACE_LEVEL)
  269. break;
  270. }
  271. }
  272. }
  273. self::$_logger->log($msg,$level,$category);
  274. }
  275. public static function beginProfile($token,$category='application')
  276. {
  277. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  278. }
  279. public static function endProfile($token,$category='application')
  280. {
  281. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  282. }
  283. public static function getLogger()
  284. {
  285. if(self::$_logger!==null)
  286. return self::$_logger;
  287. else
  288. return self::$_logger=new CLogger;
  289. }
  290. public static function setLogger($logger)
  291. {
  292. self::$_logger=$logger;
  293. }
  294. public static function powered()
  295. {
  296. return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
  297. }
  298. public static function t($category,$message,$params=array(),$source=null,$language=null)
  299. {
  300. if(self::$_app!==null)
  301. {
  302. if($source===null)
  303. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  304. if(($source=self::$_app->getComponent($source))!==null)
  305. $message=$source->translate($category,$message,$language);
  306. }
  307. if($params===array())
  308. return $message;
  309. if(!is_array($params))
  310. $params=array($params);
  311. if(isset($params[0])) // number choice
  312. {
  313. if(strpos($message,'|')!==false)
  314. {
  315. if(strpos($message,'#')===false)
  316. {
  317. $chunks=explode('|',$message);
  318. $expressions=self::$_app->getLocale($language)->getPluralRules();
  319. if($n=min(count($chunks),count($expressions)))
  320. {
  321. for($i=0;$i<$n;$i++)
  322. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  323. $message=implode('|',$chunks);
  324. }
  325. }
  326. $message=CChoiceFormat::format($message,$params[0]);
  327. }
  328. if(!isset($params['{n}']))
  329. $params['{n}']=$params[0];
  330. unset($params[0]);
  331. }
  332. return $params!==array() ? strtr($message,$params) : $message;
  333. }
  334. public static function registerAutoloader($callback, $append=false)
  335. {
  336. if($append)
  337. {
  338. self::$enableIncludePath=false;
  339. spl_autoload_register($callback);
  340. }
  341. else
  342. {
  343. spl_autoload_unregister(array('YiiBase','autoload'));
  344. spl_autoload_register($callback);
  345. spl_autoload_register(array('YiiBase','autoload'));
  346. }
  347. }
  348. private static $_coreClasses=array(
  349. 'CApplication' => '/base/CApplication.php',
  350. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  351. 'CBehavior' => '/base/CBehavior.php',
  352. 'CComponent' => '/base/CComponent.php',
  353. 'CErrorEvent' => '/base/CErrorEvent.php',
  354. 'CErrorHandler' => '/base/CErrorHandler.php',
  355. 'CException' => '/base/CException.php',
  356. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  357. 'CHttpException' => '/base/CHttpException.php',
  358. 'CModel' => '/base/CModel.php',
  359. 'CModelBehavior' => '/base/CModelBehavior.php',
  360. 'CModelEvent' => '/base/CModelEvent.php',
  361. 'CModule' => '/base/CModule.php',
  362. 'CSecurityManager' => '/base/CSecurityManager.php',
  363. 'CStatePersister' => '/base/CStatePersister.php',
  364. 'CApcCache' => '/caching/CApcCache.php',
  365. 'CCache' => '/caching/CCache.php',
  366. 'CDbCache' => '/caching/CDbCache.php',
  367. 'CDummyCache' => '/caching/CDummyCache.php',
  368. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  369. 'CFileCache' => '/caching/CFileCache.php',
  370. 'CMemCache' => '/caching/CMemCache.php',
  371. 'CWinCache' => '/caching/CWinCache.php',
  372. 'CXCache' => '/caching/CXCache.php',
  373. 'CZendDataCache' => '/caching/CZendDataCache.php',
  374. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  375. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  376. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  377. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  378. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  379. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  380. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  381. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  382. 'CConfiguration' => '/collections/CConfiguration.php',
  383. 'CList' => '/collections/CList.php',
  384. 'CListIterator' => '/collections/CListIterator.php',
  385. 'CMap' => '/collections/CMap.php',
  386. 'CMapIterator' => '/collections/CMapIterator.php',
  387. 'CQueue' => '/collections/CQueue.php',
  388. 'CQueueIterator' => '/collections/CQueueIterator.php',
  389. 'CStack' => '/collections/CStack.php',
  390. 'CStackIterator' => '/collections/CStackIterator.php',
  391. 'CTypedList' => '/collections/CTypedList.php',
  392. 'CTypedMap' => '/collections/CTypedMap.php',
  393. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  394. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  395. 'CConsoleCommandBehavior' => '/console/CConsoleCommandBehavior.php',
  396. 'CConsoleCommandEvent' => '/console/CConsoleCommandEvent.php',
  397. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  398. 'CHelpCommand' => '/console/CHelpCommand.php',
  399. 'CDbCommand' => '/db/CDbCommand.php',
  400. 'CDbConnection' => '/db/CDbConnection.php',
  401. 'CDbDataReader' => '/db/CDbDataReader.php',
  402. 'CDbException' => '/db/CDbException.php',
  403. 'CDbMigration' => '/db/CDbMigration.php',
  404. 'CDbTransaction' => '/db/CDbTransaction.php',
  405. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  406. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  407. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  408. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  409. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  410. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  411. 'CDbExpression' => '/db/schema/CDbExpression.php',
  412. 'CDbSchema' => '/db/schema/CDbSchema.php',
  413. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  414. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  415. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  416. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  417. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  418. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  419. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  420. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  421. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  422. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  423. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  424. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  425. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  426. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  427. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  428. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  429. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  430. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  431. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  432. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  433. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  434. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  435. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  436. 'CLocale' => '/i18n/CLocale.php',
  437. 'CMessageSource' => '/i18n/CMessageSource.php',
  438. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  439. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  440. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  441. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  442. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  443. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  444. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  445. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  446. 'CLogFilter' => '/logging/CLogFilter.php',
  447. 'CLogRoute' => '/logging/CLogRoute.php',
  448. 'CLogRouter' => '/logging/CLogRouter.php',
  449. 'CLogger' => '/logging/CLogger.php',
  450. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  451. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  452. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  453. 'CFileHelper' => '/utils/CFileHelper.php',
  454. 'CFormatter' => '/utils/CFormatter.php',
  455. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  456. 'CPropertyValue' => '/utils/CPropertyValue.php',
  457. 'CTimestamp' => '/utils/CTimestamp.php',
  458. 'CVarDumper' => '/utils/CVarDumper.php',
  459. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  460. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  461. 'CCompareValidator' => '/validators/CCompareValidator.php',
  462. 'CDateValidator' => '/validators/CDateValidator.php',
  463. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  464. 'CEmailValidator' => '/validators/CEmailValidator.php',
  465. 'CExistValidator' => '/validators/CExistValidator.php',
  466. 'CFileValidator' => '/validators/CFileValidator.php',
  467. 'CFilterValidator' => '/validators/CFilterValidator.php',
  468. 'CInlineValidator' => '/validators/CInlineValidator.php',
  469. 'CNumberValidator' => '/validators/CNumberValidator.php',
  470. 'CRangeValidator' => '/validators/CRangeValidator.php',
  471. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  472. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  473. 'CSafeValidator' => '/validators/CSafeValidator.php',
  474. 'CStringValidator' => '/validators/CStringValidator.php',
  475. 'CTypeValidator' => '/validators/CTypeValidator.php',
  476. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  477. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  478. 'CUrlValidator' => '/validators/CUrlValidator.php',
  479. 'CValidator' => '/validators/CValidator.php',
  480. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  481. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  482. 'CAssetManager' => '/web/CAssetManager.php',
  483. 'CBaseController' => '/web/CBaseController.php',
  484. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  485. 'CClientScript' => '/web/CClientScript.php',
  486. 'CController' => '/web/CController.php',
  487. 'CDataProvider' => '/web/CDataProvider.php',
  488. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  489. 'CExtController' => '/web/CExtController.php',
  490. 'CFormModel' => '/web/CFormModel.php',
  491. 'CHttpCookie' => '/web/CHttpCookie.php',
  492. 'CHttpRequest' => '/web/CHttpRequest.php',
  493. 'CHttpSession' => '/web/CHttpSession.php',
  494. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  495. 'COutputEvent' => '/web/COutputEvent.php',
  496. 'CPagination' => '/web/CPagination.php',
  497. 'CSort' => '/web/CSort.php',
  498. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  499. 'CTheme' => '/web/CTheme.php',
  500. 'CThemeManager' => '/web/CThemeManager.php',
  501. 'CUploadedFile' => '/web/CUploadedFile.php',
  502. 'CUrlManager' => '/web/CUrlManager.php',
  503. 'CWebApplication' => '/web/CWebApplication.php',
  504. 'CWebModule' => '/web/CWebModule.php',
  505. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  506. 'CAction' => '/web/actions/CAction.php',
  507. 'CInlineAction' => '/web/actions/CInlineAction.php',
  508. 'CViewAction' => '/web/actions/CViewAction.php',
  509. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  510. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  511. 'CAuthItem' => '/web/auth/CAuthItem.php',
  512. 'CAuthManager' => '/web/auth/CAuthManager.php',
  513. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  514. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  515. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  516. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  517. 'CWebUser' => '/web/auth/CWebUser.php',
  518. 'CFilter' => '/web/filters/CFilter.php',
  519. 'CFilterChain' => '/web/filters/CFilterChain.php',
  520. 'CHttpCacheFilter' => '/web/filters/CHttpCacheFilter.php',
  521. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  522. 'CForm' => '/web/form/CForm.php',
  523. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  524. 'CFormElement' => '/web/form/CFormElement.php',
  525. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  526. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  527. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  528. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  529. 'CHtml' => '/web/helpers/CHtml.php',
  530. 'CJSON' => '/web/helpers/CJSON.php',
  531. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  532. 'CJavaScriptExpression' => '/web/helpers/CJavaScriptExpression.php',
  533. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  534. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  535. 'CWebService' => '/web/services/CWebService.php',
  536. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  537. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  538. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  539. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  540. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  541. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  542. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  543. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  544. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  545. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  546. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  547. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  548. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  549. 'COutputCache' => '/web/widgets/COutputCache.php',
  550. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  551. 'CStarRating' => '/web/widgets/CStarRating.php',
  552. 'CTabView' => '/web/widgets/CTabView.php',
  553. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  554. 'CTreeView' => '/web/widgets/CTreeView.php',
  555. 'CWidget' => '/web/widgets/CWidget.php',
  556. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  557. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  558. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  559. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  560. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  561. );
  562. }
  563. spl_autoload_register(array('YiiBase','autoload'));
  564. class Yii extends YiiBase
  565. {
  566. }
  567. class CComponent
  568. {
  569. private $_e;
  570. private $_m;
  571. public function __get($name)
  572. {
  573. $getter='get'.$name;
  574. if(method_exists($this,$getter))
  575. return $this->$getter();
  576. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  577. {
  578. // duplicating getEventHandlers() here for performance
  579. $name=strtolower($name);
  580. if(!isset($this->_e[$name]))
  581. $this->_e[$name]=new CList;
  582. return $this->_e[$name];
  583. }
  584. else if(isset($this->_m[$name]))
  585. return $this->_m[$name];
  586. else if(is_array($this->_m))
  587. {
  588. foreach($this->_m as $object)
  589. {
  590. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  591. return $object->$name;
  592. }
  593. }
  594. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  595. array('{class}'=>get_class($this), '{property}'=>$name)));
  596. }
  597. public function __set($name,$value)
  598. {
  599. $setter='set'.$name;
  600. if(method_exists($this,$setter))
  601. return $this->$setter($value);
  602. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  603. {
  604. // duplicating getEventHandlers() here for performance
  605. $name=strtolower($name);
  606. if(!isset($this->_e[$name]))
  607. $this->_e[$name]=new CList;
  608. return $this->_e[$name]->add($value);
  609. }
  610. else if(is_array($this->_m))
  611. {
  612. foreach($this->_m as $object)
  613. {
  614. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  615. return $object->$name=$value;
  616. }
  617. }
  618. if(method_exists($this,'get'.$name))
  619. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  620. array('{class}'=>get_class($this), '{property}'=>$name)));
  621. else
  622. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  623. array('{class}'=>get_class($this), '{property}'=>$name)));
  624. }
  625. public function __isset($name)
  626. {
  627. $getter='get'.$name;
  628. if(method_exists($this,$getter))
  629. return $this->$getter()!==null;
  630. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  631. {
  632. $name=strtolower($name);
  633. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  634. }
  635. else if(is_array($this->_m))
  636. {
  637. if(isset($this->_m[$name]))
  638. return true;
  639. foreach($this->_m as $object)
  640. {
  641. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  642. return $object->$name!==null;
  643. }
  644. }
  645. return false;
  646. }
  647. public function __unset($name)
  648. {
  649. $setter='set'.$name;
  650. if(method_exists($this,$setter))
  651. $this->$setter(null);
  652. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  653. unset($this->_e[strtolower($name)]);
  654. else if(is_array($this->_m))
  655. {
  656. if(isset($this->_m[$name]))
  657. $this->detachBehavior($name);
  658. else
  659. {
  660. foreach($this->_m as $object)
  661. {
  662. if($object->getEnabled())
  663. {
  664. if(property_exists($object,$name))
  665. return $object->$name=null;
  666. else if($object->canSetProperty($name))
  667. return $object->$setter(null);
  668. }
  669. }
  670. }
  671. }
  672. else if(method_exists($this,'get'.$name))
  673. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  674. array('{class}'=>get_class($this), '{property}'=>$name)));
  675. }
  676. public function __call($name,$parameters)
  677. {
  678. if($this->_m!==null)
  679. {
  680. foreach($this->_m as $object)
  681. {
  682. if($object->getEnabled() && method_exists($object,$name))
  683. return call_user_func_array(array($object,$name),$parameters);
  684. }
  685. }
  686. if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)
  687. return call_user_func_array($this->$name, $parameters);
  688. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  689. array('{class}'=>get_class($this), '{name}'=>$name)));
  690. }
  691. public function asa($behavior)
  692. {
  693. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  694. }
  695. public function attachBehaviors($behaviors)
  696. {
  697. foreach($behaviors as $name=>$behavior)
  698. $this->attachBehavior($name,$behavior);
  699. }
  700. public function detachBehaviors()
  701. {
  702. if($this->_m!==null)
  703. {
  704. foreach($this->_m as $name=>$behavior)
  705. $this->detachBehavior($name);
  706. $this->_m=null;
  707. }
  708. }
  709. public function attachBehavior($name,$behavior)
  710. {
  711. if(!($behavior instanceof IBehavior))
  712. $behavior=Yii::createComponent($behavior);
  713. $behavior->setEnabled(true);
  714. $behavior->attach($this);
  715. return $this->_m[$name]=$behavior;
  716. }
  717. public function detachBehavior($name)
  718. {
  719. if(isset($this->_m[$name]))
  720. {
  721. $this->_m[$name]->detach($this);
  722. $behavior=$this->_m[$name];
  723. unset($this->_m[$name]);
  724. return $behavior;
  725. }
  726. }
  727. public function enableBehaviors()
  728. {
  729. if($this->_m!==null)
  730. {
  731. foreach($this->_m as $behavior)
  732. $behavior->setEnabled(true);
  733. }
  734. }
  735. public function disableBehaviors()
  736. {
  737. if($this->_m!==null)
  738. {
  739. foreach($this->_m as $behavior)
  740. $behavior->setEnabled(false);
  741. }
  742. }
  743. public function enableBehavior($name)
  744. {
  745. if(isset($this->_m[$name]))
  746. $this->_m[$name]->setEnabled(true);
  747. }
  748. public function disableBehavior($name)
  749. {
  750. if(isset($this->_m[$name]))
  751. $this->_m[$name]->setEnabled(false);
  752. }
  753. public function hasProperty($name)
  754. {
  755. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  756. }
  757. public function canGetProperty($name)
  758. {
  759. return method_exists($this,'get'.$name);
  760. }
  761. public function canSetProperty($name)
  762. {
  763. return method_exists($this,'set'.$name);
  764. }
  765. public function hasEvent($name)
  766. {
  767. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  768. }
  769. public function hasEventHandler($name)
  770. {
  771. $name=strtolower($name);
  772. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  773. }
  774. public function getEventHandlers($name)
  775. {
  776. if($this->hasEvent($name))
  777. {
  778. $name=strtolower($name);
  779. if(!isset($this->_e[$name]))
  780. $this->_e[$name]=new CList;
  781. return $this->_e[$name];
  782. }
  783. else
  784. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  785. array('{class}'=>get_class($this), '{event}'=>$name)));
  786. }
  787. public function attachEventHandler($name,$handler)
  788. {
  789. $this->getEventHandlers($name)->add($handler);
  790. }
  791. public function detachEventHandler($name,$handler)
  792. {
  793. if($this->hasEventHandler($name))
  794. return $this->getEventHandlers($name)->remove($handler)!==false;
  795. else
  796. return false;
  797. }
  798. public function raiseEvent($name,$event)
  799. {
  800. $name=strtolower($name);
  801. if(isset($this->_e[$name]))
  802. {
  803. foreach($this->_e[$name] as $handler)
  804. {
  805. if(is_string($handler))
  806. call_user_func($handler,$event);
  807. else if(is_callable($handler,true))
  808. {
  809. if(is_array($handler))
  810. {
  811. // an array: 0 - object, 1 - method name
  812. list($object,$method)=$handler;
  813. if(is_string($object)) // static method call
  814. call_user_func($handler,$event);
  815. else if(method_exists($object,$method))
  816. $object->$method($event);
  817. else
  818. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  819. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  820. }
  821. else // PHP 5.3: anonymous function
  822. call_user_func($handler,$event);
  823. }
  824. else
  825. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  826. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  827. // stop further handling if param.handled is set true
  828. if(($event instanceof CEvent) && $event->handled)
  829. return;
  830. }
  831. }
  832. else if(YII_DEBUG && !$this->hasEvent($name))
  833. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  834. array('{class}'=>get_class($this), '{event}'=>$name)));
  835. }
  836. public function evaluateExpression($_expression_,$_data_=array())
  837. {
  838. if(is_string($_expression_))
  839. {
  840. extract($_data_);
  841. return eval('return '.$_expression_.';');
  842. }
  843. else
  844. {
  845. $_data_[]=$this;
  846. return call_user_func_array($_expression_, $_data_);
  847. }
  848. }
  849. }
  850. class CEvent extends CComponent
  851. {
  852. public $sender;
  853. public $handled=false;
  854. public $params;
  855. public function __construct($sender=null,$params=null)
  856. {
  857. $this->sender=$sender;
  858. $this->params=$params;
  859. }
  860. }
  861. class CEnumerable
  862. {
  863. }
  864. abstract class CModule extends CComponent
  865. {
  866. public $preload=array();
  867. public $behaviors=array();
  868. private $_id;
  869. private $_parentModule;
  870. private $_basePath;
  871. private $_modulePath;
  872. private $_params;
  873. private $_modules=array();
  874. private $_moduleConfig=array();
  875. private $_components=array();
  876. private $_componentConfig=array();
  877. public function __construct($id,$parent,$config=null)
  878. {
  879. $this->_id=$id;
  880. $this->_parentModule=$parent;
  881. // set basePath at early as possible to avoid trouble
  882. if(is_string($config))
  883. $config=require($config);
  884. if(isset($config['basePath']))
  885. {
  886. $this->setBasePath($config['basePath']);
  887. unset($config['basePath']);
  888. }
  889. Yii::setPathOfAlias($id,$this->getBasePath());
  890. $this->preinit();
  891. $this->configure($config);
  892. $this->attachBehaviors($this->behaviors);
  893. $this->preloadComponents();
  894. $this->init();
  895. }
  896. public function __get($name)
  897. {
  898. if($this->hasComponent($name))
  899. return $this->getComponent($name);
  900. else
  901. return parent::__get($name);
  902. }
  903. public function __isset($name)
  904. {
  905. if($this->hasComponent($name))
  906. return $this->getComponent($name)!==null;
  907. else
  908. return parent::__isset($name);
  909. }
  910. public function getId()
  911. {
  912. return $this->_id;
  913. }
  914. public function setId($id)
  915. {
  916. $this->_id=$id;
  917. }
  918. public function getBasePath()
  919. {
  920. if($this->_basePath===null)
  921. {
  922. $class=new ReflectionClass(get_class($this));
  923. $this->_basePath=dirname($class->getFileName());
  924. }
  925. return $this->_basePath;
  926. }
  927. public function setBasePath($path)
  928. {
  929. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  930. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  931. array('{path}'=>$path)));
  932. }
  933. public function getParams()
  934. {
  935. if($this->_params!==null)
  936. return $this->_params;
  937. else
  938. {
  939. $this->_params=new CAttributeCollection;
  940. $this->_params->caseSensitive=true;
  941. return $this->_params;
  942. }
  943. }
  944. public function setParams($value)
  945. {
  946. $params=$this->getParams();
  947. foreach($value as $k=>$v)
  948. $params->add($k,$v);
  949. }
  950. public function getModulePath()
  951. {
  952. if($this->_modulePath!==null)
  953. return $this->_modulePath;
  954. else
  955. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  956. }
  957. public function setModulePath($value)
  958. {
  959. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  960. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  961. array('{path}'=>$value)));
  962. }
  963. public function setImport($aliases)
  964. {
  965. foreach($aliases as $alias)
  966. Yii::import($alias);
  967. }
  968. public function setAliases($mappings)
  969. {
  970. foreach($mappings as $name=>$alias)
  971. {
  972. if(($path=Yii::getPathOfAlias($alias))!==false)
  973. Yii::setPathOfAlias($name,$path);
  974. else
  975. Yii::setPathOfAlias($name,$alias);
  976. }
  977. }
  978. public function getParentModule()
  979. {
  980. return $this->_parentModule;
  981. }
  982. public function getModule($id)
  983. {
  984. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  985. return $this->_modules[$id];
  986. else if(isset($this->_moduleConfig[$id]))
  987. {
  988. $config=$this->_moduleConfig[$id];
  989. if(!isset($config['enabled']) || $config['enabled'])
  990. {
  991. $class=$config['class'];
  992. unset($config['class'], $config['enabled']);
  993. if($this===Yii::app())
  994. $module=Yii::createComponent($class,$id,null,$config);
  995. else
  996. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  997. return $this->_modules[$id]=$module;
  998. }
  999. }
  1000. }
  1001. public function hasModule($id)
  1002. {
  1003. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  1004. }
  1005. public function getModules()
  1006. {
  1007. return $this->_moduleConfig;
  1008. }
  1009. public function setModules($modules)
  1010. {
  1011. foreach($modules as $id=>$module)
  1012. {
  1013. if(is_int($id))
  1014. {
  1015. $id=$module;
  1016. $module=array();
  1017. }
  1018. if(!isset($module['class']))
  1019. {
  1020. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1021. $module['class']=$id.'.'.ucfirst($id).'Module';
  1022. }
  1023. if(isset($this->_moduleConfig[$id]))
  1024. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1025. else
  1026. $this->_moduleConfig[$id]=$module;
  1027. }
  1028. }
  1029. public function hasComponent($id)
  1030. {
  1031. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1032. }
  1033. public function getComponent($id,$createIfNull=true)
  1034. {
  1035. if(isset($this->_components[$id]))
  1036. return $this->_components[$id];
  1037. else if(isset($this->_componentConfig[$id]) && $createIfNull)
  1038. {
  1039. $config=$this->_componentConfig[$id];
  1040. if(!isset($config['enabled']) || $config['enabled'])
  1041. {
  1042. unset($config['enabled']);
  1043. $component=Yii::createComponent($config);
  1044. $component->init();
  1045. return $this->_components[$id]=$component;
  1046. }
  1047. }
  1048. }
  1049. public function setComponent($id,$component)
  1050. {
  1051. if($component===null)
  1052. unset($this->_components[$id]);
  1053. else
  1054. {
  1055. $this->_components[$id]=$component;
  1056. if(!$component->getIsInitialized())
  1057. $component->init();
  1058. }
  1059. }
  1060. public function getComponents($loadedOnly=true)
  1061. {
  1062. if($loadedOnly)
  1063. return $this->_components;
  1064. else
  1065. return array_merge($this->_componentConfig, $this->_components);
  1066. }
  1067. public function setComponents($components,$merge=true)
  1068. {
  1069. foreach($components as $id=>$component)
  1070. {
  1071. if($component instanceof IApplicationComponent)
  1072. $this->setComponent($id,$component);
  1073. else if(isset($this->_componentConfig[$id]) && $merge)
  1074. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1075. else
  1076. $this->_componentConfig[$id]=$component;
  1077. }
  1078. }
  1079. public function configure($config)
  1080. {
  1081. if(is_array($config))
  1082. {
  1083. foreach($config as $key=>$value)
  1084. $this->$key=$value;
  1085. }
  1086. }
  1087. protected function preloadComponents()
  1088. {
  1089. foreach($this->preload as $id)
  1090. $this->getComponent($id);
  1091. }
  1092. protected function preinit()
  1093. {
  1094. }
  1095. protected function init()
  1096. {
  1097. }
  1098. }
  1099. abstract class CApplication extends CModule
  1100. {
  1101. public $name='My Application';
  1102. public $charset='UTF-8';
  1103. public $sourceLanguage='en_us';
  1104. private $_id;
  1105. private $_basePath;
  1106. private $_runtimePath;
  1107. private $_extensionPath;
  1108. private $_globalState;
  1109. private $_stateChanged;
  1110. private $_ended=false;
  1111. private $_language;
  1112. private $_homeUrl;
  1113. abstract public function processRequest();
  1114. public function __construct($config=null)
  1115. {
  1116. Yii::setApplication($this);
  1117. // set basePath at early as possible to avoid trouble
  1118. if(is_string($config))
  1119. $config=require($config);
  1120. if(isset($config['basePath']))
  1121. {
  1122. $this->setBasePath($config['basePath']);
  1123. unset($config['basePath']);
  1124. }
  1125. else
  1126. $this->setBasePath('protected');
  1127. Yii::setPathOfAlias('application',$this->getBasePath());
  1128. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1129. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1130. $this->preinit();
  1131. $this->initSystemHandlers();
  1132. $this->registerCoreComponents();
  1133. $this->configure($config);
  1134. $this->attachBehaviors($this->behaviors);
  1135. $this->preloadComponents();
  1136. $this->init();
  1137. }
  1138. public function run()
  1139. {
  1140. if($this->hasEventHandler('onBeginRequest'))
  1141. $this->onBeginRequest(new CEvent($this));
  1142. $this->processRequest();
  1143. if($this->hasEventHandler('onEndRequest'))
  1144. $this->onEndRequest(new CEvent($this));
  1145. }
  1146. public function end($status=0, $exit=true)
  1147. {
  1148. if($this->hasEventHandler('onEndRequest'))
  1149. $this->onEndRequest(new CEvent($this));
  1150. if($exit)
  1151. exit($status);
  1152. }
  1153. public function onBeginRequest($event)
  1154. {
  1155. $this->raiseEvent('onBeginRequest',$event);
  1156. }
  1157. public function onEndRequest($event)
  1158. {
  1159. if(!$this->_ended)
  1160. {
  1161. $this->_ended=true;
  1162. $this->raiseEvent('onEndRequest',$event);
  1163. }
  1164. }
  1165. public function getId()
  1166. {
  1167. if($this->_id!==null)
  1168. return $this->_id;
  1169. else
  1170. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1171. }
  1172. public function setId($id)
  1173. {
  1174. $this->_id=$id;
  1175. }
  1176. public function getBasePath()
  1177. {
  1178. return $this->_basePath;
  1179. }
  1180. public function setBasePath($path)
  1181. {
  1182. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1183. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1184. array('{path}'=>$path)));
  1185. }
  1186. public function getRuntimePath()
  1187. {
  1188. if($this->_runtimePath!==null)
  1189. return $this->_runtimePath;
  1190. else
  1191. {
  1192. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1193. return $this->_runtimePath;
  1194. }
  1195. }
  1196. public function setRuntimePath($path)
  1197. {
  1198. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1199. 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.',
  1200. array('{path}'=>$path)));
  1201. $this->_runtimePath=$runtimePath;
  1202. }
  1203. public function getExtensionPath()
  1204. {
  1205. return Yii::getPathOfAlias('ext');
  1206. }
  1207. public function setExtensionPath($path)
  1208. {
  1209. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1210. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1211. array('{path}'=>$path)));
  1212. Yii::setPathOfAlias('ext',$extensionPath);
  1213. }
  1214. public function getLanguage()
  1215. {
  1216. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1217. }
  1218. public function setLanguage($language)
  1219. {
  1220. $this->_language=$language;
  1221. }
  1222. public function getTimeZone()
  1223. {
  1224. return date_default_timezone_get();
  1225. }
  1226. public function setTimeZone($value)
  1227. {
  1228. date_default_timezone_set($value);
  1229. }
  1230. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1231. {
  1232. if($srcLanguage===null)
  1233. $srcLanguage=$this->sourceLanguage;
  1234. if($language===null)
  1235. $language=$this->getLanguage();
  1236. if($language===$srcLanguage)
  1237. return $srcFile;
  1238. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1239. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1240. }
  1241. public function getLocale($localeID=null)
  1242. {
  1243. return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID);
  1244. }
  1245. public function getLocaleDataPath()
  1246. {
  1247. return CLocale::$dataPath===null ? Yii::getPathOfAlias('system.i18n.data') : CLocale::$dataPath;
  1248. }
  1249. public function setLocaleDataPath($value)
  1250. {
  1251. CLocale::$dataPath=$value;
  1252. }
  1253. public function getNumberFormatter()
  1254. {
  1255. return $this->getLocale()->getNumberFormatter();
  1256. }
  1257. public function getDateFormatter()
  1258. {
  1259. return $this->getLocale()->getDateFormatter();
  1260. }
  1261. public function getDb()
  1262. {
  1263. return $this->getComponent('db');
  1264. }
  1265. public function getErrorHandler()
  1266. {
  1267. return $this->getComponent('errorHandler');
  1268. }
  1269. public function getSecurityManager()
  1270. {
  1271. return $this->getComponent('securityManager');
  1272. }
  1273. public function getStatePersister()
  1274. {
  1275. return $this->getComponent('statePersister');
  1276. }
  1277. public function getCache()
  1278. {
  1279. return $this->getComponent('cache');
  1280. }
  1281. public function getCoreMessages()
  1282. {
  1283. return $this->getComponent('coreMessages');
  1284. }
  1285. public function getMessages()
  1286. {
  1287. return $this->getComponent('messages');
  1288. }
  1289. public function getRequest()
  1290. {
  1291. return $this->getComponent('request');
  1292. }
  1293. public function getUrlManager()
  1294. {
  1295. return $this->getComponent('urlManager');
  1296. }
  1297. public function getController()
  1298. {
  1299. return null;
  1300. }
  1301. public function createUrl($route,$params=array(),$ampersand='&')
  1302. {
  1303. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1304. }
  1305. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1306. {
  1307. $url=$this->createUrl($route,$params,$ampersand);
  1308. if(strpos($url,'http')===0)
  1309. return $url;
  1310. else
  1311. return $this->getRequest()->getHostInfo($schema).$url;
  1312. }
  1313. public function getBaseUrl($absolute=false)
  1314. {
  1315. return $this->getRequest()->getBaseUrl($absolute);
  1316. }
  1317. public function getHomeUrl()
  1318. {
  1319. if($this->_homeUrl===null)
  1320. {
  1321. if($this->getUrlManager()->showScriptName)
  1322. return $this->getRequest()->getScriptUrl();
  1323. else
  1324. return $this->getRequest()->getBaseUrl().'/';
  1325. }
  1326. else
  1327. return $this->_homeUrl;
  1328. }
  1329. public function setHomeUrl($value)
  1330. {
  1331. $this->_homeUrl=$value;
  1332. }
  1333. public function getGlobalState($key,$defaultValue=null)
  1334. {
  1335. if($this->_globalState===null)
  1336. $this->loadGlobalState();
  1337. if(isset($this->_globalState[$key]))
  1338. return $this->_globalState[$key];
  1339. else
  1340. return $defaultValue;
  1341. }
  1342. public function setGlobalState($key,$value,$defaultValue=null)
  1343. {
  1344. if($this->_globalState===null)
  1345. $this->loadGlobalState();
  1346. $changed=$this->_stateChanged;
  1347. if($value===$defaultValue)
  1348. {
  1349. if(isset($this->_globalState[$key]))
  1350. {
  1351. unset($this->_globalState[$key]);
  1352. $this->_stateChanged=true;
  1353. }
  1354. }
  1355. else if(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1356. {
  1357. $this->_globalState[$key]=$value;
  1358. $this->_stateChanged=true;
  1359. }
  1360. if($this->_stateChanged!==$changed)
  1361. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1362. }
  1363. public function clearGlobalState($key)
  1364. {
  1365. $this->setGlobalState($key,true,true);
  1366. }
  1367. public function loadGlobalState()
  1368. {
  1369. $persister=$this->getStatePersister();
  1370. if(($this->_globalState=$persister->load())===null)
  1371. $this->_globalState=array();
  1372. $this->_stateChanged=false;
  1373. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1374. }
  1375. public function saveGlobalState()
  1376. {
  1377. if($this->_stateChanged)
  1378. {
  1379. $this->_stateChanged=false;
  1380. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1381. $this->getStatePersister()->save($this->_globalState);
  1382. }
  1383. }
  1384. public function handleException($exception)
  1385. {
  1386. // disable error capturing to avoid recursive errors
  1387. restore_error_handler();
  1388. restore_exception_handler();
  1389. $category='exception.'.get_class($exception);
  1390. if($exception instanceof CHttpException)
  1391. $category.='.'.$exception->statusCode;
  1392. // php <5.2 doesn't support string conversion auto-magically
  1393. $message=$exception->__toString();
  1394. if(isset($_SERVER['REQUEST_URI']))
  1395. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  1396. if(isset($_SERVER['HTTP_REFERER']))
  1397. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  1398. $message.="\n---";
  1399. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1400. try
  1401. {
  1402. $event=new CExceptionEvent($this,$exception);
  1403. $this->onException($event);
  1404. if(!$event->handled)
  1405. {
  1406. // try an error handler
  1407. if(($handler=$this->getErrorHandler())!==null)
  1408. $handler->handle($event);
  1409. else
  1410. $this->displayException($exception);
  1411. }
  1412. }
  1413. catch(Exception $e)
  1414. {
  1415. $this->displayException($e);
  1416. }
  1417. try
  1418. {
  1419. $this->end(1);
  1420. }
  1421. catch(Exception $e)
  1422. {
  1423. // use the most primitive way to log error
  1424. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1425. $msg .= $e->getTraceAsString()."\n";
  1426. $msg .= "Previous exception:\n";
  1427. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1428. $msg .= $exception->getTraceAsString()."\n";
  1429. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1430. error_log($msg);
  1431. exit(1);
  1432. }
  1433. }
  1434. public function handleError($code,$message,$file,$line)
  1435. {
  1436. if($code & error_reporting())
  1437. {
  1438. // disable error capturing to avoid recursive errors
  1439. restore_error_handler();
  1440. restore_exception_handler();
  1441. $log="$message ($file:$line)\nStack trace:\n";
  1442. $trace=debug_backtrace();
  1443. // skip the first 3 stacks as they do not tell the error position
  1444. if(count($trace)>3)
  1445. $trace=array_slice($trace,3);
  1446. foreach($trace as $i=>$t)
  1447. {
  1448. if(!isset($t['file']))
  1449. $t['file']='unknown';
  1450. if(!isset($t['line']))
  1451. $t['line']=0;
  1452. if(!isset($t['function']))
  1453. $t['function']='unknown';
  1454. $log.="#$i {$t['file']}({$t['line']}): ";
  1455. if(isset($t['object']) && is_object($t['object']))
  1456. $log.=get_class($t['object']).'->';
  1457. $log.="{$t['function']}()\n";
  1458. }
  1459. if(isset($_SERVER['REQUEST_URI']))
  1460. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1461. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1462. try
  1463. {
  1464. Yii::import('CErrorEvent',true);
  1465. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1466. $this->onError($event);
  1467. if(!$event->handled)
  1468. {
  1469. // try an error handler
  1470. if(($handler=$this->getErrorHandler())!==null)
  1471. $handler->handle($event);
  1472. else
  1473. $this->displayError($code,$message,$file,$line);
  1474. }
  1475. }
  1476. catch(Exception $e)
  1477. {
  1478. $this->displayException($e);
  1479. }
  1480. try
  1481. {
  1482. $this->end(1);
  1483. }
  1484. catch(Exception $e)
  1485. {
  1486. // use the most primitive way to log error
  1487. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1488. $msg .= $e->getTraceAsString()."\n";
  1489. $msg .= "Previous error:\n";
  1490. $msg .= $log."\n";
  1491. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1492. error_log($msg);
  1493. exit(1);
  1494. }
  1495. }
  1496. }
  1497. public function onException($event)
  1498. {
  1499. $this->raiseEvent('onException',$event);
  1500. }
  1501. public function onError($event)
  1502. {
  1503. $this->raiseEvent('onError',$event);
  1504. }
  1505. public function displayError($code,$message,$file,$line)
  1506. {
  1507. if(YII_DEBUG)
  1508. {
  1509. echo "<h1>PHP Error [$code]</h1>\n";
  1510. echo "<p>$message ($file:$line)</p>\n";
  1511. echo '<pre>';
  1512. $trace=debug_backtrace();
  1513. // skip the first 3 stacks as they do not tell the error position
  1514. if(count($trace)>3)
  1515. $trace=array_slice($trace,3);
  1516. foreach($trace as $i=>$t)
  1517. {
  1518. if(!isset($t['file']))
  1519. $t['file']='unknown';
  1520. if(!isset($t['line']))
  1521. $t['line']=0;
  1522. if(!isset($t['function']))
  1523. $t['function']='unknown';
  1524. echo "#$i {$t['file']}({$t['line']}): ";
  1525. if(isset($t['object']) && is_object($t['object']))
  1526. echo get_class($t['object']).'->';
  1527. echo "{$t['function']}()\n";
  1528. }
  1529. echo '</pre>';
  1530. }
  1531. else
  1532. {
  1533. echo "<h1>PHP Error [$code]</h1>\n";
  1534. echo "<p>$message</p>\n";
  1535. }
  1536. }
  1537. public function displayException($exception)
  1538. {
  1539. if(YII_DEBUG)
  1540. {
  1541. echo '<h1>'.get_class($exception)."</h1>\n";
  1542. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1543. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1544. }
  1545. else
  1546. {
  1547. echo '<h1>'.get_class($exception)."</h1>\n";
  1548. echo '<p>'.$exception->getMessage().'</p>';
  1549. }
  1550. }
  1551. protected function initSystemHandlers()
  1552. {
  1553. if(YII_ENABLE_EXCEPTION_HANDLER)
  1554. set_exception_handler(array($this,'handleException'));
  1555. if(YII_ENABLE_ERROR_HANDLER)
  1556. set_error_handler(array($this,'handleError'),error_reporting());
  1557. }
  1558. protected function registerCoreComponents()
  1559. {
  1560. $components=array(
  1561. 'coreMessages'=>array(
  1562. 'class'=>'CPhpMessageSource',
  1563. 'language'=>'en_us',
  1564. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1565. ),
  1566. 'db'=>array(
  1567. 'class'=>'CDbConnection',
  1568. ),
  1569. 'messages'=>array(
  1570. 'class'=>'CPhpMessageSource',
  1571. ),
  1572. 'errorHandler'=>array(
  1573. 'class'=>'CErrorHandler',
  1574. ),
  1575. 'securityManager'=>array(
  1576. 'class'=>'CSecurityManager',
  1577. ),
  1578. 'statePersister'=>array(
  1579. 'class'=>'CStatePersister',
  1580. ),
  1581. 'urlManager'=>array(
  1582. 'class'=>'CUrlManager',
  1583. ),
  1584. 'request'=>array(
  1585. 'class'=>'CHttpRequest',
  1586. ),
  1587. 'format'=>array(
  1588. 'class'=>'CFormatter',
  1589. ),
  1590. );
  1591. $this->setComponents($components);
  1592. }
  1593. }
  1594. class CWebApplication extends CApplication
  1595. {
  1596. public $defaultController='site';
  1597. public $layout='main';
  1598. public $controllerMap=array();
  1599. public $catchAllRequest;
  1600. public $controllerNamespace;
  1601. private $_controllerPath;
  1602. private $_viewPath;
  1603. private $_systemViewPath;
  1604. private $_layoutPath;
  1605. private $_controller;
  1606. private $_theme;
  1607. public function processRequest()
  1608. {
  1609. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1610. {
  1611. $route=$this->catchAllRequest[0];
  1612. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1613. $_GET[$name]=$value;
  1614. }
  1615. else
  1616. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1617. $this->runController($route);
  1618. }
  1619. protected function registerCoreComponents()
  1620. {
  1621. parent::registerCoreComponents();
  1622. $components=array(
  1623. 'session'=>array(
  1624. 'class'=>'CHttpSession',
  1625. ),
  1626. 'assetManager'=>array(
  1627. 'class'=>'CAssetManager',
  1628. ),
  1629. 'user'=>array(
  1630. 'class'=>'CWebUser',
  1631. ),
  1632. 'themeManager'=>array(
  1633. 'class'=>'CThemeManager',
  1634. ),
  1635. 'authManager'=>array(
  1636. 'class'=>'CPhpAuthManager',
  1637. ),
  1638. 'clientScript'=>array(
  1639. 'class'=>'CClientScript',
  1640. ),
  1641. 'widgetFactory'=>array(
  1642. 'class'=>'CWidgetFactory',
  1643. ),
  1644. );
  1645. $this->setComponents($components);
  1646. }
  1647. public function getAuthManager()
  1648. {
  1649. return $this->getComponent('authManager');
  1650. }
  1651. public function getAssetManager()
  1652. {
  1653. return $this->getComponent('assetManager');
  1654. }
  1655. public function getSession()
  1656. {
  1657. return $this->getComponent('session');
  1658. }
  1659. public function getUser()
  1660. {
  1661. return $this->getComponent('user');
  1662. }
  1663. public function getViewRenderer()
  1664. {
  1665. return $this->getComponent('viewRenderer');
  1666. }
  1667. public function getClientScript()
  1668. {
  1669. return $this->getComponent('clientScript');
  1670. }
  1671. public function getWidgetFactory()
  1672. {
  1673. return $this->getComponent('widgetFactory');
  1674. }
  1675. public function getThemeManager()
  1676. {
  1677. return $this->getComponent('themeManager');
  1678. }
  1679. public function getTheme()
  1680. {
  1681. if(is_string($this->_theme))
  1682. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1683. return $this->_theme;
  1684. }
  1685. public function setTheme($value)
  1686. {
  1687. $this->_theme=$value;
  1688. }
  1689. public function runController($route)
  1690. {
  1691. if(($ca=$this->createController($route))!==null)
  1692. {
  1693. list($controller,$actionID)=$ca;
  1694. $oldController=$this->_controller;
  1695. $this->_controller=$controller;
  1696. $controller->init();
  1697. $controller->run($actionID);
  1698. $this->_controller=$oldController;
  1699. }
  1700. else
  1701. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1702. array('{route}'=>$route===''?$this->defaultController:$route)));
  1703. }
  1704. public function createController($route,$owner=null)
  1705. {
  1706. if($owner===null)
  1707. $owner=$this;
  1708. if(($route=trim($route,'/'))==='')
  1709. $route=$owner->defaultController;
  1710. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1711. $route.='/';
  1712. while(($pos=strpos($route,'/'))!==false)
  1713. {
  1714. $id=substr($route,0,$pos);
  1715. if(!preg_match('/^\w+$/',$id))
  1716. return null;
  1717. if(!$caseSensitive)
  1718. $id=strtolower($id);
  1719. $route=(string)substr($route,$pos+1);
  1720. if(!isset($basePath)) // first segment
  1721. {
  1722. if(isset($owner->controllerMap[$id]))
  1723. {
  1724. return array(
  1725. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1726. $this->parseActionParams($route),
  1727. );
  1728. }
  1729. if(($module=$owner->getModule($id))!==null)
  1730. return $this->createController($route,$module);
  1731. $basePath=$owner->getControllerPath();
  1732. $controllerID='';
  1733. }
  1734. else
  1735. $controllerID.='/';
  1736. $className=ucfirst($id).'Controller';
  1737. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1738. if($owner->controllerNamespace!==null)
  1739. $className=$owner->controllerNamespace.'\\'.$className;
  1740. if(is_file($classFile))
  1741. {
  1742. if(!class_exists($className,false))
  1743. require($classFile);
  1744. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1745. {
  1746. $id[0]=strtolower($id[0]);
  1747. return array(
  1748. new $className($controllerID.$id,$owner===$this?null:$owner),
  1749. $this->parseActionParams($route),
  1750. );
  1751. }
  1752. return null;
  1753. }
  1754. $controllerID.=$id;
  1755. $basePath.=DIRECTORY_SEPARATOR.$id;
  1756. }
  1757. }
  1758. protected function parseActionParams($pathInfo)
  1759. {
  1760. if(($pos=strpos($pathInfo,'/'))!==false)
  1761. {
  1762. $manager=$this->getUrlManager();
  1763. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1764. $actionID=substr($pathInfo,0,$pos);
  1765. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1766. }
  1767. else
  1768. return $pathInfo;
  1769. }
  1770. public function getController()
  1771. {
  1772. return $this->_controller;
  1773. }
  1774. public function setController($value)
  1775. {
  1776. $this->_controller=$value;
  1777. }
  1778. public function getControllerPath()
  1779. {
  1780. if($this->_controllerPath!==null)
  1781. return $this->_controllerPath;
  1782. else
  1783. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1784. }
  1785. public function setControllerPath($value)
  1786. {
  1787. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1788. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1789. array('{path}'=>$value)));
  1790. }
  1791. public function getViewPath()
  1792. {
  1793. if($this->_viewPath!==null)
  1794. return $this->_viewPath;
  1795. else
  1796. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1797. }
  1798. public function setViewPath($path)
  1799. {
  1800. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1801. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1802. array('{path}'=>$path)));
  1803. }
  1804. public function getSystemViewPath()
  1805. {
  1806. if($this->_systemViewPath!==null)
  1807. return $this->_systemViewPath;
  1808. else
  1809. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1810. }
  1811. public function setSystemViewPath($path)
  1812. {
  1813. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1814. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1815. array('{path}'=>$path)));
  1816. }
  1817. public function getLayoutPath()
  1818. {
  1819. if($this->_layoutPath!==null)
  1820. return $this->_layoutPath;
  1821. else
  1822. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1823. }
  1824. public function setLayoutPath($path)
  1825. {
  1826. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1827. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1828. array('{path}'=>$path)));
  1829. }
  1830. public function beforeControllerAction($controller,$action)
  1831. {
  1832. return true;
  1833. }
  1834. public function afterControllerAction($controller,$action)
  1835. {
  1836. }
  1837. public function findModule($id)
  1838. {
  1839. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1840. {
  1841. do
  1842. {
  1843. if(($m=$module->getModule($id))!==null)
  1844. return $m;
  1845. } while(($module=$module->getParentModule())!==null);
  1846. }
  1847. if(($m=$this->getModule($id))!==null)
  1848. return $m;
  1849. }
  1850. protected function init()
  1851. {
  1852. parent::init();
  1853. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1854. $this->getRequest();
  1855. }
  1856. }
  1857. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1858. {
  1859. private $_d=array();
  1860. private $_r=false;
  1861. public function __construct($data=null,$readOnly=false)
  1862. {
  1863. if($data!==null)
  1864. $this->copyFrom($data);
  1865. $this->setReadOnly($readOnly);
  1866. }
  1867. public function getReadOnly()
  1868. {
  1869. return $this->_r;
  1870. }
  1871. protected function setReadOnly($value)
  1872. {
  1873. $this->_r=$value;
  1874. }
  1875. public function getIterator()
  1876. {
  1877. return new CMapIterator($this->_d);
  1878. }
  1879. public function count()
  1880. {
  1881. return $this->getCount();
  1882. }
  1883. public function getCount()
  1884. {
  1885. return count($this->_d);
  1886. }
  1887. public function getKeys()
  1888. {
  1889. return array_keys($this->_d);
  1890. }
  1891. public function itemAt($key)
  1892. {
  1893. if(isset($this->_d[$key]))
  1894. return $this->_d[$key];
  1895. else
  1896. return null;
  1897. }
  1898. public function add($key,$value)
  1899. {
  1900. if(!$this->_r)
  1901. {
  1902. if($key===null)
  1903. $this->_d[]=$value;
  1904. else
  1905. $this->_d[$key]=$value;
  1906. }
  1907. else
  1908. throw new CException(Yii::t('yii','The map is read only.'));
  1909. }
  1910. public function remove($key)
  1911. {
  1912. if(!$this->_r)
  1913. {
  1914. if(isset($this->_d[$key]))
  1915. {
  1916. $value=$this->_d[$key];
  1917. unset($this->_d[$key]);
  1918. return $value;
  1919. }
  1920. else
  1921. {
  1922. // it is possible the value is null, which is not detected by isset
  1923. unset($this->_d[$key]);
  1924. return null;
  1925. }
  1926. }
  1927. else
  1928. throw new CException(Yii::t('yii','The map is read only.'));
  1929. }
  1930. public function clear()
  1931. {
  1932. foreach(array_keys($this->_d) as $key)
  1933. $this->remove($key);
  1934. }
  1935. public function contains($key)
  1936. {
  1937. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  1938. }
  1939. public function toArray()
  1940. {
  1941. return $this->_d;
  1942. }
  1943. public function copyFrom($data)
  1944. {
  1945. if(is_array($data) || $data instanceof Traversable)
  1946. {
  1947. if($this->getCount()>0)
  1948. $this->clear();
  1949. if($data instanceof CMap)
  1950. $data=$data->_d;
  1951. foreach($data as $key=>$value)
  1952. $this->add($key,$value);
  1953. }
  1954. else if($data!==null)
  1955. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1956. }
  1957. public function mergeWith($data,$recursive=true)
  1958. {
  1959. if(is_array($data) || $data instanceof Traversable)
  1960. {
  1961. if($data instanceof CMap)
  1962. $data=$data->_d;
  1963. if($recursive)
  1964. {
  1965. if($data instanceof Traversable)
  1966. {
  1967. $d=array();
  1968. foreach($data as $key=>$value)
  1969. $d[$key]=$value;
  1970. $this->_d=self::mergeArray($this->_d,$d);
  1971. }
  1972. else
  1973. $this->_d=self::mergeArray($this->_d,$data);
  1974. }
  1975. else
  1976. {
  1977. foreach($data as $key=>$value)
  1978. $this->add($key,$value);
  1979. }
  1980. }
  1981. else if($data!==null)
  1982. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1983. }
  1984. public static function mergeArray($a,$b)
  1985. {
  1986. $args=func_get_args();
  1987. $res=array_shift($args);
  1988. while(!empty($args))
  1989. {
  1990. $next=array_shift($args);
  1991. foreach($next as $k => $v)
  1992. {
  1993. if(is_integer($k))
  1994. isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
  1995. else if(is_array($v) && isset($res[$k]) && is_array($res[$k]))
  1996. $res[$k]=self::mergeArray($res[$k],$v);
  1997. else
  1998. $res[$k]=$v;
  1999. }
  2000. }
  2001. return $res;
  2002. }
  2003. public function offsetExists($offset)
  2004. {
  2005. return $this->contains($offset);
  2006. }
  2007. public function offsetGet($offset)
  2008. {
  2009. return $this->itemAt($offset);
  2010. }
  2011. public function offsetSet($offset,$item)
  2012. {
  2013. $this->add($offset,$item);
  2014. }
  2015. public function offsetUnset($offset)
  2016. {
  2017. $this->remove($offset);
  2018. }
  2019. }
  2020. class CLogger extends CComponent
  2021. {
  2022. const LEVEL_TRACE='trace';
  2023. const LEVEL_WARNING='warning';
  2024. const LEVEL_ERROR='error';
  2025. const LEVEL_INFO='info';
  2026. const LEVEL_PROFILE='profile';
  2027. public $autoFlush=10000;
  2028. public $autoDump=false;
  2029. private $_logs=array();
  2030. private $_logCount=0;
  2031. private $_levels;
  2032. private $_categories;
  2033. private $_timings;
  2034. private $_processing=false;
  2035. public function log($message,$level='info',$category='application')
  2036. {
  2037. $this->_logs[]=array($message,$level,$category,microtime(true));
  2038. $this->_logCount++;
  2039. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
  2040. {
  2041. $this->_processing=true;
  2042. $this->flush($this->autoDump);
  2043. $this->_processing=false;
  2044. }
  2045. }
  2046. public function getLogs($levels='',$categories='')
  2047. {
  2048. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2049. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2050. if(empty($levels) && empty($categories))
  2051. return $this->_logs;
  2052. else if(empty($levels))
  2053. return array_values(array_filter($this->_logs,array($this,'filterByCategory')));
  2054. else if(empty($categories))
  2055. return array_values(array_filter($this->_logs,array($this,'filterByLevel')));
  2056. else
  2057. {
  2058. $ret=array_filter($this->_logs,array($this,'filterByLevel'));
  2059. return array_values(array_filter($ret,array($this,'filterByCategory')));
  2060. }
  2061. }
  2062. private function filterByCategory($value)
  2063. {
  2064. foreach($this->_categories as $category)
  2065. {
  2066. $cat=strtolower($value[2]);
  2067. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2068. return true;
  2069. }
  2070. return false;
  2071. }
  2072. private function filterTimingByCategory($value)
  2073. {
  2074. foreach($this->_categories as $category)
  2075. {
  2076. $cat=strtolower($value[1]);
  2077. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2078. return true;
  2079. }
  2080. return false;
  2081. }
  2082. private function filterByLevel($value)
  2083. {
  2084. return in_array(strtolower($value[1]),$this->_levels);
  2085. }
  2086. public function getExecutionTime()
  2087. {
  2088. return microtime(true)-YII_BEGIN_TIME;
  2089. }
  2090. public function getMemoryUsage()
  2091. {
  2092. if(function_exists('memory_get_usage'))
  2093. return memory_get_usage();
  2094. else
  2095. {
  2096. $output=array();
  2097. if(strncmp(PHP_OS,'WIN',3)===0)
  2098. {
  2099. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2100. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2101. }
  2102. else
  2103. {
  2104. $pid=getmypid();
  2105. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2106. $output=explode(" ",$output[0]);
  2107. return isset($output[1]) ? $output[1]*1024 : 0;
  2108. }
  2109. }
  2110. }
  2111. public function getProfilingResults($token=null,$categories=null,$refresh=false)
  2112. {
  2113. if($this->_timings===null || $refresh)
  2114. $this->calculateTimings();
  2115. if($token===null && $categories===null)
  2116. return $this->_timings;
  2117. $timings = $this->_timings;
  2118. if($categories!==null) {
  2119. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2120. $timings=array_filter($timings,array($this,'filterTimingByCategory'));
  2121. }
  2122. $results=array();
  2123. foreach($timings as $timing)
  2124. {
  2125. if($token===null || $timing[0]===$token)
  2126. $results[]=$timing[2];
  2127. }
  2128. return $results;
  2129. }
  2130. private function calculateTimings()
  2131. {
  2132. $this->_timings=array();
  2133. $stack=array();
  2134. foreach($this->_logs as $log)
  2135. {
  2136. if($log[1]!==CLogger::LEVEL_PROFILE)
  2137. continue;
  2138. list($message,$level,$category,$timestamp)=$log;
  2139. if(!strncasecmp($message,'begin:',6))
  2140. {
  2141. $log[0]=substr($message,6);
  2142. $stack[]=$log;
  2143. }
  2144. else if(!strncasecmp($message,'end:',4))
  2145. {
  2146. $token=substr($message,4);
  2147. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2148. {
  2149. $delta=$log[3]-$last[3];
  2150. $this->_timings[]=array($message,$category,$delta);
  2151. }
  2152. else
  2153. 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.',
  2154. array('{token}'=>$token)));
  2155. }
  2156. }
  2157. $now=microtime(true);
  2158. while(($last=array_pop($stack))!==null)
  2159. {
  2160. $delta=$now-$last[3];
  2161. $this->_timings[]=array($last[0],$last[2],$delta);
  2162. }
  2163. }
  2164. public function flush($dumpLogs=false)
  2165. {
  2166. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2167. $this->_logs=array();
  2168. $this->_logCount=0;
  2169. }
  2170. public function onFlush($event)
  2171. {
  2172. $this->raiseEvent('onFlush', $event);
  2173. }
  2174. }
  2175. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2176. {
  2177. public $behaviors=array();
  2178. private $_initialized=false;
  2179. public function init()
  2180. {
  2181. $this->attachBehaviors($this->behaviors);
  2182. $this->_initialized=true;
  2183. }
  2184. public function getIsInitialized()
  2185. {
  2186. return $this->_initialized;
  2187. }
  2188. }
  2189. class CHttpRequest extends CApplicationComponent
  2190. {
  2191. public $enableCookieValidation=false;
  2192. public $enableCsrfValidation=false;
  2193. public $csrfTokenName='YII_CSRF_TOKEN';
  2194. public $csrfCookie;
  2195. private $_requestUri;
  2196. private $_pathInfo;
  2197. private $_scriptFile;
  2198. private $_scriptUrl;
  2199. private $_hostInfo;
  2200. private $_baseUrl;
  2201. private $_cookies;
  2202. private $_preferredLanguage;
  2203. private $_csrfToken;
  2204. private $_deleteParams;
  2205. private $_putParams;
  2206. public function init()
  2207. {
  2208. parent::init();
  2209. $this->normalizeRequest();
  2210. }
  2211. protected function normalizeRequest()
  2212. {
  2213. // normalize request
  2214. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2215. {
  2216. if(isset($_GET))
  2217. $_GET=$this->stripSlashes($_GET);
  2218. if(isset($_POST))
  2219. $_POST=$this->stripSlashes($_POST);
  2220. if(isset($_REQUEST))
  2221. $_REQUEST=$this->stripSlashes($_REQUEST);
  2222. if(isset($_COOKIE))
  2223. $_COOKIE=$this->stripSlashes($_COOKIE);
  2224. }
  2225. if($this->enableCsrfValidation)
  2226. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2227. }
  2228. public function stripSlashes(&$data)
  2229. {
  2230. return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
  2231. }
  2232. public function getParam($name,$defaultValue=null)
  2233. {
  2234. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2235. }
  2236. public function getQuery($name,$defaultValue=null)
  2237. {
  2238. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2239. }
  2240. public function getPost($name,$defaultValue=null)
  2241. {
  2242. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2243. }
  2244. public function getDelete($name,$defaultValue=null)
  2245. {
  2246. if($this->getIsDeleteViaPostRequest())
  2247. return $this->getPost($name, $defaultValue);
  2248. if($this->_deleteParams===null)
  2249. $this->_deleteParams=$this->getIsDeleteRequest() ? $this->getRestParams() : array();
  2250. return isset($this->_deleteParams[$name]) ? $this->_deleteParams[$name] : $defaultValue;
  2251. }
  2252. public function getPut($name,$defaultValue=null)
  2253. {
  2254. if($this->getIsPutViaPostRequest())
  2255. return $this->getPost($name, $defaultValue);
  2256. if($this->_putParams===null)
  2257. $this->_putParams=$this->getIsPutRequest() ? $this->getRestParams() : array();
  2258. return isset($this->_putParams[$name]) ? $this->_putParams[$name] : $defaultValue;
  2259. }
  2260. protected function getRestParams()
  2261. {
  2262. $result=array();
  2263. if(function_exists('mb_parse_str'))
  2264. mb_parse_str(file_get_contents('php://input'), $result);
  2265. else
  2266. parse_str(file_get_contents('php://input'), $result);
  2267. return $result;
  2268. }
  2269. public function getUrl()
  2270. {
  2271. return $this->getRequestUri();
  2272. }
  2273. public function getHostInfo($schema='')
  2274. {
  2275. if($this->_hostInfo===null)
  2276. {
  2277. if($secure=$this->getIsSecureConnection())
  2278. $http='https';
  2279. else
  2280. $http='http';
  2281. if(isset($_SERVER['HTTP_HOST']))
  2282. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2283. else
  2284. {
  2285. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2286. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2287. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2288. $this->_hostInfo.=':'.$port;
  2289. }
  2290. }
  2291. if($schema!=='')
  2292. {
  2293. $secure=$this->getIsSecureConnection();
  2294. if($secure && $schema==='https' || !$secure && $schema==='http')
  2295. return $this->_hostInfo;
  2296. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2297. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2298. $port=':'.$port;
  2299. else
  2300. $port='';
  2301. $pos=strpos($this->_hostInfo,':');
  2302. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2303. }
  2304. else
  2305. return $this->_hostInfo;
  2306. }
  2307. public function setHostInfo($value)
  2308. {
  2309. $this->_hostInfo=rtrim($value,'/');
  2310. }
  2311. public function getBaseUrl($absolute=false)
  2312. {
  2313. if($this->_baseUrl===null)
  2314. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2315. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2316. }
  2317. public function setBaseUrl($value)
  2318. {
  2319. $this->_baseUrl=$value;
  2320. }
  2321. public function getScriptUrl()
  2322. {
  2323. if($this->_scriptUrl===null)
  2324. {
  2325. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2326. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2327. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2328. else if(basename($_SERVER['PHP_SELF'])===$scriptName)
  2329. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2330. else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2331. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2332. else if(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2333. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2334. else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2335. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2336. else
  2337. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2338. }
  2339. return $this->_scriptUrl;
  2340. }
  2341. public function setScriptUrl($value)
  2342. {
  2343. $this->_scriptUrl='/'.trim($value,'/');
  2344. }
  2345. public function getPathInfo()
  2346. {
  2347. if($this->_pathInfo===null)
  2348. {
  2349. $pathInfo=$this->getRequestUri();
  2350. if(($pos=strpos($pathInfo,'?'))!==false)
  2351. $pathInfo=substr($pathInfo,0,$pos);
  2352. $pathInfo=$this->decodePathInfo($pathInfo);
  2353. $scriptUrl=$this->getScriptUrl();
  2354. $baseUrl=$this->getBaseUrl();
  2355. if(strpos($pathInfo,$scriptUrl)===0)
  2356. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2357. else if($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2358. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2359. else if(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2360. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2361. else
  2362. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2363. $this->_pathInfo=trim($pathInfo,'/');
  2364. }
  2365. return $this->_pathInfo;
  2366. }
  2367. protected function decodePathInfo($pathInfo)
  2368. {
  2369. $pathInfo = urldecode($pathInfo);
  2370. // is it UTF-8?
  2371. // http://w3.org/International/questions/qa-forms-utf-8.html
  2372. if(preg_match('%^(?:
  2373. [\x09\x0A\x0D\x20-\x7E] # ASCII
  2374. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  2375. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  2376. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  2377. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  2378. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  2379. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  2380. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  2381. )*$%xs', $pathInfo))
  2382. {
  2383. return $pathInfo;
  2384. }
  2385. else
  2386. {
  2387. return utf8_encode($pathInfo);
  2388. }
  2389. }
  2390. public function getRequestUri()
  2391. {
  2392. if($this->_requestUri===null)
  2393. {
  2394. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2395. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2396. else if(isset($_SERVER['REQUEST_URI']))
  2397. {
  2398. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2399. if(!empty($_SERVER['HTTP_HOST']))
  2400. {
  2401. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2402. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2403. }
  2404. else
  2405. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2406. }
  2407. else if(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2408. {
  2409. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2410. if(!empty($_SERVER['QUERY_STRING']))
  2411. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2412. }
  2413. else
  2414. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2415. }
  2416. return $this->_requestUri;
  2417. }
  2418. public function getQueryString()
  2419. {
  2420. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2421. }
  2422. public function getIsSecureConnection()
  2423. {
  2424. return !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'],'off');
  2425. }
  2426. public function getRequestType()
  2427. {
  2428. if(isset($_POST['_method']))
  2429. return strtoupper($_POST['_method']);
  2430. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2431. }
  2432. public function getIsPostRequest()
  2433. {
  2434. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2435. }
  2436. public function getIsDeleteRequest()
  2437. {
  2438. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE')) || $this->getIsDeleteViaPostRequest();
  2439. }
  2440. protected function getIsDeleteViaPostRequest()
  2441. {
  2442. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'DELETE');
  2443. }
  2444. public function getIsPutRequest()
  2445. {
  2446. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT')) || $this->getIsPutViaPostRequest();
  2447. }
  2448. protected function getIsPutViaPostRequest()
  2449. {
  2450. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PUT');
  2451. }
  2452. public function getIsAjaxRequest()
  2453. {
  2454. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2455. }
  2456. public function getIsFlashRequest()
  2457. {
  2458. return isset($_SERVER['HTTP_USER_AGENT']) && (stripos($_SERVER['HTTP_USER_AGENT'],'Shockwave')!==false || stripos($_SERVER['HTTP_USER_AGENT'],'Flash')!==false);
  2459. }
  2460. public function getServerName()
  2461. {
  2462. return $_SERVER['SERVER_NAME'];
  2463. }
  2464. public function getServerPort()
  2465. {
  2466. return $_SERVER['SERVER_PORT'];
  2467. }
  2468. public function getUrlReferrer()
  2469. {
  2470. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2471. }
  2472. public function getUserAgent()
  2473. {
  2474. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2475. }
  2476. public function getUserHostAddress()
  2477. {
  2478. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2479. }
  2480. public function getUserHost()
  2481. {
  2482. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2483. }
  2484. public function getScriptFile()
  2485. {
  2486. if($this->_scriptFile!==null)
  2487. return $this->_scriptFile;
  2488. else
  2489. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2490. }
  2491. public function getBrowser($userAgent=null)
  2492. {
  2493. return get_browser($userAgent,true);
  2494. }
  2495. public function getAcceptTypes()
  2496. {
  2497. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2498. }
  2499. private $_port;
  2500. public function getPort()
  2501. {
  2502. if($this->_port===null)
  2503. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2504. return $this->_port;
  2505. }
  2506. public function setPort($value)
  2507. {
  2508. $this->_port=(int)$value;
  2509. $this->_hostInfo=null;
  2510. }
  2511. private $_securePort;
  2512. public function getSecurePort()
  2513. {
  2514. if($this->_securePort===null)
  2515. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2516. return $this->_securePort;
  2517. }
  2518. public function setSecurePort($value)
  2519. {
  2520. $this->_securePort=(int)$value;
  2521. $this->_hostInfo=null;
  2522. }
  2523. public function getCookies()
  2524. {
  2525. if($this->_cookies!==null)
  2526. return $this->_cookies;
  2527. else
  2528. return $this->_cookies=new CCookieCollection($this);
  2529. }
  2530. public function redirect($url,$terminate=true,$statusCode=302)
  2531. {
  2532. if(strpos($url,'/')===0)
  2533. $url=$this->getHostInfo().$url;
  2534. header('Location: '.$url, true, $statusCode);
  2535. if($terminate)
  2536. Yii::app()->end();
  2537. }
  2538. public function getPreferredLanguage()
  2539. {
  2540. if($this->_preferredLanguage===null)
  2541. {
  2542. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && ($n=preg_match_all('/([\w\-_]+)\s*(;\s*q\s*=\s*(\d*\.\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))>0)
  2543. {
  2544. $languages=array();
  2545. for($i=0;$i<$n;++$i)
  2546. $languages[$matches[1][$i]]=empty($matches[3][$i]) ? 1.0 : floatval($matches[3][$i]);
  2547. arsort($languages);
  2548. foreach($languages as $language=>$pref)
  2549. return $this->_preferredLanguage=CLocale::getCanonicalID($language);
  2550. }
  2551. return $this->_preferredLanguage=false;
  2552. }
  2553. return $this->_preferredLanguage;
  2554. }
  2555. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2556. {
  2557. if($mimeType===null)
  2558. {
  2559. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2560. $mimeType='text/plain';
  2561. }
  2562. header('Pragma: public');
  2563. header('Expires: 0');
  2564. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2565. header("Content-type: $mimeType");
  2566. if(ob_get_length()===false)
  2567. header('Content-Length: '.(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content)));
  2568. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2569. header('Content-Transfer-Encoding: binary');
  2570. if($terminate)
  2571. {
  2572. // clean up the application first because the file downloading could take long time
  2573. // which may cause timeout of some resources (such as DB connection)
  2574. Yii::app()->end(0,false);
  2575. echo $content;
  2576. exit(0);
  2577. }
  2578. else
  2579. echo $content;
  2580. }
  2581. public function xSendFile($filePath, $options=array())
  2582. {
  2583. if(!isset($options['forceDownload']) || $options['forceDownload'])
  2584. $disposition='attachment';
  2585. else
  2586. $disposition='inline';
  2587. if(!isset($options['saveName']))
  2588. $options['saveName']=basename($filePath);
  2589. if(!isset($options['mimeType']))
  2590. {
  2591. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2592. $options['mimeType']='text/plain';
  2593. }
  2594. if(!isset($options['xHeader']))
  2595. $options['xHeader']='X-Sendfile';
  2596. if($options['mimeType'] !== null)
  2597. header('Content-type: '.$options['mimeType']);
  2598. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  2599. if(isset($options['addHeaders']))
  2600. {
  2601. foreach($options['addHeaders'] as $header=>$value)
  2602. header($header.': '.$value);
  2603. }
  2604. header(trim($options['xHeader']).': '.$filePath);
  2605. if(!isset($options['terminate']) || $options['terminate'])
  2606. Yii::app()->end();
  2607. }
  2608. public function getCsrfToken()
  2609. {
  2610. if($this->_csrfToken===null)
  2611. {
  2612. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2613. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2614. {
  2615. $cookie=$this->createCsrfCookie();
  2616. $this->_csrfToken=$cookie->value;
  2617. $this->getCookies()->add($cookie->name,$cookie);
  2618. }
  2619. }
  2620. return $this->_csrfToken;
  2621. }
  2622. protected function createCsrfCookie()
  2623. {
  2624. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2625. if(is_array($this->csrfCookie))
  2626. {
  2627. foreach($this->csrfCookie as $name=>$value)
  2628. $cookie->$name=$value;
  2629. }
  2630. return $cookie;
  2631. }
  2632. public function validateCsrfToken($event)
  2633. {
  2634. if($this->getIsPostRequest())
  2635. {
  2636. // only validate POST requests
  2637. $cookies=$this->getCookies();
  2638. if($cookies->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName]))
  2639. {
  2640. $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value;
  2641. $tokenFromPost=$_POST[$this->csrfTokenName];
  2642. $valid=$tokenFromCookie===$tokenFromPost;
  2643. }
  2644. else
  2645. $valid=false;
  2646. if(!$valid)
  2647. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2648. }
  2649. }
  2650. }
  2651. class CCookieCollection extends CMap
  2652. {
  2653. private $_request;
  2654. private $_initialized=false;
  2655. public function __construct(CHttpRequest $request)
  2656. {
  2657. $this->_request=$request;
  2658. $this->copyfrom($this->getCookies());
  2659. $this->_initialized=true;
  2660. }
  2661. public function getRequest()
  2662. {
  2663. return $this->_request;
  2664. }
  2665. protected function getCookies()
  2666. {
  2667. $cookies=array();
  2668. if($this->_request->enableCookieValidation)
  2669. {
  2670. $sm=Yii::app()->getSecurityManager();
  2671. foreach($_COOKIE as $name=>$value)
  2672. {
  2673. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  2674. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  2675. }
  2676. }
  2677. else
  2678. {
  2679. foreach($_COOKIE as $name=>$value)
  2680. $cookies[$name]=new CHttpCookie($name,$value);
  2681. }
  2682. return $cookies;
  2683. }
  2684. public function add($name,$cookie)
  2685. {
  2686. if($cookie instanceof CHttpCookie)
  2687. {
  2688. $this->remove($name);
  2689. parent::add($name,$cookie);
  2690. if($this->_initialized)
  2691. $this->addCookie($cookie);
  2692. }
  2693. else
  2694. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  2695. }
  2696. public function remove($name,$options=array())
  2697. {
  2698. if(($cookie=parent::remove($name))!==null)
  2699. {
  2700. if($this->_initialized)
  2701. {
  2702. $cookie->configure($options);
  2703. $this->removeCookie($cookie);
  2704. }
  2705. }
  2706. return $cookie;
  2707. }
  2708. protected function addCookie($cookie)
  2709. {
  2710. $value=$cookie->value;
  2711. if($this->_request->enableCookieValidation)
  2712. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  2713. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2714. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2715. else
  2716. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  2717. }
  2718. protected function removeCookie($cookie)
  2719. {
  2720. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2721. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2722. else
  2723. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure);
  2724. }
  2725. }
  2726. class CUrlManager extends CApplicationComponent
  2727. {
  2728. const CACHE_KEY='Yii.CUrlManager.rules';
  2729. const GET_FORMAT='get';
  2730. const PATH_FORMAT='path';
  2731. public $rules=array();
  2732. public $urlSuffix='';
  2733. public $showScriptName=true;
  2734. public $appendParams=true;
  2735. public $routeVar='r';
  2736. public $caseSensitive=true;
  2737. public $matchValue=false;
  2738. public $cacheID='cache';
  2739. public $useStrictParsing=false;
  2740. public $urlRuleClass='CUrlRule';
  2741. private $_urlFormat=self::GET_FORMAT;
  2742. private $_rules=array();
  2743. private $_baseUrl;
  2744. public function init()
  2745. {
  2746. parent::init();
  2747. $this->processRules();
  2748. }
  2749. protected function processRules()
  2750. {
  2751. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  2752. return;
  2753. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  2754. {
  2755. $hash=md5(serialize($this->rules));
  2756. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  2757. {
  2758. $this->_rules=$data[0];
  2759. return;
  2760. }
  2761. }
  2762. foreach($this->rules as $pattern=>$route)
  2763. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2764. if(isset($cache))
  2765. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  2766. }
  2767. public function addRules($rules,$append=true)
  2768. {
  2769. if ($append)
  2770. {
  2771. foreach($rules as $pattern=>$route)
  2772. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2773. }
  2774. else
  2775. {
  2776. $rules=array_reverse($rules);
  2777. foreach($rules as $pattern=>$route)
  2778. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  2779. }
  2780. }
  2781. protected function createUrlRule($route,$pattern)
  2782. {
  2783. if(is_array($route) && isset($route['class']))
  2784. return $route;
  2785. else
  2786. return new $this->urlRuleClass($route,$pattern);
  2787. }
  2788. public function createUrl($route,$params=array(),$ampersand='&')
  2789. {
  2790. unset($params[$this->routeVar]);
  2791. foreach($params as $i=>$param)
  2792. if($param===null)
  2793. $params[$i]='';
  2794. if(isset($params['#']))
  2795. {
  2796. $anchor='#'.$params['#'];
  2797. unset($params['#']);
  2798. }
  2799. else
  2800. $anchor='';
  2801. $route=trim($route,'/');
  2802. foreach($this->_rules as $i=>$rule)
  2803. {
  2804. if(is_array($rule))
  2805. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2806. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  2807. {
  2808. if($rule->hasHostInfo)
  2809. return $url==='' ? '/'.$anchor : $url.$anchor;
  2810. else
  2811. return $this->getBaseUrl().'/'.$url.$anchor;
  2812. }
  2813. }
  2814. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  2815. }
  2816. protected function createUrlDefault($route,$params,$ampersand)
  2817. {
  2818. if($this->getUrlFormat()===self::PATH_FORMAT)
  2819. {
  2820. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  2821. if($this->appendParams)
  2822. {
  2823. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  2824. return $route==='' ? $url : $url.$this->urlSuffix;
  2825. }
  2826. else
  2827. {
  2828. if($route!=='')
  2829. $url.=$this->urlSuffix;
  2830. $query=$this->createPathInfo($params,'=',$ampersand);
  2831. return $query==='' ? $url : $url.'?'.$query;
  2832. }
  2833. }
  2834. else
  2835. {
  2836. $url=$this->getBaseUrl();
  2837. if(!$this->showScriptName)
  2838. $url.='/';
  2839. if($route!=='')
  2840. {
  2841. $url.='?'.$this->routeVar.'='.$route;
  2842. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2843. $url.=$ampersand.$query;
  2844. }
  2845. else if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2846. $url.='?'.$query;
  2847. return $url;
  2848. }
  2849. }
  2850. public function parseUrl($request)
  2851. {
  2852. if($this->getUrlFormat()===self::PATH_FORMAT)
  2853. {
  2854. $rawPathInfo=$request->getPathInfo();
  2855. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  2856. foreach($this->_rules as $i=>$rule)
  2857. {
  2858. if(is_array($rule))
  2859. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2860. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  2861. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  2862. }
  2863. if($this->useStrictParsing)
  2864. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  2865. array('{route}'=>$pathInfo)));
  2866. else
  2867. return $pathInfo;
  2868. }
  2869. else if(isset($_GET[$this->routeVar]))
  2870. return $_GET[$this->routeVar];
  2871. else if(isset($_POST[$this->routeVar]))
  2872. return $_POST[$this->routeVar];
  2873. else
  2874. return '';
  2875. }
  2876. public function parsePathInfo($pathInfo)
  2877. {
  2878. if($pathInfo==='')
  2879. return;
  2880. $segs=explode('/',$pathInfo.'/');
  2881. $n=count($segs);
  2882. for($i=0;$i<$n-1;$i+=2)
  2883. {
  2884. $key=$segs[$i];
  2885. if($key==='') continue;
  2886. $value=$segs[$i+1];
  2887. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  2888. {
  2889. $name=substr($key,0,$pos);
  2890. for($j=$m-1;$j>=0;--$j)
  2891. {
  2892. if($matches[1][$j]==='')
  2893. $value=array($value);
  2894. else
  2895. $value=array($matches[1][$j]=>$value);
  2896. }
  2897. if(isset($_GET[$name]) && is_array($_GET[$name]))
  2898. $value=CMap::mergeArray($_GET[$name],$value);
  2899. $_REQUEST[$name]=$_GET[$name]=$value;
  2900. }
  2901. else
  2902. $_REQUEST[$key]=$_GET[$key]=$value;
  2903. }
  2904. }
  2905. public function createPathInfo($params,$equal,$ampersand, $key=null)
  2906. {
  2907. $pairs = array();
  2908. foreach($params as $k => $v)
  2909. {
  2910. if ($key!==null)
  2911. $k = $key.'['.$k.']';
  2912. if (is_array($v))
  2913. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  2914. else
  2915. $pairs[]=urlencode($k).$equal.urlencode($v);
  2916. }
  2917. return implode($ampersand,$pairs);
  2918. }
  2919. public function removeUrlSuffix($pathInfo,$urlSuffix)
  2920. {
  2921. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  2922. return substr($pathInfo,0,-strlen($urlSuffix));
  2923. else
  2924. return $pathInfo;
  2925. }
  2926. public function getBaseUrl()
  2927. {
  2928. if($this->_baseUrl!==null)
  2929. return $this->_baseUrl;
  2930. else
  2931. {
  2932. if($this->showScriptName)
  2933. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  2934. else
  2935. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  2936. return $this->_baseUrl;
  2937. }
  2938. }
  2939. public function setBaseUrl($value)
  2940. {
  2941. $this->_baseUrl=$value;
  2942. }
  2943. public function getUrlFormat()
  2944. {
  2945. return $this->_urlFormat;
  2946. }
  2947. public function setUrlFormat($value)
  2948. {
  2949. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  2950. $this->_urlFormat=$value;
  2951. else
  2952. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  2953. }
  2954. }
  2955. abstract class CBaseUrlRule extends CComponent
  2956. {
  2957. public $hasHostInfo=false;
  2958. abstract public function createUrl($manager,$route,$params,$ampersand);
  2959. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  2960. }
  2961. class CUrlRule extends CBaseUrlRule
  2962. {
  2963. public $urlSuffix;
  2964. public $caseSensitive;
  2965. public $defaultParams=array();
  2966. public $matchValue;
  2967. public $verb;
  2968. public $parsingOnly=false;
  2969. public $route;
  2970. public $references=array();
  2971. public $routePattern;
  2972. public $pattern;
  2973. public $template;
  2974. public $params=array();
  2975. public $append;
  2976. public $hasHostInfo;
  2977. public function __construct($route,$pattern)
  2978. {
  2979. if(is_array($route))
  2980. {
  2981. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  2982. {
  2983. if(isset($route[$name]))
  2984. $this->$name=$route[$name];
  2985. }
  2986. if(isset($route['pattern']))
  2987. $pattern=$route['pattern'];
  2988. $route=$route[0];
  2989. }
  2990. $this->route=trim($route,'/');
  2991. $tr2['/']=$tr['/']='\\/';
  2992. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  2993. {
  2994. foreach($matches2[1] as $name)
  2995. $this->references[$name]="<$name>";
  2996. }
  2997. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  2998. if($this->verb!==null)
  2999. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  3000. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  3001. {
  3002. $tokens=array_combine($matches[1],$matches[2]);
  3003. foreach($tokens as $name=>$value)
  3004. {
  3005. if($value==='')
  3006. $value='[^\/]+';
  3007. $tr["<$name>"]="(?P<$name>$value)";
  3008. if(isset($this->references[$name]))
  3009. $tr2["<$name>"]=$tr["<$name>"];
  3010. else
  3011. $this->params[$name]=$value;
  3012. }
  3013. }
  3014. $p=rtrim($pattern,'*');
  3015. $this->append=$p!==$pattern;
  3016. $p=trim($p,'/');
  3017. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  3018. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  3019. if($this->append)
  3020. $this->pattern.='/u';
  3021. else
  3022. $this->pattern.='$/u';
  3023. if($this->references!==array())
  3024. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  3025. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  3026. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  3027. array('{route}'=>$route,'{pattern}'=>$pattern)));
  3028. }
  3029. public function createUrl($manager,$route,$params,$ampersand)
  3030. {
  3031. if($this->parsingOnly)
  3032. return false;
  3033. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3034. $case='';
  3035. else
  3036. $case='i';
  3037. $tr=array();
  3038. if($route!==$this->route)
  3039. {
  3040. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  3041. {
  3042. foreach($this->references as $key=>$name)
  3043. $tr[$name]=$matches[$key];
  3044. }
  3045. else
  3046. return false;
  3047. }
  3048. foreach($this->defaultParams as $key=>$value)
  3049. {
  3050. if(isset($params[$key]))
  3051. {
  3052. if($params[$key]==$value)
  3053. unset($params[$key]);
  3054. else
  3055. return false;
  3056. }
  3057. }
  3058. foreach($this->params as $key=>$value)
  3059. if(!isset($params[$key]))
  3060. return false;
  3061. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  3062. {
  3063. foreach($this->params as $key=>$value)
  3064. {
  3065. if(!preg_match('/\A'.$value.'\z/u'.$case,$params[$key]))
  3066. return false;
  3067. }
  3068. }
  3069. foreach($this->params as $key=>$value)
  3070. {
  3071. $tr["<$key>"]=urlencode($params[$key]);
  3072. unset($params[$key]);
  3073. }
  3074. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3075. $url=strtr($this->template,$tr);
  3076. if($this->hasHostInfo)
  3077. {
  3078. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  3079. if(stripos($url,$hostInfo)===0)
  3080. $url=substr($url,strlen($hostInfo));
  3081. }
  3082. if(empty($params))
  3083. return $url!=='' ? $url.$suffix : $url;
  3084. if($this->append)
  3085. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  3086. else
  3087. {
  3088. if($url!=='')
  3089. $url.=$suffix;
  3090. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  3091. }
  3092. return $url;
  3093. }
  3094. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  3095. {
  3096. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  3097. return false;
  3098. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3099. $case='';
  3100. else
  3101. $case='i';
  3102. if($this->urlSuffix!==null)
  3103. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3104. // URL suffix required, but not found in the requested URL
  3105. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3106. {
  3107. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3108. if($urlSuffix!='' && $urlSuffix!=='/')
  3109. return false;
  3110. }
  3111. if($this->hasHostInfo)
  3112. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3113. $pathInfo.='/';
  3114. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3115. {
  3116. foreach($this->defaultParams as $name=>$value)
  3117. {
  3118. if(!isset($_GET[$name]))
  3119. $_REQUEST[$name]=$_GET[$name]=$value;
  3120. }
  3121. $tr=array();
  3122. foreach($matches as $key=>$value)
  3123. {
  3124. if(isset($this->references[$key]))
  3125. $tr[$this->references[$key]]=$value;
  3126. else if(isset($this->params[$key]))
  3127. $_REQUEST[$key]=$_GET[$key]=$value;
  3128. }
  3129. if($pathInfo!==$matches[0]) // there're additional GET params
  3130. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3131. if($this->routePattern!==null)
  3132. return strtr($this->route,$tr);
  3133. else
  3134. return $this->route;
  3135. }
  3136. else
  3137. return false;
  3138. }
  3139. }
  3140. abstract class CBaseController extends CComponent
  3141. {
  3142. private $_widgetStack=array();
  3143. abstract public function getViewFile($viewName);
  3144. public function renderFile($viewFile,$data=null,$return=false)
  3145. {
  3146. $widgetCount=count($this->_widgetStack);
  3147. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3148. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3149. else
  3150. $content=$this->renderInternal($viewFile,$data,$return);
  3151. if(count($this->_widgetStack)===$widgetCount)
  3152. return $content;
  3153. else
  3154. {
  3155. $widget=end($this->_widgetStack);
  3156. 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.',
  3157. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3158. }
  3159. }
  3160. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3161. {
  3162. // we use special variable names here to avoid conflict when extracting data
  3163. if(is_array($_data_))
  3164. extract($_data_,EXTR_PREFIX_SAME,'data');
  3165. else
  3166. $data=$_data_;
  3167. if($_return_)
  3168. {
  3169. ob_start();
  3170. ob_implicit_flush(false);
  3171. require($_viewFile_);
  3172. return ob_get_clean();
  3173. }
  3174. else
  3175. require($_viewFile_);
  3176. }
  3177. public function createWidget($className,$properties=array())
  3178. {
  3179. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3180. $widget->init();
  3181. return $widget;
  3182. }
  3183. public function widget($className,$properties=array(),$captureOutput=false)
  3184. {
  3185. if($captureOutput)
  3186. {
  3187. ob_start();
  3188. ob_implicit_flush(false);
  3189. $widget=$this->createWidget($className,$properties);
  3190. $widget->run();
  3191. return ob_get_clean();
  3192. }
  3193. else
  3194. {
  3195. $widget=$this->createWidget($className,$properties);
  3196. $widget->run();
  3197. return $widget;
  3198. }
  3199. }
  3200. public function beginWidget($className,$properties=array())
  3201. {
  3202. $widget=$this->createWidget($className,$properties);
  3203. $this->_widgetStack[]=$widget;
  3204. return $widget;
  3205. }
  3206. public function endWidget($id='')
  3207. {
  3208. if(($widget=array_pop($this->_widgetStack))!==null)
  3209. {
  3210. $widget->run();
  3211. return $widget;
  3212. }
  3213. else
  3214. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3215. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3216. }
  3217. public function beginClip($id,$properties=array())
  3218. {
  3219. $properties['id']=$id;
  3220. $this->beginWidget('CClipWidget',$properties);
  3221. }
  3222. public function endClip()
  3223. {
  3224. $this->endWidget('CClipWidget');
  3225. }
  3226. public function beginCache($id,$properties=array())
  3227. {
  3228. $properties['id']=$id;
  3229. $cache=$this->beginWidget('COutputCache',$properties);
  3230. if($cache->getIsContentCached())
  3231. {
  3232. $this->endCache();
  3233. return false;
  3234. }
  3235. else
  3236. return true;
  3237. }
  3238. public function endCache()
  3239. {
  3240. $this->endWidget('COutputCache');
  3241. }
  3242. public function beginContent($view=null,$data=array())
  3243. {
  3244. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3245. }
  3246. public function endContent()
  3247. {
  3248. $this->endWidget('CContentDecorator');
  3249. }
  3250. }
  3251. class CController extends CBaseController
  3252. {
  3253. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3254. public $layout;
  3255. public $defaultAction='index';
  3256. private $_id;
  3257. private $_action;
  3258. private $_pageTitle;
  3259. private $_cachingStack;
  3260. private $_clips;
  3261. private $_dynamicOutput;
  3262. private $_pageStates;
  3263. private $_module;
  3264. public function __construct($id,$module=null)
  3265. {
  3266. $this->_id=$id;
  3267. $this->_module=$module;
  3268. $this->attachBehaviors($this->behaviors());
  3269. }
  3270. public function init()
  3271. {
  3272. }
  3273. public function filters()
  3274. {
  3275. return array();
  3276. }
  3277. public function actions()
  3278. {
  3279. return array();
  3280. }
  3281. public function behaviors()
  3282. {
  3283. return array();
  3284. }
  3285. public function accessRules()
  3286. {
  3287. return array();
  3288. }
  3289. public function run($actionID)
  3290. {
  3291. if(($action=$this->createAction($actionID))!==null)
  3292. {
  3293. if(($parent=$this->getModule())===null)
  3294. $parent=Yii::app();
  3295. if($parent->beforeControllerAction($this,$action))
  3296. {
  3297. $this->runActionWithFilters($action,$this->filters());
  3298. $parent->afterControllerAction($this,$action);
  3299. }
  3300. }
  3301. else
  3302. $this->missingAction($actionID);
  3303. }
  3304. public function runActionWithFilters($action,$filters)
  3305. {
  3306. if(empty($filters))
  3307. $this->runAction($action);
  3308. else
  3309. {
  3310. $priorAction=$this->_action;
  3311. $this->_action=$action;
  3312. CFilterChain::create($this,$action,$filters)->run();
  3313. $this->_action=$priorAction;
  3314. }
  3315. }
  3316. public function runAction($action)
  3317. {
  3318. $priorAction=$this->_action;
  3319. $this->_action=$action;
  3320. if($this->beforeAction($action))
  3321. {
  3322. if($action->runWithParams($this->getActionParams())===false)
  3323. $this->invalidActionParams($action);
  3324. else
  3325. $this->afterAction($action);
  3326. }
  3327. $this->_action=$priorAction;
  3328. }
  3329. public function getActionParams()
  3330. {
  3331. return $_GET;
  3332. }
  3333. public function invalidActionParams($action)
  3334. {
  3335. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3336. }
  3337. public function processOutput($output)
  3338. {
  3339. Yii::app()->getClientScript()->render($output);
  3340. // if using page caching, we should delay dynamic output replacement
  3341. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3342. {
  3343. $output=$this->processDynamicOutput($output);
  3344. $this->_dynamicOutput=null;
  3345. }
  3346. if($this->_pageStates===null)
  3347. $this->_pageStates=$this->loadPageStates();
  3348. if(!empty($this->_pageStates))
  3349. $this->savePageStates($this->_pageStates,$output);
  3350. return $output;
  3351. }
  3352. public function processDynamicOutput($output)
  3353. {
  3354. if($this->_dynamicOutput)
  3355. {
  3356. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3357. }
  3358. return $output;
  3359. }
  3360. protected function replaceDynamicOutput($matches)
  3361. {
  3362. $content=$matches[0];
  3363. if(isset($this->_dynamicOutput[$matches[1]]))
  3364. {
  3365. $content=$this->_dynamicOutput[$matches[1]];
  3366. $this->_dynamicOutput[$matches[1]]=null;
  3367. }
  3368. return $content;
  3369. }
  3370. public function createAction($actionID)
  3371. {
  3372. if($actionID==='')
  3373. $actionID=$this->defaultAction;
  3374. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3375. return new CInlineAction($this,$actionID);
  3376. else
  3377. {
  3378. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3379. if($action!==null && !method_exists($action,'run'))
  3380. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3381. return $action;
  3382. }
  3383. }
  3384. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3385. {
  3386. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3387. {
  3388. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3389. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3390. }
  3391. else if($pos===false)
  3392. return null;
  3393. // the action is defined in a provider
  3394. $prefix=substr($actionID,0,$pos+1);
  3395. if(!isset($actionMap[$prefix]))
  3396. return null;
  3397. $actionID=(string)substr($actionID,$pos+1);
  3398. $provider=$actionMap[$prefix];
  3399. if(is_string($provider))
  3400. $providerType=$provider;
  3401. else if(is_array($provider) && isset($provider['class']))
  3402. {
  3403. $providerType=$provider['class'];
  3404. if(isset($provider[$actionID]))
  3405. {
  3406. if(is_string($provider[$actionID]))
  3407. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3408. else
  3409. $config=array_merge($provider[$actionID],$config);
  3410. }
  3411. }
  3412. else
  3413. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3414. $class=Yii::import($providerType,true);
  3415. $map=call_user_func(array($class,'actions'));
  3416. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3417. }
  3418. public function missingAction($actionID)
  3419. {
  3420. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3421. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3422. }
  3423. public function getAction()
  3424. {
  3425. return $this->_action;
  3426. }
  3427. public function setAction($value)
  3428. {
  3429. $this->_action=$value;
  3430. }
  3431. public function getId()
  3432. {
  3433. return $this->_id;
  3434. }
  3435. public function getUniqueId()
  3436. {
  3437. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3438. }
  3439. public function getRoute()
  3440. {
  3441. if(($action=$this->getAction())!==null)
  3442. return $this->getUniqueId().'/'.$action->getId();
  3443. else
  3444. return $this->getUniqueId();
  3445. }
  3446. public function getModule()
  3447. {
  3448. return $this->_module;
  3449. }
  3450. public function getViewPath()
  3451. {
  3452. if(($module=$this->getModule())===null)
  3453. $module=Yii::app();
  3454. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3455. }
  3456. public function getViewFile($viewName)
  3457. {
  3458. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3459. return $viewFile;
  3460. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3461. if(($module=$this->getModule())!==null)
  3462. $moduleViewPath=$module->getViewPath();
  3463. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3464. }
  3465. public function getLayoutFile($layoutName)
  3466. {
  3467. if($layoutName===false)
  3468. return false;
  3469. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3470. return $layoutFile;
  3471. if(empty($layoutName))
  3472. {
  3473. $module=$this->getModule();
  3474. while($module!==null)
  3475. {
  3476. if($module->layout===false)
  3477. return false;
  3478. if(!empty($module->layout))
  3479. break;
  3480. $module=$module->getParentModule();
  3481. }
  3482. if($module===null)
  3483. $module=Yii::app();
  3484. $layoutName=$module->layout;
  3485. }
  3486. else if(($module=$this->getModule())===null)
  3487. $module=Yii::app();
  3488. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3489. }
  3490. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3491. {
  3492. if(empty($viewName))
  3493. return false;
  3494. if($moduleViewPath===null)
  3495. $moduleViewPath=$basePath;
  3496. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3497. $extension=$renderer->fileExtension;
  3498. else
  3499. $extension='.php';
  3500. if($viewName[0]==='/')
  3501. {
  3502. if(strncmp($viewName,'//',2)===0)
  3503. $viewFile=$basePath.$viewName;
  3504. else
  3505. $viewFile=$moduleViewPath.$viewName;
  3506. }
  3507. else if(strpos($viewName,'.'))
  3508. $viewFile=Yii::getPathOfAlias($viewName);
  3509. else
  3510. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3511. if(is_file($viewFile.$extension))
  3512. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3513. else if($extension!=='.php' && is_file($viewFile.'.php'))
  3514. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3515. else
  3516. return false;
  3517. }
  3518. public function getClips()
  3519. {
  3520. if($this->_clips!==null)
  3521. return $this->_clips;
  3522. else
  3523. return $this->_clips=new CMap;
  3524. }
  3525. public function forward($route,$exit=true)
  3526. {
  3527. if(strpos($route,'/')===false)
  3528. $this->run($route);
  3529. else
  3530. {
  3531. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3532. $route=$module->getId().'/'.$route;
  3533. Yii::app()->runController($route);
  3534. }
  3535. if($exit)
  3536. Yii::app()->end();
  3537. }
  3538. public function render($view,$data=null,$return=false)
  3539. {
  3540. if($this->beforeRender($view))
  3541. {
  3542. $output=$this->renderPartial($view,$data,true);
  3543. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3544. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3545. $this->afterRender($view,$output);
  3546. $output=$this->processOutput($output);
  3547. if($return)
  3548. return $output;
  3549. else
  3550. echo $output;
  3551. }
  3552. }
  3553. protected function beforeRender($view)
  3554. {
  3555. return true;
  3556. }
  3557. protected function afterRender($view, &$output)
  3558. {
  3559. }
  3560. public function renderText($text,$return=false)
  3561. {
  3562. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3563. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3564. $text=$this->processOutput($text);
  3565. if($return)
  3566. return $text;
  3567. else
  3568. echo $text;
  3569. }
  3570. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3571. {
  3572. if(($viewFile=$this->getViewFile($view))!==false)
  3573. {
  3574. $output=$this->renderFile($viewFile,$data,true);
  3575. if($processOutput)
  3576. $output=$this->processOutput($output);
  3577. if($return)
  3578. return $output;
  3579. else
  3580. echo $output;
  3581. }
  3582. else
  3583. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3584. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3585. }
  3586. public function renderClip($name,$params=array(),$return=false)
  3587. {
  3588. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  3589. if($return)
  3590. return $text;
  3591. else
  3592. echo $text;
  3593. }
  3594. public function renderDynamic($callback)
  3595. {
  3596. $n=count($this->_dynamicOutput);
  3597. echo "<###dynamic-$n###>";
  3598. $params=func_get_args();
  3599. array_shift($params);
  3600. $this->renderDynamicInternal($callback,$params);
  3601. }
  3602. public function renderDynamicInternal($callback,$params)
  3603. {
  3604. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3605. if(is_string($callback) && method_exists($this,$callback))
  3606. $callback=array($this,$callback);
  3607. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3608. }
  3609. public function createUrl($route,$params=array(),$ampersand='&')
  3610. {
  3611. if($route==='')
  3612. $route=$this->getId().'/'.$this->getAction()->getId();
  3613. else if(strpos($route,'/')===false)
  3614. $route=$this->getId().'/'.$route;
  3615. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3616. $route=$module->getId().'/'.$route;
  3617. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3618. }
  3619. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3620. {
  3621. $url=$this->createUrl($route,$params,$ampersand);
  3622. if(strpos($url,'http')===0)
  3623. return $url;
  3624. else
  3625. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  3626. }
  3627. public function getPageTitle()
  3628. {
  3629. if($this->_pageTitle!==null)
  3630. return $this->_pageTitle;
  3631. else
  3632. {
  3633. $name=ucfirst(basename($this->getId()));
  3634. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3635. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3636. else
  3637. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3638. }
  3639. }
  3640. public function setPageTitle($value)
  3641. {
  3642. $this->_pageTitle=$value;
  3643. }
  3644. public function redirect($url,$terminate=true,$statusCode=302)
  3645. {
  3646. if(is_array($url))
  3647. {
  3648. $route=isset($url[0]) ? $url[0] : '';
  3649. $url=$this->createUrl($route,array_splice($url,1));
  3650. }
  3651. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  3652. }
  3653. public function refresh($terminate=true,$anchor='')
  3654. {
  3655. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  3656. }
  3657. public function recordCachingAction($context,$method,$params)
  3658. {
  3659. if($this->_cachingStack) // record only when there is an active output cache
  3660. {
  3661. foreach($this->_cachingStack as $cache)
  3662. $cache->recordAction($context,$method,$params);
  3663. }
  3664. }
  3665. public function getCachingStack($createIfNull=true)
  3666. {
  3667. if(!$this->_cachingStack)
  3668. $this->_cachingStack=new CStack;
  3669. return $this->_cachingStack;
  3670. }
  3671. public function isCachingStackEmpty()
  3672. {
  3673. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  3674. }
  3675. protected function beforeAction($action)
  3676. {
  3677. return true;
  3678. }
  3679. protected function afterAction($action)
  3680. {
  3681. }
  3682. public function filterPostOnly($filterChain)
  3683. {
  3684. if(Yii::app()->getRequest()->getIsPostRequest())
  3685. $filterChain->run();
  3686. else
  3687. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3688. }
  3689. public function filterAjaxOnly($filterChain)
  3690. {
  3691. if(Yii::app()->getRequest()->getIsAjaxRequest())
  3692. $filterChain->run();
  3693. else
  3694. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3695. }
  3696. public function filterAccessControl($filterChain)
  3697. {
  3698. $filter=new CAccessControlFilter;
  3699. $filter->setRules($this->accessRules());
  3700. $filter->filter($filterChain);
  3701. }
  3702. public function getPageState($name,$defaultValue=null)
  3703. {
  3704. if($this->_pageStates===null)
  3705. $this->_pageStates=$this->loadPageStates();
  3706. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  3707. }
  3708. public function setPageState($name,$value,$defaultValue=null)
  3709. {
  3710. if($this->_pageStates===null)
  3711. $this->_pageStates=$this->loadPageStates();
  3712. if($value===$defaultValue)
  3713. unset($this->_pageStates[$name]);
  3714. else
  3715. $this->_pageStates[$name]=$value;
  3716. $params=func_get_args();
  3717. $this->recordCachingAction('','setPageState',$params);
  3718. }
  3719. public function clearPageStates()
  3720. {
  3721. $this->_pageStates=array();
  3722. }
  3723. protected function loadPageStates()
  3724. {
  3725. if(!empty($_POST[self::STATE_INPUT_NAME]))
  3726. {
  3727. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  3728. {
  3729. if(extension_loaded('zlib'))
  3730. $data=@gzuncompress($data);
  3731. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  3732. return unserialize($data);
  3733. }
  3734. }
  3735. return array();
  3736. }
  3737. protected function savePageStates($states,&$output)
  3738. {
  3739. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  3740. if(extension_loaded('zlib'))
  3741. $data=gzcompress($data);
  3742. $value=base64_encode($data);
  3743. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  3744. }
  3745. }
  3746. abstract class CAction extends CComponent implements IAction
  3747. {
  3748. private $_id;
  3749. private $_controller;
  3750. public function __construct($controller,$id)
  3751. {
  3752. $this->_controller=$controller;
  3753. $this->_id=$id;
  3754. }
  3755. public function getController()
  3756. {
  3757. return $this->_controller;
  3758. }
  3759. public function getId()
  3760. {
  3761. return $this->_id;
  3762. }
  3763. public function runWithParams($params)
  3764. {
  3765. $method=new ReflectionMethod($this, 'run');
  3766. if($method->getNumberOfParameters()>0)
  3767. return $this->runWithParamsInternal($this, $method, $params);
  3768. else
  3769. return $this->run();
  3770. }
  3771. protected function runWithParamsInternal($object, $method, $params)
  3772. {
  3773. $ps=array();
  3774. foreach($method->getParameters() as $i=>$param)
  3775. {
  3776. $name=$param->getName();
  3777. if(isset($params[$name]))
  3778. {
  3779. if($param->isArray())
  3780. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  3781. else if(!is_array($params[$name]))
  3782. $ps[]=$params[$name];
  3783. else
  3784. return false;
  3785. }
  3786. else if($param->isDefaultValueAvailable())
  3787. $ps[]=$param->getDefaultValue();
  3788. else
  3789. return false;
  3790. }
  3791. $method->invokeArgs($object,$ps);
  3792. return true;
  3793. }
  3794. }
  3795. class CInlineAction extends CAction
  3796. {
  3797. public function run()
  3798. {
  3799. $method='action'.$this->getId();
  3800. $this->getController()->$method();
  3801. }
  3802. public function runWithParams($params)
  3803. {
  3804. $methodName='action'.$this->getId();
  3805. $controller=$this->getController();
  3806. $method=new ReflectionMethod($controller, $methodName);
  3807. if($method->getNumberOfParameters()>0)
  3808. return $this->runWithParamsInternal($controller, $method, $params);
  3809. else
  3810. return $controller->$methodName();
  3811. }
  3812. }
  3813. class CWebUser extends CApplicationComponent implements IWebUser
  3814. {
  3815. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  3816. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  3817. const STATES_VAR='__states';
  3818. const AUTH_TIMEOUT_VAR='__timeout';
  3819. public $allowAutoLogin=false;
  3820. public $guestName='Guest';
  3821. public $loginUrl=array('/site/login');
  3822. public $identityCookie;
  3823. public $authTimeout;
  3824. public $autoRenewCookie=false;
  3825. public $autoUpdateFlash=true;
  3826. public $loginRequiredAjaxResponse;
  3827. private $_keyPrefix;
  3828. private $_access=array();
  3829. public function __get($name)
  3830. {
  3831. if($this->hasState($name))
  3832. return $this->getState($name);
  3833. else
  3834. return parent::__get($name);
  3835. }
  3836. public function __set($name,$value)
  3837. {
  3838. if($this->hasState($name))
  3839. $this->setState($name,$value);
  3840. else
  3841. parent::__set($name,$value);
  3842. }
  3843. public function __isset($name)
  3844. {
  3845. if($this->hasState($name))
  3846. return $this->getState($name)!==null;
  3847. else
  3848. return parent::__isset($name);
  3849. }
  3850. public function __unset($name)
  3851. {
  3852. if($this->hasState($name))
  3853. $this->setState($name,null);
  3854. else
  3855. parent::__unset($name);
  3856. }
  3857. public function init()
  3858. {
  3859. parent::init();
  3860. Yii::app()->getSession()->open();
  3861. if($this->getIsGuest() && $this->allowAutoLogin)
  3862. $this->restoreFromCookie();
  3863. else if($this->autoRenewCookie && $this->allowAutoLogin)
  3864. $this->renewCookie();
  3865. if($this->autoUpdateFlash)
  3866. $this->updateFlash();
  3867. $this->updateAuthStatus();
  3868. }
  3869. public function login($identity,$duration=0)
  3870. {
  3871. $id=$identity->getId();
  3872. $states=$identity->getPersistentStates();
  3873. if($this->beforeLogin($id,$states,false))
  3874. {
  3875. $this->changeIdentity($id,$identity->getName(),$states);
  3876. if($duration>0)
  3877. {
  3878. if($this->allowAutoLogin)
  3879. $this->saveToCookie($duration);
  3880. else
  3881. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  3882. array('{class}'=>get_class($this))));
  3883. }
  3884. $this->afterLogin(false);
  3885. }
  3886. return !$this->getIsGuest();
  3887. }
  3888. public function logout($destroySession=true)
  3889. {
  3890. if($this->beforeLogout())
  3891. {
  3892. if($this->allowAutoLogin)
  3893. {
  3894. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  3895. if($this->identityCookie!==null)
  3896. {
  3897. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3898. $cookie->value=null;
  3899. $cookie->expire=0;
  3900. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  3901. }
  3902. }
  3903. if($destroySession)
  3904. Yii::app()->getSession()->destroy();
  3905. else
  3906. $this->clearStates();
  3907. $this->afterLogout();
  3908. }
  3909. }
  3910. public function getIsGuest()
  3911. {
  3912. return $this->getState('__id')===null;
  3913. }
  3914. public function getId()
  3915. {
  3916. return $this->getState('__id');
  3917. }
  3918. public function setId($value)
  3919. {
  3920. $this->setState('__id',$value);
  3921. }
  3922. public function getName()
  3923. {
  3924. if(($name=$this->getState('__name'))!==null)
  3925. return $name;
  3926. else
  3927. return $this->guestName;
  3928. }
  3929. public function setName($value)
  3930. {
  3931. $this->setState('__name',$value);
  3932. }
  3933. public function getReturnUrl($defaultUrl=null)
  3934. {
  3935. return $this->getState('__returnUrl', $defaultUrl===null ? Yii::app()->getRequest()->getScriptUrl() : CHtml::normalizeUrl($defaultUrl));
  3936. }
  3937. public function setReturnUrl($value)
  3938. {
  3939. $this->setState('__returnUrl',$value);
  3940. }
  3941. public function loginRequired()
  3942. {
  3943. $app=Yii::app();
  3944. $request=$app->getRequest();
  3945. if(!$request->getIsAjaxRequest())
  3946. $this->setReturnUrl($request->getUrl());
  3947. elseif(isset($this->loginRequiredAjaxResponse))
  3948. {
  3949. echo $this->loginRequiredAjaxResponse;
  3950. Yii::app()->end();
  3951. }
  3952. if(($url=$this->loginUrl)!==null)
  3953. {
  3954. if(is_array($url))
  3955. {
  3956. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  3957. $url=$app->createUrl($route,array_splice($url,1));
  3958. }
  3959. $request->redirect($url);
  3960. }
  3961. else
  3962. throw new CHttpException(403,Yii::t('yii','Login Required'));
  3963. }
  3964. protected function beforeLogin($id,$states,$fromCookie)
  3965. {
  3966. return true;
  3967. }
  3968. protected function afterLogin($fromCookie)
  3969. {
  3970. }
  3971. protected function beforeLogout()
  3972. {
  3973. return true;
  3974. }
  3975. protected function afterLogout()
  3976. {
  3977. }
  3978. protected function restoreFromCookie()
  3979. {
  3980. $app=Yii::app();
  3981. $request=$app->getRequest();
  3982. $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  3983. if($cookie && !empty($cookie->value) && is_string($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  3984. {
  3985. $data=@unserialize($data);
  3986. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3987. {
  3988. list($id,$name,$duration,$states)=$data;
  3989. if($this->beforeLogin($id,$states,true))
  3990. {
  3991. $this->changeIdentity($id,$name,$states);
  3992. if($this->autoRenewCookie)
  3993. {
  3994. $cookie->expire=time()+$duration;
  3995. $request->getCookies()->add($cookie->name,$cookie);
  3996. }
  3997. $this->afterLogin(true);
  3998. }
  3999. }
  4000. }
  4001. }
  4002. protected function renewCookie()
  4003. {
  4004. $request=Yii::app()->getRequest();
  4005. $cookies=$request->getCookies();
  4006. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  4007. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  4008. {
  4009. $data=@unserialize($data);
  4010. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4011. {
  4012. $cookie->expire=time()+$data[2];
  4013. $cookies->add($cookie->name,$cookie);
  4014. }
  4015. }
  4016. }
  4017. protected function saveToCookie($duration)
  4018. {
  4019. $app=Yii::app();
  4020. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4021. $cookie->expire=time()+$duration;
  4022. $data=array(
  4023. $this->getId(),
  4024. $this->getName(),
  4025. $duration,
  4026. $this->saveIdentityStates(),
  4027. );
  4028. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  4029. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  4030. }
  4031. protected function createIdentityCookie($name)
  4032. {
  4033. $cookie=new CHttpCookie($name,'');
  4034. if(is_array($this->identityCookie))
  4035. {
  4036. foreach($this->identityCookie as $name=>$value)
  4037. $cookie->$name=$value;
  4038. }
  4039. return $cookie;
  4040. }
  4041. public function getStateKeyPrefix()
  4042. {
  4043. if($this->_keyPrefix!==null)
  4044. return $this->_keyPrefix;
  4045. else
  4046. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  4047. }
  4048. public function setStateKeyPrefix($value)
  4049. {
  4050. $this->_keyPrefix=$value;
  4051. }
  4052. public function getState($key,$defaultValue=null)
  4053. {
  4054. $key=$this->getStateKeyPrefix().$key;
  4055. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4056. }
  4057. public function setState($key,$value,$defaultValue=null)
  4058. {
  4059. $key=$this->getStateKeyPrefix().$key;
  4060. if($value===$defaultValue)
  4061. unset($_SESSION[$key]);
  4062. else
  4063. $_SESSION[$key]=$value;
  4064. }
  4065. public function hasState($key)
  4066. {
  4067. $key=$this->getStateKeyPrefix().$key;
  4068. return isset($_SESSION[$key]);
  4069. }
  4070. public function clearStates()
  4071. {
  4072. $keys=array_keys($_SESSION);
  4073. $prefix=$this->getStateKeyPrefix();
  4074. $n=strlen($prefix);
  4075. foreach($keys as $key)
  4076. {
  4077. if(!strncmp($key,$prefix,$n))
  4078. unset($_SESSION[$key]);
  4079. }
  4080. }
  4081. public function getFlashes($delete=true)
  4082. {
  4083. $flashes=array();
  4084. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  4085. $keys=array_keys($_SESSION);
  4086. $n=strlen($prefix);
  4087. foreach($keys as $key)
  4088. {
  4089. if(!strncmp($key,$prefix,$n))
  4090. {
  4091. $flashes[substr($key,$n)]=$_SESSION[$key];
  4092. if($delete)
  4093. unset($_SESSION[$key]);
  4094. }
  4095. }
  4096. if($delete)
  4097. $this->setState(self::FLASH_COUNTERS,array());
  4098. return $flashes;
  4099. }
  4100. public function getFlash($key,$defaultValue=null,$delete=true)
  4101. {
  4102. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4103. if($delete)
  4104. $this->setFlash($key,null);
  4105. return $value;
  4106. }
  4107. public function setFlash($key,$value,$defaultValue=null)
  4108. {
  4109. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4110. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4111. if($value===$defaultValue)
  4112. unset($counters[$key]);
  4113. else
  4114. $counters[$key]=0;
  4115. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4116. }
  4117. public function hasFlash($key)
  4118. {
  4119. return $this->getFlash($key, null, false)!==null;
  4120. }
  4121. protected function changeIdentity($id,$name,$states)
  4122. {
  4123. Yii::app()->getSession()->regenerateID(true);
  4124. $this->setId($id);
  4125. $this->setName($name);
  4126. $this->loadIdentityStates($states);
  4127. }
  4128. protected function saveIdentityStates()
  4129. {
  4130. $states=array();
  4131. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4132. $states[$name]=$this->getState($name);
  4133. return $states;
  4134. }
  4135. protected function loadIdentityStates($states)
  4136. {
  4137. $names=array();
  4138. if(is_array($states))
  4139. {
  4140. foreach($states as $name=>$value)
  4141. {
  4142. $this->setState($name,$value);
  4143. $names[$name]=true;
  4144. }
  4145. }
  4146. $this->setState(self::STATES_VAR,$names);
  4147. }
  4148. protected function updateFlash()
  4149. {
  4150. $counters=$this->getState(self::FLASH_COUNTERS);
  4151. if(!is_array($counters))
  4152. return;
  4153. foreach($counters as $key=>$count)
  4154. {
  4155. if($count)
  4156. {
  4157. unset($counters[$key]);
  4158. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4159. }
  4160. else
  4161. $counters[$key]++;
  4162. }
  4163. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4164. }
  4165. protected function updateAuthStatus()
  4166. {
  4167. if($this->authTimeout!==null && !$this->getIsGuest())
  4168. {
  4169. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4170. if ($expires!==null && $expires < time())
  4171. $this->logout(false);
  4172. else
  4173. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4174. }
  4175. }
  4176. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4177. {
  4178. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4179. return $this->_access[$operation];
  4180. $access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4181. if($allowCaching && $params===array())
  4182. $this->_access[$operation]=$access;
  4183. return $access;
  4184. }
  4185. }
  4186. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4187. {
  4188. public $autoStart=true;
  4189. public function init()
  4190. {
  4191. parent::init();
  4192. if($this->autoStart)
  4193. $this->open();
  4194. register_shutdown_function(array($this,'close'));
  4195. }
  4196. public function getUseCustomStorage()
  4197. {
  4198. return false;
  4199. }
  4200. public function open()
  4201. {
  4202. if($this->getUseCustomStorage())
  4203. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4204. @session_start();
  4205. if(YII_DEBUG && session_id()=='')
  4206. {
  4207. $message=Yii::t('yii','Failed to start session.');
  4208. if(function_exists('error_get_last'))
  4209. {
  4210. $error=error_get_last();
  4211. if(isset($error['message']))
  4212. $message=$error['message'];
  4213. }
  4214. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4215. }
  4216. }
  4217. public function close()
  4218. {
  4219. if(session_id()!=='')
  4220. @session_write_close();
  4221. }
  4222. public function destroy()
  4223. {
  4224. if(session_id()!=='')
  4225. {
  4226. @session_unset();
  4227. @session_destroy();
  4228. }
  4229. }
  4230. public function getIsStarted()
  4231. {
  4232. return session_id()!=='';
  4233. }
  4234. public function getSessionID()
  4235. {
  4236. return session_id();
  4237. }
  4238. public function setSessionID($value)
  4239. {
  4240. session_id($value);
  4241. }
  4242. public function regenerateID($deleteOldSession=false)
  4243. {
  4244. session_regenerate_id($deleteOldSession);
  4245. }
  4246. public function getSessionName()
  4247. {
  4248. return session_name();
  4249. }
  4250. public function setSessionName($value)
  4251. {
  4252. session_name($value);
  4253. }
  4254. public function getSavePath()
  4255. {
  4256. return session_save_path();
  4257. }
  4258. public function setSavePath($value)
  4259. {
  4260. if(is_dir($value))
  4261. session_save_path($value);
  4262. else
  4263. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4264. array('{path}'=>$value)));
  4265. }
  4266. public function getCookieParams()
  4267. {
  4268. return session_get_cookie_params();
  4269. }
  4270. public function setCookieParams($value)
  4271. {
  4272. $data=session_get_cookie_params();
  4273. extract($data);
  4274. extract($value);
  4275. if(isset($httponly))
  4276. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4277. else
  4278. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4279. }
  4280. public function getCookieMode()
  4281. {
  4282. if(ini_get('session.use_cookies')==='0')
  4283. return 'none';
  4284. else if(ini_get('session.use_only_cookies')==='0')
  4285. return 'allow';
  4286. else
  4287. return 'only';
  4288. }
  4289. public function setCookieMode($value)
  4290. {
  4291. if($value==='none')
  4292. {
  4293. ini_set('session.use_cookies','0');
  4294. ini_set('session.use_only_cookies','0');
  4295. }
  4296. else if($value==='allow')
  4297. {
  4298. ini_set('session.use_cookies','1');
  4299. ini_set('session.use_only_cookies','0');
  4300. }
  4301. else if($value==='only')
  4302. {
  4303. ini_set('session.use_cookies','1');
  4304. ini_set('session.use_only_cookies','1');
  4305. }
  4306. else
  4307. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4308. }
  4309. public function getGCProbability()
  4310. {
  4311. return (int)ini_get('session.gc_probability');
  4312. }
  4313. public function setGCProbability($value)
  4314. {
  4315. $value=(int)$value;
  4316. if($value>=0 && $value<=100)
  4317. {
  4318. ini_set('session.gc_probability',$value);
  4319. ini_set('session.gc_divisor','100');
  4320. }
  4321. else
  4322. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be an integer between 0 and 100.',
  4323. array('{value}'=>$value)));
  4324. }
  4325. public function getUseTransparentSessionID()
  4326. {
  4327. return ini_get('session.use_trans_sid')==1;
  4328. }
  4329. public function setUseTransparentSessionID($value)
  4330. {
  4331. ini_set('session.use_trans_sid',$value?'1':'0');
  4332. }
  4333. public function getTimeout()
  4334. {
  4335. return (int)ini_get('session.gc_maxlifetime');
  4336. }
  4337. public function setTimeout($value)
  4338. {
  4339. ini_set('session.gc_maxlifetime',$value);
  4340. }
  4341. public function openSession($savePath,$sessionName)
  4342. {
  4343. return true;
  4344. }
  4345. public function closeSession()
  4346. {
  4347. return true;
  4348. }
  4349. public function readSession($id)
  4350. {
  4351. return '';
  4352. }
  4353. public function writeSession($id,$data)
  4354. {
  4355. return true;
  4356. }
  4357. public function destroySession($id)
  4358. {
  4359. return true;
  4360. }
  4361. public function gcSession($maxLifetime)
  4362. {
  4363. return true;
  4364. }
  4365. //------ The following methods enable CHttpSession to be CMap-like -----
  4366. public function getIterator()
  4367. {
  4368. return new CHttpSessionIterator;
  4369. }
  4370. public function getCount()
  4371. {
  4372. return count($_SESSION);
  4373. }
  4374. public function count()
  4375. {
  4376. return $this->getCount();
  4377. }
  4378. public function getKeys()
  4379. {
  4380. return array_keys($_SESSION);
  4381. }
  4382. public function get($key,$defaultValue=null)
  4383. {
  4384. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4385. }
  4386. public function itemAt($key)
  4387. {
  4388. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4389. }
  4390. public function add($key,$value)
  4391. {
  4392. $_SESSION[$key]=$value;
  4393. }
  4394. public function remove($key)
  4395. {
  4396. if(isset($_SESSION[$key]))
  4397. {
  4398. $value=$_SESSION[$key];
  4399. unset($_SESSION[$key]);
  4400. return $value;
  4401. }
  4402. else
  4403. return null;
  4404. }
  4405. public function clear()
  4406. {
  4407. foreach(array_keys($_SESSION) as $key)
  4408. unset($_SESSION[$key]);
  4409. }
  4410. public function contains($key)
  4411. {
  4412. return isset($_SESSION[$key]);
  4413. }
  4414. public function toArray()
  4415. {
  4416. return $_SESSION;
  4417. }
  4418. public function offsetExists($offset)
  4419. {
  4420. return isset($_SESSION[$offset]);
  4421. }
  4422. public function offsetGet($offset)
  4423. {
  4424. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4425. }
  4426. public function offsetSet($offset,$item)
  4427. {
  4428. $_SESSION[$offset]=$item;
  4429. }
  4430. public function offsetUnset($offset)
  4431. {
  4432. unset($_SESSION[$offset]);
  4433. }
  4434. }
  4435. class CHtml
  4436. {
  4437. const ID_PREFIX='yt';
  4438. public static $errorSummaryCss='errorSummary';
  4439. public static $errorMessageCss='errorMessage';
  4440. public static $errorCss='error';
  4441. public static $requiredCss='required';
  4442. public static $beforeRequiredLabel='';
  4443. public static $afterRequiredLabel=' <span class="required">*</span>';
  4444. public static $count=0;
  4445. public static $liveEvents = true;
  4446. public static function encode($text)
  4447. {
  4448. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4449. }
  4450. public static function decode($text)
  4451. {
  4452. return htmlspecialchars_decode($text,ENT_QUOTES);
  4453. }
  4454. public static function encodeArray($data)
  4455. {
  4456. $d=array();
  4457. foreach($data as $key=>$value)
  4458. {
  4459. if(is_string($key))
  4460. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4461. if(is_string($value))
  4462. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4463. else if(is_array($value))
  4464. $value=self::encodeArray($value);
  4465. $d[$key]=$value;
  4466. }
  4467. return $d;
  4468. }
  4469. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4470. {
  4471. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4472. if($content===false)
  4473. return $closeTag ? $html.' />' : $html.'>';
  4474. else
  4475. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4476. }
  4477. public static function openTag($tag,$htmlOptions=array())
  4478. {
  4479. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4480. }
  4481. public static function closeTag($tag)
  4482. {
  4483. return '</'.$tag.'>';
  4484. }
  4485. public static function cdata($text)
  4486. {
  4487. return '<![CDATA[' . $text . ']]>';
  4488. }
  4489. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4490. {
  4491. if($name!==null)
  4492. $options['name']=$name;
  4493. if($httpEquiv!==null)
  4494. $options['http-equiv']=$httpEquiv;
  4495. $options['content']=$content;
  4496. return self::tag('meta',$options);
  4497. }
  4498. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4499. {
  4500. if($relation!==null)
  4501. $options['rel']=$relation;
  4502. if($type!==null)
  4503. $options['type']=$type;
  4504. if($href!==null)
  4505. $options['href']=$href;
  4506. if($media!==null)
  4507. $options['media']=$media;
  4508. return self::tag('link',$options);
  4509. }
  4510. public static function css($text,$media='')
  4511. {
  4512. if($media!=='')
  4513. $media=' media="'.$media.'"';
  4514. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4515. }
  4516. public static function refresh($seconds, $url='')
  4517. {
  4518. $content="$seconds";
  4519. if($url!=='')
  4520. $content.=';'.self::normalizeUrl($url);
  4521. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4522. }
  4523. public static function cssFile($url,$media='')
  4524. {
  4525. if($media!=='')
  4526. $media=' media="'.$media.'"';
  4527. return '<link rel="stylesheet" type="text/css" href="'.self::encode($url).'"'.$media.' />';
  4528. }
  4529. public static function script($text)
  4530. {
  4531. return "<script type=\"text/javascript\">\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</script>";
  4532. }
  4533. public static function scriptFile($url)
  4534. {
  4535. return '<script type="text/javascript" src="'.self::encode($url).'"></script>';
  4536. }
  4537. public static function form($action='',$method='post',$htmlOptions=array())
  4538. {
  4539. return self::beginForm($action,$method,$htmlOptions);
  4540. }
  4541. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4542. {
  4543. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4544. $htmlOptions['method']=$method;
  4545. $form=self::tag('form',$htmlOptions,false,false);
  4546. $hiddens=array();
  4547. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4548. {
  4549. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4550. {
  4551. if(($pos=strpos($pair,'='))!==false)
  4552. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4553. }
  4554. }
  4555. $request=Yii::app()->request;
  4556. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4557. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4558. if($hiddens!==array())
  4559. $form.="\n".self::tag('div',array('style'=>'display:none'),implode("\n",$hiddens));
  4560. return $form;
  4561. }
  4562. public static function endForm()
  4563. {
  4564. return '</form>';
  4565. }
  4566. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4567. {
  4568. return self::form($action,$method,$htmlOptions)."\n".
  4569. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4570. }
  4571. public static function pageStateField($value)
  4572. {
  4573. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4574. }
  4575. public static function link($text,$url='#',$htmlOptions=array())
  4576. {
  4577. if($url!=='')
  4578. $htmlOptions['href']=self::normalizeUrl($url);
  4579. self::clientChange('click',$htmlOptions);
  4580. return self::tag('a',$htmlOptions,$text);
  4581. }
  4582. public static function mailto($text,$email='',$htmlOptions=array())
  4583. {
  4584. if($email==='')
  4585. $email=$text;
  4586. return self::link($text,'mailto:'.$email,$htmlOptions);
  4587. }
  4588. public static function image($src,$alt='',$htmlOptions=array())
  4589. {
  4590. $htmlOptions['src']=$src;
  4591. $htmlOptions['alt']=$alt;
  4592. return self::tag('img',$htmlOptions);
  4593. }
  4594. public static function button($label='button',$htmlOptions=array())
  4595. {
  4596. if(!isset($htmlOptions['name']))
  4597. {
  4598. if(!array_key_exists('name',$htmlOptions))
  4599. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4600. }
  4601. if(!isset($htmlOptions['type']))
  4602. $htmlOptions['type']='button';
  4603. if(!isset($htmlOptions['value']))
  4604. $htmlOptions['value']=$label;
  4605. self::clientChange('click',$htmlOptions);
  4606. return self::tag('input',$htmlOptions);
  4607. }
  4608. public static function htmlButton($label='button',$htmlOptions=array())
  4609. {
  4610. if(!isset($htmlOptions['name']))
  4611. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4612. if(!isset($htmlOptions['type']))
  4613. $htmlOptions['type']='button';
  4614. self::clientChange('click',$htmlOptions);
  4615. return self::tag('button',$htmlOptions,$label);
  4616. }
  4617. public static function submitButton($label='submit',$htmlOptions=array())
  4618. {
  4619. $htmlOptions['type']='submit';
  4620. return self::button($label,$htmlOptions);
  4621. }
  4622. public static function resetButton($label='reset',$htmlOptions=array())
  4623. {
  4624. $htmlOptions['type']='reset';
  4625. return self::button($label,$htmlOptions);
  4626. }
  4627. public static function imageButton($src,$htmlOptions=array())
  4628. {
  4629. $htmlOptions['src']=$src;
  4630. $htmlOptions['type']='image';
  4631. return self::button('submit',$htmlOptions);
  4632. }
  4633. public static function linkButton($label='submit',$htmlOptions=array())
  4634. {
  4635. if(!isset($htmlOptions['submit']))
  4636. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  4637. return self::link($label,'#',$htmlOptions);
  4638. }
  4639. public static function label($label,$for,$htmlOptions=array())
  4640. {
  4641. if($for===false)
  4642. unset($htmlOptions['for']);
  4643. else
  4644. $htmlOptions['for']=$for;
  4645. if(isset($htmlOptions['required']))
  4646. {
  4647. if($htmlOptions['required'])
  4648. {
  4649. if(isset($htmlOptions['class']))
  4650. $htmlOptions['class'].=' '.self::$requiredCss;
  4651. else
  4652. $htmlOptions['class']=self::$requiredCss;
  4653. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  4654. }
  4655. unset($htmlOptions['required']);
  4656. }
  4657. return self::tag('label',$htmlOptions,$label);
  4658. }
  4659. public static function textField($name,$value='',$htmlOptions=array())
  4660. {
  4661. self::clientChange('change',$htmlOptions);
  4662. return self::inputField('text',$name,$value,$htmlOptions);
  4663. }
  4664. public static function hiddenField($name,$value='',$htmlOptions=array())
  4665. {
  4666. return self::inputField('hidden',$name,$value,$htmlOptions);
  4667. }
  4668. public static function passwordField($name,$value='',$htmlOptions=array())
  4669. {
  4670. self::clientChange('change',$htmlOptions);
  4671. return self::inputField('password',$name,$value,$htmlOptions);
  4672. }
  4673. public static function fileField($name,$value='',$htmlOptions=array())
  4674. {
  4675. return self::inputField('file',$name,$value,$htmlOptions);
  4676. }
  4677. public static function textArea($name,$value='',$htmlOptions=array())
  4678. {
  4679. $htmlOptions['name']=$name;
  4680. if(!isset($htmlOptions['id']))
  4681. $htmlOptions['id']=self::getIdByName($name);
  4682. else if($htmlOptions['id']===false)
  4683. unset($htmlOptions['id']);
  4684. self::clientChange('change',$htmlOptions);
  4685. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  4686. }
  4687. public static function radioButton($name,$checked=false,$htmlOptions=array())
  4688. {
  4689. if($checked)
  4690. $htmlOptions['checked']='checked';
  4691. else
  4692. unset($htmlOptions['checked']);
  4693. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4694. self::clientChange('click',$htmlOptions);
  4695. if(array_key_exists('uncheckValue',$htmlOptions))
  4696. {
  4697. $uncheck=$htmlOptions['uncheckValue'];
  4698. unset($htmlOptions['uncheckValue']);
  4699. }
  4700. else
  4701. $uncheck=null;
  4702. if($uncheck!==null)
  4703. {
  4704. // add a hidden field so that if the radio button is not selected, it still submits a value
  4705. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4706. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4707. else
  4708. $uncheckOptions=array('id'=>false);
  4709. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4710. }
  4711. else
  4712. $hidden='';
  4713. // add a hidden field so that if the radio button is not selected, it still submits a value
  4714. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  4715. }
  4716. public static function checkBox($name,$checked=false,$htmlOptions=array())
  4717. {
  4718. if($checked)
  4719. $htmlOptions['checked']='checked';
  4720. else
  4721. unset($htmlOptions['checked']);
  4722. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4723. self::clientChange('click',$htmlOptions);
  4724. if(array_key_exists('uncheckValue',$htmlOptions))
  4725. {
  4726. $uncheck=$htmlOptions['uncheckValue'];
  4727. unset($htmlOptions['uncheckValue']);
  4728. }
  4729. else
  4730. $uncheck=null;
  4731. if($uncheck!==null)
  4732. {
  4733. // add a hidden field so that if the radio button is not selected, it still submits a value
  4734. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4735. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4736. else
  4737. $uncheckOptions=array('id'=>false);
  4738. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4739. }
  4740. else
  4741. $hidden='';
  4742. // add a hidden field so that if the checkbox is not selected, it still submits a value
  4743. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  4744. }
  4745. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  4746. {
  4747. $htmlOptions['name']=$name;
  4748. if(!isset($htmlOptions['id']))
  4749. $htmlOptions['id']=self::getIdByName($name);
  4750. else if($htmlOptions['id']===false)
  4751. unset($htmlOptions['id']);
  4752. self::clientChange('change',$htmlOptions);
  4753. $options="\n".self::listOptions($select,$data,$htmlOptions);
  4754. return self::tag('select',$htmlOptions,$options);
  4755. }
  4756. public static function listBox($name,$select,$data,$htmlOptions=array())
  4757. {
  4758. if(!isset($htmlOptions['size']))
  4759. $htmlOptions['size']=4;
  4760. if(isset($htmlOptions['multiple']))
  4761. {
  4762. if(substr($name,-2)!=='[]')
  4763. $name.='[]';
  4764. }
  4765. return self::dropDownList($name,$select,$data,$htmlOptions);
  4766. }
  4767. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  4768. {
  4769. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4770. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4771. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  4772. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  4773. if(substr($name,-2)!=='[]')
  4774. $name.='[]';
  4775. if(isset($htmlOptions['checkAll']))
  4776. {
  4777. $checkAllLabel=$htmlOptions['checkAll'];
  4778. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  4779. }
  4780. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  4781. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4782. unset($htmlOptions['labelOptions']);
  4783. $items=array();
  4784. $baseID=self::getIdByName($name);
  4785. $id=0;
  4786. $checkAll=true;
  4787. foreach($data as $value=>$label)
  4788. {
  4789. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  4790. $checkAll=$checkAll && $checked;
  4791. $htmlOptions['value']=$value;
  4792. $htmlOptions['id']=$baseID.'_'.$id++;
  4793. $option=self::checkBox($name,$checked,$htmlOptions);
  4794. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4795. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4796. }
  4797. if(isset($checkAllLabel))
  4798. {
  4799. $htmlOptions['value']=1;
  4800. $htmlOptions['id']=$id=$baseID.'_all';
  4801. $option=self::checkBox($id,$checkAll,$htmlOptions);
  4802. $label=self::label($checkAllLabel,$id,$labelOptions);
  4803. $item=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4804. if($checkAllLast)
  4805. $items[]=$item;
  4806. else
  4807. array_unshift($items,$item);
  4808. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  4809. $js=<<<EOD
  4810. $('#$id').click(function() {
  4811. $("input[name='$name']").prop('checked', this.checked);
  4812. });
  4813. $("input[name='$name']").click(function() {
  4814. $('#$id').prop('checked', !$("input[name='$name']:not(:checked)").length);
  4815. });
  4816. $('#$id').prop('checked', !$("input[name='$name']:not(:checked)").length);
  4817. EOD;
  4818. $cs=Yii::app()->getClientScript();
  4819. $cs->registerCoreScript('jquery');
  4820. $cs->registerScript($id,$js);
  4821. }
  4822. if(empty($container))
  4823. return implode($separator,$items);
  4824. else
  4825. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  4826. }
  4827. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  4828. {
  4829. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4830. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4831. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  4832. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  4833. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4834. unset($htmlOptions['labelOptions']);
  4835. $items=array();
  4836. $baseID=self::getIdByName($name);
  4837. $id=0;
  4838. foreach($data as $value=>$label)
  4839. {
  4840. $checked=!strcmp($value,$select);
  4841. $htmlOptions['value']=$value;
  4842. $htmlOptions['id']=$baseID.'_'.$id++;
  4843. $option=self::radioButton($name,$checked,$htmlOptions);
  4844. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4845. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4846. }
  4847. if(empty($container))
  4848. return implode($separator,$items);
  4849. else
  4850. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  4851. }
  4852. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  4853. {
  4854. if(!isset($htmlOptions['href']))
  4855. $htmlOptions['href']='#';
  4856. $ajaxOptions['url']=$url;
  4857. $htmlOptions['ajax']=$ajaxOptions;
  4858. self::clientChange('click',$htmlOptions);
  4859. return self::tag('a',$htmlOptions,$text);
  4860. }
  4861. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4862. {
  4863. $ajaxOptions['url']=$url;
  4864. $htmlOptions['ajax']=$ajaxOptions;
  4865. return self::button($label,$htmlOptions);
  4866. }
  4867. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4868. {
  4869. $ajaxOptions['type']='POST';
  4870. $htmlOptions['type']='submit';
  4871. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  4872. }
  4873. public static function ajax($options)
  4874. {
  4875. Yii::app()->getClientScript()->registerCoreScript('jquery');
  4876. if(!isset($options['url']))
  4877. $options['url']=new CJavaScriptExpression('location.href');
  4878. else
  4879. $options['url']=self::normalizeUrl($options['url']);
  4880. if(!isset($options['cache']))
  4881. $options['cache']=false;
  4882. if(!isset($options['data']) && isset($options['type']))
  4883. $options['data']=new CJavaScriptExpression('jQuery(this).parents("form").serialize()');
  4884. foreach(array('beforeSend','complete','error','success') as $name)
  4885. {
  4886. if(isset($options[$name]) && !($options[$name] instanceof CJavaScriptExpression))
  4887. $options[$name]=new CJavaScriptExpression($options[$name]);
  4888. }
  4889. if(isset($options['update']))
  4890. {
  4891. if(!isset($options['success']))
  4892. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['update'].'").html(html)}');
  4893. unset($options['update']);
  4894. }
  4895. if(isset($options['replace']))
  4896. {
  4897. if(!isset($options['success']))
  4898. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['replace'].'").replaceWith(html)}');
  4899. unset($options['replace']);
  4900. }
  4901. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  4902. }
  4903. public static function asset($path,$hashByName=false)
  4904. {
  4905. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  4906. }
  4907. public static function normalizeUrl($url)
  4908. {
  4909. if(is_array($url))
  4910. {
  4911. if(isset($url[0]))
  4912. {
  4913. if(($c=Yii::app()->getController())!==null)
  4914. $url=$c->createUrl($url[0],array_splice($url,1));
  4915. else
  4916. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  4917. }
  4918. else
  4919. $url='';
  4920. }
  4921. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  4922. }
  4923. protected static function inputField($type,$name,$value,$htmlOptions)
  4924. {
  4925. $htmlOptions['type']=$type;
  4926. $htmlOptions['value']=$value;
  4927. $htmlOptions['name']=$name;
  4928. if(!isset($htmlOptions['id']))
  4929. $htmlOptions['id']=self::getIdByName($name);
  4930. else if($htmlOptions['id']===false)
  4931. unset($htmlOptions['id']);
  4932. return self::tag('input',$htmlOptions);
  4933. }
  4934. public static function activeLabel($model,$attribute,$htmlOptions=array())
  4935. {
  4936. if(isset($htmlOptions['for']))
  4937. {
  4938. $for=$htmlOptions['for'];
  4939. unset($htmlOptions['for']);
  4940. }
  4941. else
  4942. $for=self::getIdByName(self::resolveName($model,$attribute));
  4943. if(isset($htmlOptions['label']))
  4944. {
  4945. if(($label=$htmlOptions['label'])===false)
  4946. return '';
  4947. unset($htmlOptions['label']);
  4948. }
  4949. else
  4950. $label=$model->getAttributeLabel($attribute);
  4951. if($model->hasErrors($attribute))
  4952. self::addErrorCss($htmlOptions);
  4953. return self::label($label,$for,$htmlOptions);
  4954. }
  4955. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  4956. {
  4957. $realAttribute=$attribute;
  4958. self::resolveName($model,$attribute); // strip off square brackets if any
  4959. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  4960. return self::activeLabel($model,$realAttribute,$htmlOptions);
  4961. }
  4962. public static function activeTextField($model,$attribute,$htmlOptions=array())
  4963. {
  4964. self::resolveNameID($model,$attribute,$htmlOptions);
  4965. self::clientChange('change',$htmlOptions);
  4966. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  4967. }
  4968. public static function activeUrlField($model,$attribute,$htmlOptions=array())
  4969. {
  4970. self::resolveNameID($model,$attribute,$htmlOptions);
  4971. self::clientChange('change',$htmlOptions);
  4972. return self::activeInputField('url',$model,$attribute,$htmlOptions);
  4973. }
  4974. public static function activeEmailField($model,$attribute,$htmlOptions=array())
  4975. {
  4976. self::resolveNameID($model,$attribute,$htmlOptions);
  4977. self::clientChange('change',$htmlOptions);
  4978. return self::activeInputField('email',$model,$attribute,$htmlOptions);
  4979. }
  4980. public static function activeNumberField($model,$attribute,$htmlOptions=array())
  4981. {
  4982. self::resolveNameID($model,$attribute,$htmlOptions);
  4983. self::clientChange('change',$htmlOptions);
  4984. return self::activeInputField('number',$model,$attribute,$htmlOptions);
  4985. }
  4986. public static function activeRangeField($model,$attribute,$htmlOptions=array())
  4987. {
  4988. self::resolveNameID($model,$attribute,$htmlOptions);
  4989. self::clientChange('change',$htmlOptions);
  4990. return self::activeInputField('range',$model,$attribute,$htmlOptions);
  4991. }
  4992. public static function activeDateField($model,$attribute,$htmlOptions=array())
  4993. {
  4994. self::resolveNameID($model,$attribute,$htmlOptions);
  4995. self::clientChange('change',$htmlOptions);
  4996. return self::activeInputField('date',$model,$attribute,$htmlOptions);
  4997. }
  4998. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  4999. {
  5000. self::resolveNameID($model,$attribute,$htmlOptions);
  5001. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  5002. }
  5003. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  5004. {
  5005. self::resolveNameID($model,$attribute,$htmlOptions);
  5006. self::clientChange('change',$htmlOptions);
  5007. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  5008. }
  5009. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  5010. {
  5011. self::resolveNameID($model,$attribute,$htmlOptions);
  5012. self::clientChange('change',$htmlOptions);
  5013. if($model->hasErrors($attribute))
  5014. self::addErrorCss($htmlOptions);
  5015. $text=self::resolveValue($model,$attribute);
  5016. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  5017. }
  5018. public static function activeFileField($model,$attribute,$htmlOptions=array())
  5019. {
  5020. self::resolveNameID($model,$attribute,$htmlOptions);
  5021. // add a hidden field so that if a model only has a file field, we can
  5022. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  5023. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5024. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  5025. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  5026. }
  5027. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  5028. {
  5029. self::resolveNameID($model,$attribute,$htmlOptions);
  5030. if(!isset($htmlOptions['value']))
  5031. $htmlOptions['value']=1;
  5032. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5033. $htmlOptions['checked']='checked';
  5034. self::clientChange('click',$htmlOptions);
  5035. if(array_key_exists('uncheckValue',$htmlOptions))
  5036. {
  5037. $uncheck=$htmlOptions['uncheckValue'];
  5038. unset($htmlOptions['uncheckValue']);
  5039. }
  5040. else
  5041. $uncheck='0';
  5042. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5043. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5044. // add a hidden field so that if the radio button is not selected, it still submits a value
  5045. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  5046. }
  5047. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  5048. {
  5049. self::resolveNameID($model,$attribute,$htmlOptions);
  5050. if(!isset($htmlOptions['value']))
  5051. $htmlOptions['value']=1;
  5052. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5053. $htmlOptions['checked']='checked';
  5054. self::clientChange('click',$htmlOptions);
  5055. if(array_key_exists('uncheckValue',$htmlOptions))
  5056. {
  5057. $uncheck=$htmlOptions['uncheckValue'];
  5058. unset($htmlOptions['uncheckValue']);
  5059. }
  5060. else
  5061. $uncheck='0';
  5062. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5063. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5064. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  5065. }
  5066. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  5067. {
  5068. self::resolveNameID($model,$attribute,$htmlOptions);
  5069. $selection=self::resolveValue($model,$attribute);
  5070. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  5071. self::clientChange('change',$htmlOptions);
  5072. if($model->hasErrors($attribute))
  5073. self::addErrorCss($htmlOptions);
  5074. if(isset($htmlOptions['multiple']))
  5075. {
  5076. if(substr($htmlOptions['name'],-2)!=='[]')
  5077. $htmlOptions['name'].='[]';
  5078. }
  5079. return self::tag('select',$htmlOptions,$options);
  5080. }
  5081. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  5082. {
  5083. if(!isset($htmlOptions['size']))
  5084. $htmlOptions['size']=4;
  5085. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  5086. }
  5087. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  5088. {
  5089. self::resolveNameID($model,$attribute,$htmlOptions);
  5090. $selection=self::resolveValue($model,$attribute);
  5091. if($model->hasErrors($attribute))
  5092. self::addErrorCss($htmlOptions);
  5093. $name=$htmlOptions['name'];
  5094. unset($htmlOptions['name']);
  5095. if(array_key_exists('uncheckValue',$htmlOptions))
  5096. {
  5097. $uncheck=$htmlOptions['uncheckValue'];
  5098. unset($htmlOptions['uncheckValue']);
  5099. }
  5100. else
  5101. $uncheck='';
  5102. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5103. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5104. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  5105. }
  5106. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  5107. {
  5108. self::resolveNameID($model,$attribute,$htmlOptions);
  5109. $selection=self::resolveValue($model,$attribute);
  5110. if($model->hasErrors($attribute))
  5111. self::addErrorCss($htmlOptions);
  5112. $name=$htmlOptions['name'];
  5113. unset($htmlOptions['name']);
  5114. if(array_key_exists('uncheckValue',$htmlOptions))
  5115. {
  5116. $uncheck=$htmlOptions['uncheckValue'];
  5117. unset($htmlOptions['uncheckValue']);
  5118. }
  5119. else
  5120. $uncheck='';
  5121. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5122. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5123. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  5124. }
  5125. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  5126. {
  5127. $content='';
  5128. if(!is_array($model))
  5129. $model=array($model);
  5130. if(isset($htmlOptions['firstError']))
  5131. {
  5132. $firstError=$htmlOptions['firstError'];
  5133. unset($htmlOptions['firstError']);
  5134. }
  5135. else
  5136. $firstError=false;
  5137. foreach($model as $m)
  5138. {
  5139. foreach($m->getErrors() as $errors)
  5140. {
  5141. foreach($errors as $error)
  5142. {
  5143. if($error!='')
  5144. $content.="<li>$error</li>\n";
  5145. if($firstError)
  5146. break;
  5147. }
  5148. }
  5149. }
  5150. if($content!=='')
  5151. {
  5152. if($header===null)
  5153. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5154. if(!isset($htmlOptions['class']))
  5155. $htmlOptions['class']=self::$errorSummaryCss;
  5156. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5157. }
  5158. else
  5159. return '';
  5160. }
  5161. public static function error($model,$attribute,$htmlOptions=array())
  5162. {
  5163. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5164. $error=$model->getError($attribute);
  5165. if($error!='')
  5166. {
  5167. if(!isset($htmlOptions['class']))
  5168. $htmlOptions['class']=self::$errorMessageCss;
  5169. return self::tag('div',$htmlOptions,$error);
  5170. }
  5171. else
  5172. return '';
  5173. }
  5174. public static function listData($models,$valueField,$textField,$groupField='')
  5175. {
  5176. $listData=array();
  5177. if($groupField==='')
  5178. {
  5179. foreach($models as $model)
  5180. {
  5181. $value=self::value($model,$valueField);
  5182. $text=self::value($model,$textField);
  5183. $listData[$value]=$text;
  5184. }
  5185. }
  5186. else
  5187. {
  5188. foreach($models as $model)
  5189. {
  5190. $group=self::value($model,$groupField);
  5191. $value=self::value($model,$valueField);
  5192. $text=self::value($model,$textField);
  5193. $listData[$group][$value]=$text;
  5194. }
  5195. }
  5196. return $listData;
  5197. }
  5198. public static function value($model,$attribute,$defaultValue=null)
  5199. {
  5200. foreach(explode('.',$attribute) as $name)
  5201. {
  5202. if(is_object($model))
  5203. $model=$model->$name;
  5204. else if(is_array($model) && isset($model[$name]))
  5205. $model=$model[$name];
  5206. else
  5207. return $defaultValue;
  5208. }
  5209. return $model;
  5210. }
  5211. public static function getIdByName($name)
  5212. {
  5213. return str_replace(array('[]', '][', '[', ']', ' '), array('', '_', '_', '', '_'), $name);
  5214. }
  5215. public static function activeId($model,$attribute)
  5216. {
  5217. return self::getIdByName(self::activeName($model,$attribute));
  5218. }
  5219. public static function activeName($model,$attribute)
  5220. {
  5221. $a=$attribute; // because the attribute name may be changed by resolveName
  5222. return self::resolveName($model,$a);
  5223. }
  5224. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5225. {
  5226. $htmlOptions['type']=$type;
  5227. if($type==='text' || $type==='password')
  5228. {
  5229. if(!isset($htmlOptions['maxlength']))
  5230. {
  5231. foreach($model->getValidators($attribute) as $validator)
  5232. {
  5233. if($validator instanceof CStringValidator && $validator->max!==null)
  5234. {
  5235. $htmlOptions['maxlength']=$validator->max;
  5236. break;
  5237. }
  5238. }
  5239. }
  5240. else if($htmlOptions['maxlength']===false)
  5241. unset($htmlOptions['maxlength']);
  5242. }
  5243. if($type==='file')
  5244. unset($htmlOptions['value']);
  5245. else if(!isset($htmlOptions['value']))
  5246. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5247. if($model->hasErrors($attribute))
  5248. self::addErrorCss($htmlOptions);
  5249. return self::tag('input',$htmlOptions);
  5250. }
  5251. public static function listOptions($selection,$listData,&$htmlOptions)
  5252. {
  5253. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5254. $content='';
  5255. if(isset($htmlOptions['prompt']))
  5256. {
  5257. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5258. unset($htmlOptions['prompt']);
  5259. }
  5260. if(isset($htmlOptions['empty']))
  5261. {
  5262. if(!is_array($htmlOptions['empty']))
  5263. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5264. foreach($htmlOptions['empty'] as $value=>$label)
  5265. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5266. unset($htmlOptions['empty']);
  5267. }
  5268. if(isset($htmlOptions['options']))
  5269. {
  5270. $options=$htmlOptions['options'];
  5271. unset($htmlOptions['options']);
  5272. }
  5273. else
  5274. $options=array();
  5275. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  5276. if(is_array($selection))
  5277. {
  5278. foreach($selection as $i=>$item)
  5279. {
  5280. if(is_object($item))
  5281. $selection[$i]=$item->$key;
  5282. }
  5283. }
  5284. else if(is_object($selection))
  5285. $selection=$selection->$key;
  5286. foreach($listData as $key=>$value)
  5287. {
  5288. if(is_array($value))
  5289. {
  5290. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  5291. $dummy=array('options'=>$options);
  5292. if(isset($htmlOptions['encode']))
  5293. $dummy['encode']=$htmlOptions['encode'];
  5294. $content.=self::listOptions($selection,$value,$dummy);
  5295. $content.='</optgroup>'."\n";
  5296. }
  5297. else
  5298. {
  5299. $attributes=array('value'=>(string)$key, 'encode'=>!$raw);
  5300. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  5301. $attributes['selected']='selected';
  5302. if(isset($options[$key]))
  5303. $attributes=array_merge($attributes,$options[$key]);
  5304. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  5305. }
  5306. }
  5307. unset($htmlOptions['key']);
  5308. return $content;
  5309. }
  5310. protected static function clientChange($event,&$htmlOptions)
  5311. {
  5312. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  5313. return;
  5314. if(isset($htmlOptions['live']))
  5315. {
  5316. $live=$htmlOptions['live'];
  5317. unset($htmlOptions['live']);
  5318. }
  5319. else
  5320. $live = self::$liveEvents;
  5321. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  5322. $return='return true';
  5323. else
  5324. $return='return false';
  5325. if(isset($htmlOptions['on'.$event]))
  5326. {
  5327. $handler=trim($htmlOptions['on'.$event],';').';';
  5328. unset($htmlOptions['on'.$event]);
  5329. }
  5330. else
  5331. $handler='';
  5332. if(isset($htmlOptions['id']))
  5333. $id=$htmlOptions['id'];
  5334. else
  5335. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  5336. $cs=Yii::app()->getClientScript();
  5337. $cs->registerCoreScript('jquery');
  5338. if(isset($htmlOptions['submit']))
  5339. {
  5340. $cs->registerCoreScript('yii');
  5341. $request=Yii::app()->getRequest();
  5342. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  5343. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  5344. if(isset($htmlOptions['params']))
  5345. $params=CJavaScript::encode($htmlOptions['params']);
  5346. else
  5347. $params='{}';
  5348. if($htmlOptions['submit']!=='')
  5349. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  5350. else
  5351. $url='';
  5352. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  5353. }
  5354. if(isset($htmlOptions['ajax']))
  5355. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  5356. if(isset($htmlOptions['confirm']))
  5357. {
  5358. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  5359. if($handler!=='')
  5360. $handler="if($confirm) {".$handler."} else return false;";
  5361. else
  5362. $handler="return $confirm;";
  5363. }
  5364. if($live)
  5365. $cs->registerScript('Yii.CHtml.#' . $id, "$('body').on('$event','#$id',function(){{$handler}});");
  5366. else
  5367. $cs->registerScript('Yii.CHtml.#' . $id, "$('#$id').on('$event', function(){{$handler}});");
  5368. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  5369. }
  5370. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  5371. {
  5372. if(!isset($htmlOptions['name']))
  5373. $htmlOptions['name']=self::resolveName($model,$attribute);
  5374. if(!isset($htmlOptions['id']))
  5375. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  5376. else if($htmlOptions['id']===false)
  5377. unset($htmlOptions['id']);
  5378. }
  5379. public static function resolveName($model,&$attribute)
  5380. {
  5381. if(($pos=strpos($attribute,'['))!==false)
  5382. {
  5383. if($pos!==0) // e.g. name[a][b]
  5384. return get_class($model).'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5385. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5386. {
  5387. $sub=substr($attribute,0,$pos+1);
  5388. $attribute=substr($attribute,$pos+1);
  5389. return get_class($model).$sub.'['.$attribute.']';
  5390. }
  5391. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5392. {
  5393. $name=get_class($model).'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5394. $attribute=$matches[1];
  5395. return $name;
  5396. }
  5397. }
  5398. return get_class($model).'['.$attribute.']';
  5399. }
  5400. public static function resolveValue($model,$attribute)
  5401. {
  5402. if(($pos=strpos($attribute,'['))!==false)
  5403. {
  5404. if($pos===0) // [a]name[b][c], should ignore [a]
  5405. {
  5406. if(preg_match('/\](\w+(\[.+)?)/',$attribute,$matches))
  5407. $attribute=$matches[1]; // we get: name[b][c]
  5408. if(($pos=strpos($attribute,'['))===false)
  5409. return $model->$attribute;
  5410. }
  5411. $name=substr($attribute,0,$pos);
  5412. $value=$model->$name;
  5413. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5414. {
  5415. if((is_array($value) || $value instanceof ArrayAccess) && isset($value[$id]))
  5416. $value=$value[$id];
  5417. else
  5418. return null;
  5419. }
  5420. return $value;
  5421. }
  5422. else
  5423. return $model->$attribute;
  5424. }
  5425. protected static function addErrorCss(&$htmlOptions)
  5426. {
  5427. if(isset($htmlOptions['class']))
  5428. $htmlOptions['class'].=' '.self::$errorCss;
  5429. else
  5430. $htmlOptions['class']=self::$errorCss;
  5431. }
  5432. public static function renderAttributes($htmlOptions)
  5433. {
  5434. static $specialAttributes=array(
  5435. 'checked'=>1,
  5436. 'declare'=>1,
  5437. 'defer'=>1,
  5438. 'disabled'=>1,
  5439. 'ismap'=>1,
  5440. 'multiple'=>1,
  5441. 'nohref'=>1,
  5442. 'noresize'=>1,
  5443. 'readonly'=>1,
  5444. 'selected'=>1,
  5445. );
  5446. if($htmlOptions===array())
  5447. return '';
  5448. $html='';
  5449. if(isset($htmlOptions['encode']))
  5450. {
  5451. $raw=!$htmlOptions['encode'];
  5452. unset($htmlOptions['encode']);
  5453. }
  5454. else
  5455. $raw=false;
  5456. foreach($htmlOptions as $name=>$value)
  5457. {
  5458. if(isset($specialAttributes[$name]))
  5459. {
  5460. if($value)
  5461. $html .= ' ' . $name . '="' . $name . '"';
  5462. }
  5463. else if($value!==null)
  5464. $html .= ' ' . $name . '="' . ($raw ? $value : self::encode($value)) . '"';
  5465. }
  5466. return $html;
  5467. }
  5468. }
  5469. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  5470. {
  5471. public $enableSkin=false;
  5472. public $widgets=array();
  5473. public $skinnableWidgets;
  5474. public $skinPath;
  5475. private $_skins=array(); // class name, skin name, property name => value
  5476. public function init()
  5477. {
  5478. parent::init();
  5479. if($this->enableSkin && $this->skinPath===null)
  5480. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  5481. }
  5482. public function createWidget($owner,$className,$properties=array())
  5483. {
  5484. $className=Yii::import($className,true);
  5485. $widget=new $className($owner);
  5486. if(isset($this->widgets[$className]))
  5487. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  5488. if($this->enableSkin)
  5489. {
  5490. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  5491. {
  5492. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  5493. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  5494. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  5495. }
  5496. }
  5497. foreach($properties as $name=>$value)
  5498. $widget->$name=$value;
  5499. return $widget;
  5500. }
  5501. protected function getSkin($className,$skinName)
  5502. {
  5503. if(!isset($this->_skins[$className][$skinName]))
  5504. {
  5505. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  5506. if(is_file($skinFile))
  5507. $this->_skins[$className]=require($skinFile);
  5508. else
  5509. $this->_skins[$className]=array();
  5510. if(($theme=Yii::app()->getTheme())!==null)
  5511. {
  5512. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  5513. if(is_file($skinFile))
  5514. {
  5515. $skins=require($skinFile);
  5516. foreach($skins as $name=>$skin)
  5517. $this->_skins[$className][$name]=$skin;
  5518. }
  5519. }
  5520. if(!isset($this->_skins[$className][$skinName]))
  5521. $this->_skins[$className][$skinName]=array();
  5522. }
  5523. return $this->_skins[$className][$skinName];
  5524. }
  5525. }
  5526. class CWidget extends CBaseController
  5527. {
  5528. public $actionPrefix;
  5529. public $skin='default';
  5530. private static $_viewPaths;
  5531. private static $_counter=0;
  5532. private $_id;
  5533. private $_owner;
  5534. public static function actions()
  5535. {
  5536. return array();
  5537. }
  5538. public function __construct($owner=null)
  5539. {
  5540. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  5541. }
  5542. public function getOwner()
  5543. {
  5544. return $this->_owner;
  5545. }
  5546. public function getId($autoGenerate=true)
  5547. {
  5548. if($this->_id!==null)
  5549. return $this->_id;
  5550. else if($autoGenerate)
  5551. return $this->_id='yw'.self::$_counter++;
  5552. }
  5553. public function setId($value)
  5554. {
  5555. $this->_id=$value;
  5556. }
  5557. public function getController()
  5558. {
  5559. if($this->_owner instanceof CController)
  5560. return $this->_owner;
  5561. else
  5562. return Yii::app()->getController();
  5563. }
  5564. public function init()
  5565. {
  5566. }
  5567. public function run()
  5568. {
  5569. }
  5570. public function getViewPath($checkTheme=false)
  5571. {
  5572. $className=get_class($this);
  5573. if(isset(self::$_viewPaths[$className]))
  5574. return self::$_viewPaths[$className];
  5575. else
  5576. {
  5577. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  5578. {
  5579. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  5580. if(strpos($className,'\\')!==false) // namespaced class
  5581. $path.=str_replace('\\','_',ltrim($className,'\\'));
  5582. else
  5583. $path.=$className;
  5584. if(is_dir($path))
  5585. return self::$_viewPaths[$className]=$path;
  5586. }
  5587. $class=new ReflectionClass($className);
  5588. return self::$_viewPaths[$className]=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  5589. }
  5590. }
  5591. public function getViewFile($viewName)
  5592. {
  5593. if(($renderer=Yii::app()->getViewRenderer())!==null)
  5594. $extension=$renderer->fileExtension;
  5595. else
  5596. $extension='.php';
  5597. if(strpos($viewName,'.')) // a path alias
  5598. $viewFile=Yii::getPathOfAlias($viewName);
  5599. else
  5600. {
  5601. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  5602. if(is_file($viewFile.$extension))
  5603. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5604. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5605. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5606. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  5607. }
  5608. if(is_file($viewFile.$extension))
  5609. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5610. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5611. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5612. else
  5613. return false;
  5614. }
  5615. public function render($view,$data=null,$return=false)
  5616. {
  5617. if(($viewFile=$this->getViewFile($view))!==false)
  5618. return $this->renderFile($viewFile,$data,$return);
  5619. else
  5620. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  5621. array('{widget}'=>get_class($this), '{view}'=>$view)));
  5622. }
  5623. }
  5624. class CClientScript extends CApplicationComponent
  5625. {
  5626. const POS_HEAD=0;
  5627. const POS_BEGIN=1;
  5628. const POS_END=2;
  5629. const POS_LOAD=3;
  5630. const POS_READY=4;
  5631. public $enableJavaScript=true;
  5632. public $scriptMap=array();
  5633. public $packages=array();
  5634. public $corePackages;
  5635. public $scripts=array();
  5636. protected $cssFiles=array();
  5637. protected $scriptFiles=array();
  5638. protected $metaTags=array();
  5639. protected $linkTags=array();
  5640. protected $css=array();
  5641. protected $hasScripts=false;
  5642. protected $coreScripts=array();
  5643. public $coreScriptPosition=self::POS_HEAD;
  5644. public $defaultScriptFilePosition=self::POS_HEAD;
  5645. public $defaultScriptPosition=self::POS_READY;
  5646. private $_baseUrl;
  5647. public function reset()
  5648. {
  5649. $this->hasScripts=false;
  5650. $this->coreScripts=array();
  5651. $this->cssFiles=array();
  5652. $this->css=array();
  5653. $this->scriptFiles=array();
  5654. $this->scripts=array();
  5655. $this->metaTags=array();
  5656. $this->linkTags=array();
  5657. $this->recordCachingAction('clientScript','reset',array());
  5658. }
  5659. public function render(&$output)
  5660. {
  5661. if(!$this->hasScripts)
  5662. return;
  5663. $this->renderCoreScripts();
  5664. if(!empty($this->scriptMap))
  5665. $this->remapScripts();
  5666. $this->unifyScripts();
  5667. $this->renderHead($output);
  5668. if($this->enableJavaScript)
  5669. {
  5670. $this->renderBodyBegin($output);
  5671. $this->renderBodyEnd($output);
  5672. }
  5673. }
  5674. protected function unifyScripts()
  5675. {
  5676. if(!$this->enableJavaScript)
  5677. return;
  5678. $map=array();
  5679. if(isset($this->scriptFiles[self::POS_HEAD]))
  5680. $map=$this->scriptFiles[self::POS_HEAD];
  5681. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5682. {
  5683. foreach($this->scriptFiles[self::POS_BEGIN] as $key=>$scriptFile)
  5684. {
  5685. if(isset($map[$scriptFile]))
  5686. unset($this->scriptFiles[self::POS_BEGIN][$key]);
  5687. else
  5688. $map[$scriptFile]=true;
  5689. }
  5690. }
  5691. if(isset($this->scriptFiles[self::POS_END]))
  5692. {
  5693. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  5694. {
  5695. if(isset($map[$scriptFile]))
  5696. unset($this->scriptFiles[self::POS_END][$key]);
  5697. }
  5698. }
  5699. }
  5700. protected function remapScripts()
  5701. {
  5702. $cssFiles=array();
  5703. foreach($this->cssFiles as $url=>$media)
  5704. {
  5705. $name=basename($url);
  5706. if(isset($this->scriptMap[$name]))
  5707. {
  5708. if($this->scriptMap[$name]!==false)
  5709. $cssFiles[$this->scriptMap[$name]]=$media;
  5710. }
  5711. else if(isset($this->scriptMap['*.css']))
  5712. {
  5713. if($this->scriptMap['*.css']!==false)
  5714. $cssFiles[$this->scriptMap['*.css']]=$media;
  5715. }
  5716. else
  5717. $cssFiles[$url]=$media;
  5718. }
  5719. $this->cssFiles=$cssFiles;
  5720. $jsFiles=array();
  5721. foreach($this->scriptFiles as $position=>$scripts)
  5722. {
  5723. $jsFiles[$position]=array();
  5724. foreach($scripts as $key=>$script)
  5725. {
  5726. $name=basename($script);
  5727. if(isset($this->scriptMap[$name]))
  5728. {
  5729. if($this->scriptMap[$name]!==false)
  5730. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  5731. }
  5732. else if(isset($this->scriptMap['*.js']))
  5733. {
  5734. if($this->scriptMap['*.js']!==false)
  5735. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  5736. }
  5737. else
  5738. $jsFiles[$position][$key]=$script;
  5739. }
  5740. }
  5741. $this->scriptFiles=$jsFiles;
  5742. }
  5743. public function renderCoreScripts()
  5744. {
  5745. if($this->coreScripts===null)
  5746. return;
  5747. $cssFiles=array();
  5748. $jsFiles=array();
  5749. foreach($this->coreScripts as $name=>$package)
  5750. {
  5751. $baseUrl=$this->getPackageBaseUrl($name);
  5752. if(!empty($package['js']))
  5753. {
  5754. foreach($package['js'] as $js)
  5755. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  5756. }
  5757. if(!empty($package['css']))
  5758. {
  5759. foreach($package['css'] as $css)
  5760. $cssFiles[$baseUrl.'/'.$css]='';
  5761. }
  5762. }
  5763. // merge in place
  5764. if($cssFiles!==array())
  5765. {
  5766. foreach($this->cssFiles as $cssFile=>$media)
  5767. $cssFiles[$cssFile]=$media;
  5768. $this->cssFiles=$cssFiles;
  5769. }
  5770. if($jsFiles!==array())
  5771. {
  5772. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  5773. {
  5774. foreach($this->scriptFiles[$this->coreScriptPosition] as $url)
  5775. $jsFiles[$url]=$url;
  5776. }
  5777. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  5778. }
  5779. }
  5780. public function renderHead(&$output)
  5781. {
  5782. $html='';
  5783. foreach($this->metaTags as $meta)
  5784. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  5785. foreach($this->linkTags as $link)
  5786. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  5787. foreach($this->cssFiles as $url=>$media)
  5788. $html.=CHtml::cssFile($url,$media)."\n";
  5789. foreach($this->css as $css)
  5790. $html.=CHtml::css($css[0],$css[1])."\n";
  5791. if($this->enableJavaScript)
  5792. {
  5793. if(isset($this->scriptFiles[self::POS_HEAD]))
  5794. {
  5795. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFile)
  5796. $html.=CHtml::scriptFile($scriptFile)."\n";
  5797. }
  5798. if(isset($this->scripts[self::POS_HEAD]))
  5799. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_HEAD]))."\n";
  5800. }
  5801. if($html!=='')
  5802. {
  5803. $count=0;
  5804. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  5805. if($count)
  5806. $output=str_replace('<###head###>',$html,$output);
  5807. else
  5808. $output=$html.$output;
  5809. }
  5810. }
  5811. public function renderBodyBegin(&$output)
  5812. {
  5813. $html='';
  5814. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5815. {
  5816. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile)
  5817. $html.=CHtml::scriptFile($scriptFile)."\n";
  5818. }
  5819. if(isset($this->scripts[self::POS_BEGIN]))
  5820. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_BEGIN]))."\n";
  5821. if($html!=='')
  5822. {
  5823. $count=0;
  5824. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  5825. if($count)
  5826. $output=str_replace('<###begin###>',$html,$output);
  5827. else
  5828. $output=$html.$output;
  5829. }
  5830. }
  5831. public function renderBodyEnd(&$output)
  5832. {
  5833. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  5834. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  5835. return;
  5836. $fullPage=0;
  5837. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  5838. $html='';
  5839. if(isset($this->scriptFiles[self::POS_END]))
  5840. {
  5841. foreach($this->scriptFiles[self::POS_END] as $scriptFile)
  5842. $html.=CHtml::scriptFile($scriptFile)."\n";
  5843. }
  5844. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  5845. if(isset($this->scripts[self::POS_READY]))
  5846. {
  5847. if($fullPage)
  5848. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  5849. else
  5850. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  5851. }
  5852. if(isset($this->scripts[self::POS_LOAD]))
  5853. {
  5854. if($fullPage)
  5855. $scripts[]="jQuery(window).load(function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  5856. else
  5857. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  5858. }
  5859. if(!empty($scripts))
  5860. $html.=CHtml::script(implode("\n",$scripts))."\n";
  5861. if($fullPage)
  5862. $output=str_replace('<###end###>',$html,$output);
  5863. else
  5864. $output=$output.$html;
  5865. }
  5866. public function getCoreScriptUrl()
  5867. {
  5868. if($this->_baseUrl!==null)
  5869. return $this->_baseUrl;
  5870. else
  5871. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  5872. }
  5873. public function setCoreScriptUrl($value)
  5874. {
  5875. $this->_baseUrl=$value;
  5876. }
  5877. public function getPackageBaseUrl($name)
  5878. {
  5879. if(!isset($this->coreScripts[$name]))
  5880. return false;
  5881. $package=$this->coreScripts[$name];
  5882. if(isset($package['baseUrl']))
  5883. {
  5884. $baseUrl=$package['baseUrl'];
  5885. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  5886. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  5887. $baseUrl=rtrim($baseUrl,'/');
  5888. }
  5889. else if(isset($package['basePath']))
  5890. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  5891. else
  5892. $baseUrl=$this->getCoreScriptUrl();
  5893. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  5894. }
  5895. public function registerPackage($name)
  5896. {
  5897. return $this->registerCoreScript($name);
  5898. }
  5899. public function registerCoreScript($name)
  5900. {
  5901. if(isset($this->coreScripts[$name]))
  5902. return $this;
  5903. if(isset($this->packages[$name]))
  5904. $package=$this->packages[$name];
  5905. else
  5906. {
  5907. if($this->corePackages===null)
  5908. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  5909. if(isset($this->corePackages[$name]))
  5910. $package=$this->corePackages[$name];
  5911. }
  5912. if(isset($package))
  5913. {
  5914. if(!empty($package['depends']))
  5915. {
  5916. foreach($package['depends'] as $p)
  5917. $this->registerCoreScript($p);
  5918. }
  5919. $this->coreScripts[$name]=$package;
  5920. $this->hasScripts=true;
  5921. $params=func_get_args();
  5922. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  5923. }
  5924. return $this;
  5925. }
  5926. public function registerCssFile($url,$media='')
  5927. {
  5928. $this->hasScripts=true;
  5929. $this->cssFiles[$url]=$media;
  5930. $params=func_get_args();
  5931. $this->recordCachingAction('clientScript','registerCssFile',$params);
  5932. return $this;
  5933. }
  5934. public function registerCss($id,$css,$media='')
  5935. {
  5936. $this->hasScripts=true;
  5937. $this->css[$id]=array($css,$media);
  5938. $params=func_get_args();
  5939. $this->recordCachingAction('clientScript','registerCss',$params);
  5940. return $this;
  5941. }
  5942. public function registerScriptFile($url,$position=null)
  5943. {
  5944. if($position===null)
  5945. $position=$this->defaultScriptFilePosition;
  5946. $this->hasScripts=true;
  5947. $this->scriptFiles[$position][$url]=$url;
  5948. $params=func_get_args();
  5949. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  5950. return $this;
  5951. }
  5952. public function registerScript($id,$script,$position=null)
  5953. {
  5954. if($position===null)
  5955. $position=$this->defaultScriptPosition;
  5956. $this->hasScripts=true;
  5957. $this->scripts[$position][$id]=$script;
  5958. if($position===self::POS_READY || $position===self::POS_LOAD)
  5959. $this->registerCoreScript('jquery');
  5960. $params=func_get_args();
  5961. $this->recordCachingAction('clientScript','registerScript',$params);
  5962. return $this;
  5963. }
  5964. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array())
  5965. {
  5966. $this->hasScripts=true;
  5967. if($name!==null)
  5968. $options['name']=$name;
  5969. if($httpEquiv!==null)
  5970. $options['http-equiv']=$httpEquiv;
  5971. $options['content']=$content;
  5972. $this->metaTags[serialize($options)]=$options;
  5973. $params=func_get_args();
  5974. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  5975. return $this;
  5976. }
  5977. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  5978. {
  5979. $this->hasScripts=true;
  5980. if($relation!==null)
  5981. $options['rel']=$relation;
  5982. if($type!==null)
  5983. $options['type']=$type;
  5984. if($href!==null)
  5985. $options['href']=$href;
  5986. if($media!==null)
  5987. $options['media']=$media;
  5988. $this->linkTags[serialize($options)]=$options;
  5989. $params=func_get_args();
  5990. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  5991. return $this;
  5992. }
  5993. public function isCssFileRegistered($url)
  5994. {
  5995. return isset($this->cssFiles[$url]);
  5996. }
  5997. public function isCssRegistered($id)
  5998. {
  5999. return isset($this->css[$id]);
  6000. }
  6001. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  6002. {
  6003. return isset($this->scriptFiles[$position][$url]);
  6004. }
  6005. public function isScriptRegistered($id,$position=self::POS_READY)
  6006. {
  6007. return isset($this->scripts[$position][$id]);
  6008. }
  6009. protected function recordCachingAction($context,$method,$params)
  6010. {
  6011. if(($controller=Yii::app()->getController())!==null)
  6012. $controller->recordCachingAction($context,$method,$params);
  6013. }
  6014. public function addPackage($name,$definition)
  6015. {
  6016. $this->packages[$name]=$definition;
  6017. return $this;
  6018. }
  6019. }
  6020. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  6021. {
  6022. private $_d=array();
  6023. private $_c=0;
  6024. private $_r=false;
  6025. public function __construct($data=null,$readOnly=false)
  6026. {
  6027. if($data!==null)
  6028. $this->copyFrom($data);
  6029. $this->setReadOnly($readOnly);
  6030. }
  6031. public function getReadOnly()
  6032. {
  6033. return $this->_r;
  6034. }
  6035. protected function setReadOnly($value)
  6036. {
  6037. $this->_r=$value;
  6038. }
  6039. public function getIterator()
  6040. {
  6041. return new CListIterator($this->_d);
  6042. }
  6043. public function count()
  6044. {
  6045. return $this->getCount();
  6046. }
  6047. public function getCount()
  6048. {
  6049. return $this->_c;
  6050. }
  6051. public function itemAt($index)
  6052. {
  6053. if(isset($this->_d[$index]))
  6054. return $this->_d[$index];
  6055. else if($index>=0 && $index<$this->_c) // in case the value is null
  6056. return $this->_d[$index];
  6057. else
  6058. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6059. array('{index}'=>$index)));
  6060. }
  6061. public function add($item)
  6062. {
  6063. $this->insertAt($this->_c,$item);
  6064. return $this->_c-1;
  6065. }
  6066. public function insertAt($index,$item)
  6067. {
  6068. if(!$this->_r)
  6069. {
  6070. if($index===$this->_c)
  6071. $this->_d[$this->_c++]=$item;
  6072. else if($index>=0 && $index<$this->_c)
  6073. {
  6074. array_splice($this->_d,$index,0,array($item));
  6075. $this->_c++;
  6076. }
  6077. else
  6078. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6079. array('{index}'=>$index)));
  6080. }
  6081. else
  6082. throw new CException(Yii::t('yii','The list is read only.'));
  6083. }
  6084. public function remove($item)
  6085. {
  6086. if(($index=$this->indexOf($item))>=0)
  6087. {
  6088. $this->removeAt($index);
  6089. return $index;
  6090. }
  6091. else
  6092. return false;
  6093. }
  6094. public function removeAt($index)
  6095. {
  6096. if(!$this->_r)
  6097. {
  6098. if($index>=0 && $index<$this->_c)
  6099. {
  6100. $this->_c--;
  6101. if($index===$this->_c)
  6102. return array_pop($this->_d);
  6103. else
  6104. {
  6105. $item=$this->_d[$index];
  6106. array_splice($this->_d,$index,1);
  6107. return $item;
  6108. }
  6109. }
  6110. else
  6111. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6112. array('{index}'=>$index)));
  6113. }
  6114. else
  6115. throw new CException(Yii::t('yii','The list is read only.'));
  6116. }
  6117. public function clear()
  6118. {
  6119. for($i=$this->_c-1;$i>=0;--$i)
  6120. $this->removeAt($i);
  6121. }
  6122. public function contains($item)
  6123. {
  6124. return $this->indexOf($item)>=0;
  6125. }
  6126. public function indexOf($item)
  6127. {
  6128. if(($index=array_search($item,$this->_d,true))!==false)
  6129. return $index;
  6130. else
  6131. return -1;
  6132. }
  6133. public function toArray()
  6134. {
  6135. return $this->_d;
  6136. }
  6137. public function copyFrom($data)
  6138. {
  6139. if(is_array($data) || ($data instanceof Traversable))
  6140. {
  6141. if($this->_c>0)
  6142. $this->clear();
  6143. if($data instanceof CList)
  6144. $data=$data->_d;
  6145. foreach($data as $item)
  6146. $this->add($item);
  6147. }
  6148. else if($data!==null)
  6149. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6150. }
  6151. public function mergeWith($data)
  6152. {
  6153. if(is_array($data) || ($data instanceof Traversable))
  6154. {
  6155. if($data instanceof CList)
  6156. $data=$data->_d;
  6157. foreach($data as $item)
  6158. $this->add($item);
  6159. }
  6160. else if($data!==null)
  6161. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6162. }
  6163. public function offsetExists($offset)
  6164. {
  6165. return ($offset>=0 && $offset<$this->_c);
  6166. }
  6167. public function offsetGet($offset)
  6168. {
  6169. return $this->itemAt($offset);
  6170. }
  6171. public function offsetSet($offset,$item)
  6172. {
  6173. if($offset===null || $offset===$this->_c)
  6174. $this->insertAt($this->_c,$item);
  6175. else
  6176. {
  6177. $this->removeAt($offset);
  6178. $this->insertAt($offset,$item);
  6179. }
  6180. }
  6181. public function offsetUnset($offset)
  6182. {
  6183. $this->removeAt($offset);
  6184. }
  6185. }
  6186. class CFilterChain extends CList
  6187. {
  6188. public $controller;
  6189. public $action;
  6190. public $filterIndex=0;
  6191. public function __construct($controller,$action)
  6192. {
  6193. $this->controller=$controller;
  6194. $this->action=$action;
  6195. }
  6196. public static function create($controller,$action,$filters)
  6197. {
  6198. $chain=new CFilterChain($controller,$action);
  6199. $actionID=$action->getId();
  6200. foreach($filters as $filter)
  6201. {
  6202. if(is_string($filter)) // filterName [+|- action1 action2]
  6203. {
  6204. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  6205. {
  6206. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  6207. if(($filter[$pos]==='+')===$matched)
  6208. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  6209. }
  6210. else
  6211. $filter=CInlineFilter::create($controller,$filter);
  6212. }
  6213. else if(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  6214. {
  6215. if(!isset($filter[0]))
  6216. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  6217. $filterClass=$filter[0];
  6218. unset($filter[0]);
  6219. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  6220. {
  6221. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  6222. if(($filterClass[$pos]==='+')===$matched)
  6223. $filterClass=trim(substr($filterClass,0,$pos));
  6224. else
  6225. continue;
  6226. }
  6227. $filter['class']=$filterClass;
  6228. $filter=Yii::createComponent($filter);
  6229. }
  6230. if(is_object($filter))
  6231. {
  6232. $filter->init();
  6233. $chain->add($filter);
  6234. }
  6235. }
  6236. return $chain;
  6237. }
  6238. public function insertAt($index,$item)
  6239. {
  6240. if($item instanceof IFilter)
  6241. parent::insertAt($index,$item);
  6242. else
  6243. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  6244. }
  6245. public function run()
  6246. {
  6247. if($this->offsetExists($this->filterIndex))
  6248. {
  6249. $filter=$this->itemAt($this->filterIndex++);
  6250. $filter->filter($this);
  6251. }
  6252. else
  6253. $this->controller->runAction($this->action);
  6254. }
  6255. }
  6256. class CFilter extends CComponent implements IFilter
  6257. {
  6258. public function filter($filterChain)
  6259. {
  6260. if($this->preFilter($filterChain))
  6261. {
  6262. $filterChain->run();
  6263. $this->postFilter($filterChain);
  6264. }
  6265. }
  6266. public function init()
  6267. {
  6268. }
  6269. protected function preFilter($filterChain)
  6270. {
  6271. return true;
  6272. }
  6273. protected function postFilter($filterChain)
  6274. {
  6275. }
  6276. }
  6277. class CInlineFilter extends CFilter
  6278. {
  6279. public $name;
  6280. public static function create($controller,$filterName)
  6281. {
  6282. if(method_exists($controller,'filter'.$filterName))
  6283. {
  6284. $filter=new CInlineFilter;
  6285. $filter->name=$filterName;
  6286. return $filter;
  6287. }
  6288. else
  6289. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  6290. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  6291. }
  6292. public function filter($filterChain)
  6293. {
  6294. $method='filter'.$this->name;
  6295. $filterChain->controller->$method($filterChain);
  6296. }
  6297. }
  6298. class CAccessControlFilter extends CFilter
  6299. {
  6300. public $message;
  6301. private $_rules=array();
  6302. public function getRules()
  6303. {
  6304. return $this->_rules;
  6305. }
  6306. public function setRules($rules)
  6307. {
  6308. foreach($rules as $rule)
  6309. {
  6310. if(is_array($rule) && isset($rule[0]))
  6311. {
  6312. $r=new CAccessRule;
  6313. $r->allow=$rule[0]==='allow';
  6314. foreach(array_slice($rule,1) as $name=>$value)
  6315. {
  6316. if($name==='expression' || $name==='roles' || $name==='message' || $name==='deniedCallback')
  6317. $r->$name=$value;
  6318. else
  6319. $r->$name=array_map('strtolower',$value);
  6320. }
  6321. $this->_rules[]=$r;
  6322. }
  6323. }
  6324. }
  6325. protected function preFilter($filterChain)
  6326. {
  6327. $app=Yii::app();
  6328. $request=$app->getRequest();
  6329. $user=$app->getUser();
  6330. $verb=$request->getRequestType();
  6331. $ip=$request->getUserHostAddress();
  6332. foreach($this->getRules() as $rule)
  6333. {
  6334. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  6335. break;
  6336. else if($allow<0) // denied
  6337. {
  6338. if(isset($rule->deniedCallback))
  6339. call_user_func($rule->deniedCallback, $rule);
  6340. else
  6341. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  6342. return false;
  6343. }
  6344. }
  6345. return true;
  6346. }
  6347. protected function resolveErrorMessage($rule)
  6348. {
  6349. if($rule->message!==null)
  6350. return $rule->message;
  6351. else if($this->message!==null)
  6352. return $this->message;
  6353. else
  6354. return Yii::t('yii','You are not authorized to perform this action.');
  6355. }
  6356. protected function accessDenied($user,$message)
  6357. {
  6358. if($user->getIsGuest())
  6359. $user->loginRequired();
  6360. else
  6361. throw new CHttpException(403,$message);
  6362. }
  6363. }
  6364. class CAccessRule extends CComponent
  6365. {
  6366. public $allow;
  6367. public $actions;
  6368. public $controllers;
  6369. public $users;
  6370. public $roles;
  6371. public $ips;
  6372. public $verbs;
  6373. public $expression;
  6374. public $message;
  6375. public $deniedCallback;
  6376. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  6377. {
  6378. if($this->isActionMatched($action)
  6379. && $this->isUserMatched($user)
  6380. && $this->isRoleMatched($user)
  6381. && $this->isIpMatched($ip)
  6382. && $this->isVerbMatched($verb)
  6383. && $this->isControllerMatched($controller)
  6384. && $this->isExpressionMatched($user))
  6385. return $this->allow ? 1 : -1;
  6386. else
  6387. return 0;
  6388. }
  6389. protected function isActionMatched($action)
  6390. {
  6391. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  6392. }
  6393. protected function isControllerMatched($controller)
  6394. {
  6395. return empty($this->controllers) || in_array(strtolower($controller->getId()),$this->controllers);
  6396. }
  6397. protected function isUserMatched($user)
  6398. {
  6399. if(empty($this->users))
  6400. return true;
  6401. foreach($this->users as $u)
  6402. {
  6403. if($u==='*')
  6404. return true;
  6405. else if($u==='?' && $user->getIsGuest())
  6406. return true;
  6407. else if($u==='@' && !$user->getIsGuest())
  6408. return true;
  6409. else if(!strcasecmp($u,$user->getName()))
  6410. return true;
  6411. }
  6412. return false;
  6413. }
  6414. protected function isRoleMatched($user)
  6415. {
  6416. if(empty($this->roles))
  6417. return true;
  6418. foreach($this->roles as $key=>$role)
  6419. {
  6420. if(is_numeric($key))
  6421. {
  6422. if($user->checkAccess($role))
  6423. return true;
  6424. }
  6425. else
  6426. {
  6427. if($user->checkAccess($key,$role))
  6428. return true;
  6429. }
  6430. }
  6431. return false;
  6432. }
  6433. protected function isIpMatched($ip)
  6434. {
  6435. if(empty($this->ips))
  6436. return true;
  6437. foreach($this->ips as $rule)
  6438. {
  6439. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  6440. return true;
  6441. }
  6442. return false;
  6443. }
  6444. protected function isVerbMatched($verb)
  6445. {
  6446. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  6447. }
  6448. protected function isExpressionMatched($user)
  6449. {
  6450. if($this->expression===null)
  6451. return true;
  6452. else
  6453. return $this->evaluateExpression($this->expression, array('user'=>$user));
  6454. }
  6455. }
  6456. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  6457. {
  6458. private $_errors=array(); // attribute name => array of errors
  6459. private $_validators; // validators
  6460. private $_scenario=''; // scenario
  6461. abstract public function attributeNames();
  6462. public function rules()
  6463. {
  6464. return array();
  6465. }
  6466. public function behaviors()
  6467. {
  6468. return array();
  6469. }
  6470. public function attributeLabels()
  6471. {
  6472. return array();
  6473. }
  6474. public function validate($attributes=null, $clearErrors=true)
  6475. {
  6476. if($clearErrors)
  6477. $this->clearErrors();
  6478. if($this->beforeValidate())
  6479. {
  6480. foreach($this->getValidators() as $validator)
  6481. $validator->validate($this,$attributes);
  6482. $this->afterValidate();
  6483. return !$this->hasErrors();
  6484. }
  6485. else
  6486. return false;
  6487. }
  6488. protected function afterConstruct()
  6489. {
  6490. if($this->hasEventHandler('onAfterConstruct'))
  6491. $this->onAfterConstruct(new CEvent($this));
  6492. }
  6493. protected function beforeValidate()
  6494. {
  6495. $event=new CModelEvent($this);
  6496. $this->onBeforeValidate($event);
  6497. return $event->isValid;
  6498. }
  6499. protected function afterValidate()
  6500. {
  6501. $this->onAfterValidate(new CEvent($this));
  6502. }
  6503. public function onAfterConstruct($event)
  6504. {
  6505. $this->raiseEvent('onAfterConstruct',$event);
  6506. }
  6507. public function onBeforeValidate($event)
  6508. {
  6509. $this->raiseEvent('onBeforeValidate',$event);
  6510. }
  6511. public function onAfterValidate($event)
  6512. {
  6513. $this->raiseEvent('onAfterValidate',$event);
  6514. }
  6515. public function getValidatorList()
  6516. {
  6517. if($this->_validators===null)
  6518. $this->_validators=$this->createValidators();
  6519. return $this->_validators;
  6520. }
  6521. public function getValidators($attribute=null)
  6522. {
  6523. if($this->_validators===null)
  6524. $this->_validators=$this->createValidators();
  6525. $validators=array();
  6526. $scenario=$this->getScenario();
  6527. foreach($this->_validators as $validator)
  6528. {
  6529. if($validator->applyTo($scenario))
  6530. {
  6531. if($attribute===null || in_array($attribute,$validator->attributes,true))
  6532. $validators[]=$validator;
  6533. }
  6534. }
  6535. return $validators;
  6536. }
  6537. public function createValidators()
  6538. {
  6539. $validators=new CList;
  6540. foreach($this->rules() as $rule)
  6541. {
  6542. if(isset($rule[0],$rule[1])) // attributes, validator name
  6543. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  6544. else
  6545. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  6546. array('{class}'=>get_class($this))));
  6547. }
  6548. return $validators;
  6549. }
  6550. public function isAttributeRequired($attribute)
  6551. {
  6552. foreach($this->getValidators($attribute) as $validator)
  6553. {
  6554. if($validator instanceof CRequiredValidator)
  6555. return true;
  6556. }
  6557. return false;
  6558. }
  6559. public function isAttributeSafe($attribute)
  6560. {
  6561. $attributes=$this->getSafeAttributeNames();
  6562. return in_array($attribute,$attributes);
  6563. }
  6564. public function getAttributeLabel($attribute)
  6565. {
  6566. $labels=$this->attributeLabels();
  6567. if(isset($labels[$attribute]))
  6568. return $labels[$attribute];
  6569. else
  6570. return $this->generateAttributeLabel($attribute);
  6571. }
  6572. public function hasErrors($attribute=null)
  6573. {
  6574. if($attribute===null)
  6575. return $this->_errors!==array();
  6576. else
  6577. return isset($this->_errors[$attribute]);
  6578. }
  6579. public function getErrors($attribute=null)
  6580. {
  6581. if($attribute===null)
  6582. return $this->_errors;
  6583. else
  6584. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  6585. }
  6586. public function getError($attribute)
  6587. {
  6588. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  6589. }
  6590. public function addError($attribute,$error)
  6591. {
  6592. $this->_errors[$attribute][]=$error;
  6593. }
  6594. public function addErrors($errors)
  6595. {
  6596. foreach($errors as $attribute=>$error)
  6597. {
  6598. if(is_array($error))
  6599. {
  6600. foreach($error as $e)
  6601. $this->addError($attribute, $e);
  6602. }
  6603. else
  6604. $this->addError($attribute, $error);
  6605. }
  6606. }
  6607. public function clearErrors($attribute=null)
  6608. {
  6609. if($attribute===null)
  6610. $this->_errors=array();
  6611. else
  6612. unset($this->_errors[$attribute]);
  6613. }
  6614. public function generateAttributeLabel($name)
  6615. {
  6616. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  6617. }
  6618. public function getAttributes($names=null)
  6619. {
  6620. $values=array();
  6621. foreach($this->attributeNames() as $name)
  6622. $values[$name]=$this->$name;
  6623. if(is_array($names))
  6624. {
  6625. $values2=array();
  6626. foreach($names as $name)
  6627. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  6628. return $values2;
  6629. }
  6630. else
  6631. return $values;
  6632. }
  6633. public function setAttributes($values,$safeOnly=true)
  6634. {
  6635. if(!is_array($values))
  6636. return;
  6637. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  6638. foreach($values as $name=>$value)
  6639. {
  6640. if(isset($attributes[$name]))
  6641. $this->$name=$value;
  6642. else if($safeOnly)
  6643. $this->onUnsafeAttribute($name,$value);
  6644. }
  6645. }
  6646. public function unsetAttributes($names=null)
  6647. {
  6648. if($names===null)
  6649. $names=$this->attributeNames();
  6650. foreach($names as $name)
  6651. $this->$name=null;
  6652. }
  6653. public function onUnsafeAttribute($name,$value)
  6654. {
  6655. if(YII_DEBUG)
  6656. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  6657. }
  6658. public function getScenario()
  6659. {
  6660. return $this->_scenario;
  6661. }
  6662. public function setScenario($value)
  6663. {
  6664. $this->_scenario=$value;
  6665. }
  6666. public function getSafeAttributeNames()
  6667. {
  6668. $attributes=array();
  6669. $unsafe=array();
  6670. foreach($this->getValidators() as $validator)
  6671. {
  6672. if(!$validator->safe)
  6673. {
  6674. foreach($validator->attributes as $name)
  6675. $unsafe[]=$name;
  6676. }
  6677. else
  6678. {
  6679. foreach($validator->attributes as $name)
  6680. $attributes[$name]=true;
  6681. }
  6682. }
  6683. foreach($unsafe as $name)
  6684. unset($attributes[$name]);
  6685. return array_keys($attributes);
  6686. }
  6687. public function getIterator()
  6688. {
  6689. $attributes=$this->getAttributes();
  6690. return new CMapIterator($attributes);
  6691. }
  6692. public function offsetExists($offset)
  6693. {
  6694. return property_exists($this,$offset);
  6695. }
  6696. public function offsetGet($offset)
  6697. {
  6698. return $this->$offset;
  6699. }
  6700. public function offsetSet($offset,$item)
  6701. {
  6702. $this->$offset=$item;
  6703. }
  6704. public function offsetUnset($offset)
  6705. {
  6706. unset($this->$offset);
  6707. }
  6708. }
  6709. abstract class CActiveRecord extends CModel
  6710. {
  6711. const BELONGS_TO='CBelongsToRelation';
  6712. const HAS_ONE='CHasOneRelation';
  6713. const HAS_MANY='CHasManyRelation';
  6714. const MANY_MANY='CManyManyRelation';
  6715. const STAT='CStatRelation';
  6716. public static $db;
  6717. private static $_models=array(); // class name => model
  6718. private $_md; // meta data
  6719. private $_new=false; // whether this instance is new or not
  6720. private $_attributes=array(); // attribute name => attribute value
  6721. private $_related=array(); // attribute name => related objects
  6722. private $_c; // query criteria (used by finder only)
  6723. private $_pk; // old primary key value
  6724. private $_alias='t'; // the table alias being used for query
  6725. public function __construct($scenario='insert')
  6726. {
  6727. if($scenario===null) // internally used by populateRecord() and model()
  6728. return;
  6729. $this->setScenario($scenario);
  6730. $this->setIsNewRecord(true);
  6731. $this->_attributes=$this->getMetaData()->attributeDefaults;
  6732. $this->init();
  6733. $this->attachBehaviors($this->behaviors());
  6734. $this->afterConstruct();
  6735. }
  6736. public function init()
  6737. {
  6738. }
  6739. public function cache($duration, $dependency=null, $queryCount=1)
  6740. {
  6741. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  6742. return $this;
  6743. }
  6744. public function __sleep()
  6745. {
  6746. $this->_md=null;
  6747. return array_keys((array)$this);
  6748. }
  6749. public function __get($name)
  6750. {
  6751. if(isset($this->_attributes[$name]))
  6752. return $this->_attributes[$name];
  6753. else if(isset($this->getMetaData()->columns[$name]))
  6754. return null;
  6755. else if(isset($this->_related[$name]))
  6756. return $this->_related[$name];
  6757. else if(isset($this->getMetaData()->relations[$name]))
  6758. return $this->getRelated($name);
  6759. else
  6760. return parent::__get($name);
  6761. }
  6762. public function __set($name,$value)
  6763. {
  6764. if($this->setAttribute($name,$value)===false)
  6765. {
  6766. if(isset($this->getMetaData()->relations[$name]))
  6767. $this->_related[$name]=$value;
  6768. else
  6769. parent::__set($name,$value);
  6770. }
  6771. }
  6772. public function __isset($name)
  6773. {
  6774. if(isset($this->_attributes[$name]))
  6775. return true;
  6776. else if(isset($this->getMetaData()->columns[$name]))
  6777. return false;
  6778. else if(isset($this->_related[$name]))
  6779. return true;
  6780. else if(isset($this->getMetaData()->relations[$name]))
  6781. return $this->getRelated($name)!==null;
  6782. else
  6783. return parent::__isset($name);
  6784. }
  6785. public function __unset($name)
  6786. {
  6787. if(isset($this->getMetaData()->columns[$name]))
  6788. unset($this->_attributes[$name]);
  6789. else if(isset($this->getMetaData()->relations[$name]))
  6790. unset($this->_related[$name]);
  6791. else
  6792. parent::__unset($name);
  6793. }
  6794. public function __call($name,$parameters)
  6795. {
  6796. if(isset($this->getMetaData()->relations[$name]))
  6797. {
  6798. if(empty($parameters))
  6799. return $this->getRelated($name,false);
  6800. else
  6801. return $this->getRelated($name,false,$parameters[0]);
  6802. }
  6803. $scopes=$this->scopes();
  6804. if(isset($scopes[$name]))
  6805. {
  6806. $this->getDbCriteria()->mergeWith($scopes[$name]);
  6807. return $this;
  6808. }
  6809. return parent::__call($name,$parameters);
  6810. }
  6811. public function getRelated($name,$refresh=false,$params=array())
  6812. {
  6813. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  6814. return $this->_related[$name];
  6815. $md=$this->getMetaData();
  6816. if(!isset($md->relations[$name]))
  6817. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  6818. array('{class}'=>get_class($this), '{name}'=>$name)));
  6819. $relation=$md->relations[$name];
  6820. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  6821. return $relation instanceof CHasOneRelation ? null : array();
  6822. if($params!==array()) // dynamic query
  6823. {
  6824. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6825. if($exists)
  6826. $save=$this->_related[$name];
  6827. if($params instanceof CDbCriteria)
  6828. $params = $params->toArray();
  6829. $r=array($name=>$params);
  6830. }
  6831. else
  6832. $r=$name;
  6833. unset($this->_related[$name]);
  6834. $finder=new CActiveFinder($this,$r);
  6835. $finder->lazyFind($this);
  6836. if(!isset($this->_related[$name]))
  6837. {
  6838. if($relation instanceof CHasManyRelation)
  6839. $this->_related[$name]=array();
  6840. else if($relation instanceof CStatRelation)
  6841. $this->_related[$name]=$relation->defaultValue;
  6842. else
  6843. $this->_related[$name]=null;
  6844. }
  6845. if($params!==array())
  6846. {
  6847. $results=$this->_related[$name];
  6848. if($exists)
  6849. $this->_related[$name]=$save;
  6850. else
  6851. unset($this->_related[$name]);
  6852. return $results;
  6853. }
  6854. else
  6855. return $this->_related[$name];
  6856. }
  6857. public function hasRelated($name)
  6858. {
  6859. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6860. }
  6861. public function getDbCriteria($createIfNull=true)
  6862. {
  6863. if($this->_c===null)
  6864. {
  6865. if(($c=$this->defaultScope())!==array() || $createIfNull)
  6866. $this->_c=new CDbCriteria($c);
  6867. }
  6868. return $this->_c;
  6869. }
  6870. public function setDbCriteria($criteria)
  6871. {
  6872. $this->_c=$criteria;
  6873. }
  6874. public function defaultScope()
  6875. {
  6876. return array();
  6877. }
  6878. public function resetScope($resetDefault=true)
  6879. {
  6880. if($resetDefault)
  6881. $this->_c=new CDbCriteria();
  6882. else
  6883. $this->_c=null;
  6884. return $this;
  6885. }
  6886. public static function model($className=__CLASS__)
  6887. {
  6888. if(isset(self::$_models[$className]))
  6889. return self::$_models[$className];
  6890. else
  6891. {
  6892. $model=self::$_models[$className]=new $className(null);
  6893. $model->_md=new CActiveRecordMetaData($model);
  6894. $model->attachBehaviors($model->behaviors());
  6895. return $model;
  6896. }
  6897. }
  6898. public function getMetaData()
  6899. {
  6900. if($this->_md!==null)
  6901. return $this->_md;
  6902. else
  6903. return $this->_md=self::model(get_class($this))->_md;
  6904. }
  6905. public function refreshMetaData()
  6906. {
  6907. $finder=self::model(get_class($this));
  6908. $finder->_md=new CActiveRecordMetaData($finder);
  6909. if($this!==$finder)
  6910. $this->_md=$finder->_md;
  6911. }
  6912. public function tableName()
  6913. {
  6914. return get_class($this);
  6915. }
  6916. public function primaryKey()
  6917. {
  6918. }
  6919. public function relations()
  6920. {
  6921. return array();
  6922. }
  6923. public function scopes()
  6924. {
  6925. return array();
  6926. }
  6927. public function attributeNames()
  6928. {
  6929. return array_keys($this->getMetaData()->columns);
  6930. }
  6931. public function getAttributeLabel($attribute)
  6932. {
  6933. $labels=$this->attributeLabels();
  6934. if(isset($labels[$attribute]))
  6935. return $labels[$attribute];
  6936. else if(strpos($attribute,'.')!==false)
  6937. {
  6938. $segs=explode('.',$attribute);
  6939. $name=array_pop($segs);
  6940. $model=$this;
  6941. foreach($segs as $seg)
  6942. {
  6943. $relations=$model->getMetaData()->relations;
  6944. if(isset($relations[$seg]))
  6945. $model=CActiveRecord::model($relations[$seg]->className);
  6946. else
  6947. break;
  6948. }
  6949. return $model->getAttributeLabel($name);
  6950. }
  6951. else
  6952. return $this->generateAttributeLabel($attribute);
  6953. }
  6954. public function getDbConnection()
  6955. {
  6956. if(self::$db!==null)
  6957. return self::$db;
  6958. else
  6959. {
  6960. self::$db=Yii::app()->getDb();
  6961. if(self::$db instanceof CDbConnection)
  6962. return self::$db;
  6963. else
  6964. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  6965. }
  6966. }
  6967. public function getActiveRelation($name)
  6968. {
  6969. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  6970. }
  6971. public function getTableSchema()
  6972. {
  6973. return $this->getMetaData()->tableSchema;
  6974. }
  6975. public function getCommandBuilder()
  6976. {
  6977. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  6978. }
  6979. public function hasAttribute($name)
  6980. {
  6981. return isset($this->getMetaData()->columns[$name]);
  6982. }
  6983. public function getAttribute($name)
  6984. {
  6985. if(property_exists($this,$name))
  6986. return $this->$name;
  6987. else if(isset($this->_attributes[$name]))
  6988. return $this->_attributes[$name];
  6989. }
  6990. public function setAttribute($name,$value)
  6991. {
  6992. if(property_exists($this,$name))
  6993. $this->$name=$value;
  6994. else if(isset($this->getMetaData()->columns[$name]))
  6995. $this->_attributes[$name]=$value;
  6996. else
  6997. return false;
  6998. return true;
  6999. }
  7000. public function addRelatedRecord($name,$record,$index)
  7001. {
  7002. if($index!==false)
  7003. {
  7004. if(!isset($this->_related[$name]))
  7005. $this->_related[$name]=array();
  7006. if($record instanceof CActiveRecord)
  7007. {
  7008. if($index===true)
  7009. $this->_related[$name][]=$record;
  7010. else
  7011. $this->_related[$name][$index]=$record;
  7012. }
  7013. }
  7014. else if(!isset($this->_related[$name]))
  7015. $this->_related[$name]=$record;
  7016. }
  7017. public function getAttributes($names=true)
  7018. {
  7019. $attributes=$this->_attributes;
  7020. foreach($this->getMetaData()->columns as $name=>$column)
  7021. {
  7022. if(property_exists($this,$name))
  7023. $attributes[$name]=$this->$name;
  7024. else if($names===true && !isset($attributes[$name]))
  7025. $attributes[$name]=null;
  7026. }
  7027. if(is_array($names))
  7028. {
  7029. $attrs=array();
  7030. foreach($names as $name)
  7031. {
  7032. if(property_exists($this,$name))
  7033. $attrs[$name]=$this->$name;
  7034. else
  7035. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  7036. }
  7037. return $attrs;
  7038. }
  7039. else
  7040. return $attributes;
  7041. }
  7042. public function save($runValidation=true,$attributes=null)
  7043. {
  7044. if(!$runValidation || $this->validate($attributes))
  7045. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  7046. else
  7047. return false;
  7048. }
  7049. public function getIsNewRecord()
  7050. {
  7051. return $this->_new;
  7052. }
  7053. public function setIsNewRecord($value)
  7054. {
  7055. $this->_new=$value;
  7056. }
  7057. public function onBeforeSave($event)
  7058. {
  7059. $this->raiseEvent('onBeforeSave',$event);
  7060. }
  7061. public function onAfterSave($event)
  7062. {
  7063. $this->raiseEvent('onAfterSave',$event);
  7064. }
  7065. public function onBeforeDelete($event)
  7066. {
  7067. $this->raiseEvent('onBeforeDelete',$event);
  7068. }
  7069. public function onAfterDelete($event)
  7070. {
  7071. $this->raiseEvent('onAfterDelete',$event);
  7072. }
  7073. public function onBeforeFind($event)
  7074. {
  7075. $this->raiseEvent('onBeforeFind',$event);
  7076. }
  7077. public function onAfterFind($event)
  7078. {
  7079. $this->raiseEvent('onAfterFind',$event);
  7080. }
  7081. protected function beforeSave()
  7082. {
  7083. if($this->hasEventHandler('onBeforeSave'))
  7084. {
  7085. $event=new CModelEvent($this);
  7086. $this->onBeforeSave($event);
  7087. return $event->isValid;
  7088. }
  7089. else
  7090. return true;
  7091. }
  7092. protected function afterSave()
  7093. {
  7094. if($this->hasEventHandler('onAfterSave'))
  7095. $this->onAfterSave(new CEvent($this));
  7096. }
  7097. protected function beforeDelete()
  7098. {
  7099. if($this->hasEventHandler('onBeforeDelete'))
  7100. {
  7101. $event=new CModelEvent($this);
  7102. $this->onBeforeDelete($event);
  7103. return $event->isValid;
  7104. }
  7105. else
  7106. return true;
  7107. }
  7108. protected function afterDelete()
  7109. {
  7110. if($this->hasEventHandler('onAfterDelete'))
  7111. $this->onAfterDelete(new CEvent($this));
  7112. }
  7113. protected function beforeFind()
  7114. {
  7115. if($this->hasEventHandler('onBeforeFind'))
  7116. {
  7117. $event=new CModelEvent($this);
  7118. $this->onBeforeFind($event);
  7119. }
  7120. }
  7121. protected function afterFind()
  7122. {
  7123. if($this->hasEventHandler('onAfterFind'))
  7124. $this->onAfterFind(new CEvent($this));
  7125. }
  7126. public function beforeFindInternal()
  7127. {
  7128. $this->beforeFind();
  7129. }
  7130. public function afterFindInternal()
  7131. {
  7132. $this->afterFind();
  7133. }
  7134. public function insert($attributes=null)
  7135. {
  7136. if(!$this->getIsNewRecord())
  7137. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  7138. if($this->beforeSave())
  7139. {
  7140. $builder=$this->getCommandBuilder();
  7141. $table=$this->getMetaData()->tableSchema;
  7142. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  7143. if($command->execute())
  7144. {
  7145. $primaryKey=$table->primaryKey;
  7146. if($table->sequenceName!==null)
  7147. {
  7148. if(is_string($primaryKey) && $this->$primaryKey===null)
  7149. $this->$primaryKey=$builder->getLastInsertID($table);
  7150. else if(is_array($primaryKey))
  7151. {
  7152. foreach($primaryKey as $pk)
  7153. {
  7154. if($this->$pk===null)
  7155. {
  7156. $this->$pk=$builder->getLastInsertID($table);
  7157. break;
  7158. }
  7159. }
  7160. }
  7161. }
  7162. $this->_pk=$this->getPrimaryKey();
  7163. $this->afterSave();
  7164. $this->setIsNewRecord(false);
  7165. $this->setScenario('update');
  7166. return true;
  7167. }
  7168. }
  7169. return false;
  7170. }
  7171. public function update($attributes=null)
  7172. {
  7173. if($this->getIsNewRecord())
  7174. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7175. if($this->beforeSave())
  7176. {
  7177. if($this->_pk===null)
  7178. $this->_pk=$this->getPrimaryKey();
  7179. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  7180. $this->_pk=$this->getPrimaryKey();
  7181. $this->afterSave();
  7182. return true;
  7183. }
  7184. else
  7185. return false;
  7186. }
  7187. public function saveAttributes($attributes)
  7188. {
  7189. if(!$this->getIsNewRecord())
  7190. {
  7191. $values=array();
  7192. foreach($attributes as $name=>$value)
  7193. {
  7194. if(is_integer($name))
  7195. $values[$value]=$this->$value;
  7196. else
  7197. $values[$name]=$this->$name=$value;
  7198. }
  7199. if($this->_pk===null)
  7200. $this->_pk=$this->getPrimaryKey();
  7201. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  7202. {
  7203. $this->_pk=$this->getPrimaryKey();
  7204. return true;
  7205. }
  7206. else
  7207. return false;
  7208. }
  7209. else
  7210. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7211. }
  7212. public function saveCounters($counters)
  7213. {
  7214. $builder=$this->getCommandBuilder();
  7215. $table=$this->getTableSchema();
  7216. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  7217. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7218. if($command->execute())
  7219. {
  7220. foreach($counters as $name=>$value)
  7221. $this->$name=$this->$name+$value;
  7222. return true;
  7223. }
  7224. else
  7225. return false;
  7226. }
  7227. public function delete()
  7228. {
  7229. if(!$this->getIsNewRecord())
  7230. {
  7231. if($this->beforeDelete())
  7232. {
  7233. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  7234. $this->afterDelete();
  7235. return $result;
  7236. }
  7237. else
  7238. return false;
  7239. }
  7240. else
  7241. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  7242. }
  7243. public function refresh()
  7244. {
  7245. if(($record=$this->findByPk($this->getPrimaryKey()))!==null)
  7246. {
  7247. $this->_attributes=array();
  7248. $this->_related=array();
  7249. foreach($this->getMetaData()->columns as $name=>$column)
  7250. {
  7251. if(property_exists($this,$name))
  7252. $this->$name=$record->$name;
  7253. else
  7254. $this->_attributes[$name]=$record->$name;
  7255. }
  7256. return true;
  7257. }
  7258. else
  7259. return false;
  7260. }
  7261. public function equals($record)
  7262. {
  7263. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  7264. }
  7265. public function getPrimaryKey()
  7266. {
  7267. $table=$this->getMetaData()->tableSchema;
  7268. if(is_string($table->primaryKey))
  7269. return $this->{$table->primaryKey};
  7270. else if(is_array($table->primaryKey))
  7271. {
  7272. $values=array();
  7273. foreach($table->primaryKey as $name)
  7274. $values[$name]=$this->$name;
  7275. return $values;
  7276. }
  7277. else
  7278. return null;
  7279. }
  7280. public function setPrimaryKey($value)
  7281. {
  7282. $this->_pk=$this->getPrimaryKey();
  7283. $table=$this->getMetaData()->tableSchema;
  7284. if(is_string($table->primaryKey))
  7285. $this->{$table->primaryKey}=$value;
  7286. else if(is_array($table->primaryKey))
  7287. {
  7288. foreach($table->primaryKey as $name)
  7289. $this->$name=$value[$name];
  7290. }
  7291. }
  7292. public function getOldPrimaryKey()
  7293. {
  7294. return $this->_pk;
  7295. }
  7296. public function setOldPrimaryKey($value)
  7297. {
  7298. $this->_pk=$value;
  7299. }
  7300. protected function query($criteria,$all=false)
  7301. {
  7302. $this->beforeFind();
  7303. $this->applyScopes($criteria);
  7304. if(empty($criteria->with))
  7305. {
  7306. if(!$all)
  7307. $criteria->limit=1;
  7308. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  7309. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  7310. }
  7311. else
  7312. {
  7313. $finder=new CActiveFinder($this,$criteria->with);
  7314. return $finder->query($criteria,$all);
  7315. }
  7316. }
  7317. public function applyScopes(&$criteria)
  7318. {
  7319. if(!empty($criteria->scopes))
  7320. {
  7321. $scs=$this->scopes();
  7322. $c=$this->getDbCriteria();
  7323. foreach((array)$criteria->scopes as $k=>$v)
  7324. {
  7325. if(is_integer($k))
  7326. {
  7327. if(is_string($v))
  7328. {
  7329. if(isset($scs[$v]))
  7330. {
  7331. $c->mergeWith($scs[$v],true);
  7332. continue;
  7333. }
  7334. $scope=$v;
  7335. $params=array();
  7336. }
  7337. else if(is_array($v))
  7338. {
  7339. $scope=key($v);
  7340. $params=current($v);
  7341. }
  7342. }
  7343. else if(is_string($k))
  7344. {
  7345. $scope=$k;
  7346. $params=$v;
  7347. }
  7348. call_user_func_array(array($this,$scope),(array)$params);
  7349. }
  7350. }
  7351. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  7352. {
  7353. $c->mergeWith($criteria);
  7354. $criteria=$c;
  7355. $this->resetScope(false);
  7356. }
  7357. }
  7358. public function getTableAlias($quote=false, $checkScopes=true)
  7359. {
  7360. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  7361. $alias=$criteria->alias;
  7362. else
  7363. $alias=$this->_alias;
  7364. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  7365. }
  7366. public function setTableAlias($alias)
  7367. {
  7368. $this->_alias=$alias;
  7369. }
  7370. public function find($condition='',$params=array())
  7371. {
  7372. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7373. return $this->query($criteria);
  7374. }
  7375. public function findAll($condition='',$params=array())
  7376. {
  7377. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7378. return $this->query($criteria,true);
  7379. }
  7380. public function findByPk($pk,$condition='',$params=array())
  7381. {
  7382. $prefix=$this->getTableAlias(true).'.';
  7383. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7384. return $this->query($criteria);
  7385. }
  7386. public function findAllByPk($pk,$condition='',$params=array())
  7387. {
  7388. $prefix=$this->getTableAlias(true).'.';
  7389. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7390. return $this->query($criteria,true);
  7391. }
  7392. public function findByAttributes($attributes,$condition='',$params=array())
  7393. {
  7394. $prefix=$this->getTableAlias(true).'.';
  7395. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7396. return $this->query($criteria);
  7397. }
  7398. public function findAllByAttributes($attributes,$condition='',$params=array())
  7399. {
  7400. $prefix=$this->getTableAlias(true).'.';
  7401. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7402. return $this->query($criteria,true);
  7403. }
  7404. public function findBySql($sql,$params=array())
  7405. {
  7406. $this->beforeFind();
  7407. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7408. {
  7409. $this->resetScope(false);
  7410. $finder=new CActiveFinder($this,$criteria->with);
  7411. return $finder->findBySql($sql,$params);
  7412. }
  7413. else
  7414. {
  7415. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7416. return $this->populateRecord($command->queryRow());
  7417. }
  7418. }
  7419. public function findAllBySql($sql,$params=array())
  7420. {
  7421. $this->beforeFind();
  7422. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7423. {
  7424. $this->resetScope(false);
  7425. $finder=new CActiveFinder($this,$criteria->with);
  7426. return $finder->findAllBySql($sql,$params);
  7427. }
  7428. else
  7429. {
  7430. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7431. return $this->populateRecords($command->queryAll());
  7432. }
  7433. }
  7434. public function count($condition='',$params=array())
  7435. {
  7436. $builder=$this->getCommandBuilder();
  7437. $criteria=$builder->createCriteria($condition,$params);
  7438. $this->applyScopes($criteria);
  7439. if(empty($criteria->with))
  7440. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7441. else
  7442. {
  7443. $finder=new CActiveFinder($this,$criteria->with);
  7444. return $finder->count($criteria);
  7445. }
  7446. }
  7447. public function countByAttributes($attributes,$condition='',$params=array())
  7448. {
  7449. $prefix=$this->getTableAlias(true).'.';
  7450. $builder=$this->getCommandBuilder();
  7451. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7452. $this->applyScopes($criteria);
  7453. if(empty($criteria->with))
  7454. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7455. else
  7456. {
  7457. $finder=new CActiveFinder($this,$criteria->with);
  7458. return $finder->count($criteria);
  7459. }
  7460. }
  7461. public function countBySql($sql,$params=array())
  7462. {
  7463. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  7464. }
  7465. public function exists($condition='',$params=array())
  7466. {
  7467. $builder=$this->getCommandBuilder();
  7468. $criteria=$builder->createCriteria($condition,$params);
  7469. $table=$this->getTableSchema();
  7470. $criteria->select='1';
  7471. $criteria->limit=1;
  7472. $this->applyScopes($criteria);
  7473. if(empty($criteria->with))
  7474. return $builder->createFindCommand($table,$criteria)->queryRow()!==false;
  7475. else
  7476. {
  7477. $criteria->select='*';
  7478. $finder=new CActiveFinder($this,$criteria->with);
  7479. return $finder->count($criteria)>0;
  7480. }
  7481. }
  7482. public function with()
  7483. {
  7484. if(func_num_args()>0)
  7485. {
  7486. $with=func_get_args();
  7487. if(is_array($with[0])) // the parameter is given as an array
  7488. $with=$with[0];
  7489. if(!empty($with))
  7490. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  7491. }
  7492. return $this;
  7493. }
  7494. public function together()
  7495. {
  7496. $this->getDbCriteria()->together=true;
  7497. return $this;
  7498. }
  7499. public function updateByPk($pk,$attributes,$condition='',$params=array())
  7500. {
  7501. $builder=$this->getCommandBuilder();
  7502. $table=$this->getTableSchema();
  7503. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  7504. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  7505. return $command->execute();
  7506. }
  7507. public function updateAll($attributes,$condition='',$params=array())
  7508. {
  7509. $builder=$this->getCommandBuilder();
  7510. $criteria=$builder->createCriteria($condition,$params);
  7511. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  7512. return $command->execute();
  7513. }
  7514. public function updateCounters($counters,$condition='',$params=array())
  7515. {
  7516. $builder=$this->getCommandBuilder();
  7517. $criteria=$builder->createCriteria($condition,$params);
  7518. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7519. return $command->execute();
  7520. }
  7521. public function deleteByPk($pk,$condition='',$params=array())
  7522. {
  7523. $builder=$this->getCommandBuilder();
  7524. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  7525. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7526. return $command->execute();
  7527. }
  7528. public function deleteAll($condition='',$params=array())
  7529. {
  7530. $builder=$this->getCommandBuilder();
  7531. $criteria=$builder->createCriteria($condition,$params);
  7532. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7533. return $command->execute();
  7534. }
  7535. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  7536. {
  7537. $builder=$this->getCommandBuilder();
  7538. $table=$this->getTableSchema();
  7539. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  7540. $command=$builder->createDeleteCommand($table,$criteria);
  7541. return $command->execute();
  7542. }
  7543. public function populateRecord($attributes,$callAfterFind=true)
  7544. {
  7545. if($attributes!==false)
  7546. {
  7547. $record=$this->instantiate($attributes);
  7548. $record->setScenario('update');
  7549. $record->init();
  7550. $md=$record->getMetaData();
  7551. foreach($attributes as $name=>$value)
  7552. {
  7553. if(property_exists($record,$name))
  7554. $record->$name=$value;
  7555. else if(isset($md->columns[$name]))
  7556. $record->_attributes[$name]=$value;
  7557. }
  7558. $record->_pk=$record->getPrimaryKey();
  7559. $record->attachBehaviors($record->behaviors());
  7560. if($callAfterFind)
  7561. $record->afterFind();
  7562. return $record;
  7563. }
  7564. else
  7565. return null;
  7566. }
  7567. public function populateRecords($data,$callAfterFind=true,$index=null)
  7568. {
  7569. $records=array();
  7570. foreach($data as $attributes)
  7571. {
  7572. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  7573. {
  7574. if($index===null)
  7575. $records[]=$record;
  7576. else
  7577. $records[$record->$index]=$record;
  7578. }
  7579. }
  7580. return $records;
  7581. }
  7582. protected function instantiate($attributes)
  7583. {
  7584. $class=get_class($this);
  7585. $model=new $class(null);
  7586. return $model;
  7587. }
  7588. public function offsetExists($offset)
  7589. {
  7590. return $this->__isset($offset);
  7591. }
  7592. }
  7593. class CBaseActiveRelation extends CComponent
  7594. {
  7595. public $name;
  7596. public $className;
  7597. public $foreignKey;
  7598. public $select='*';
  7599. public $condition='';
  7600. public $params=array();
  7601. public $group='';
  7602. public $join='';
  7603. public $having='';
  7604. public $order='';
  7605. public function __construct($name,$className,$foreignKey,$options=array())
  7606. {
  7607. $this->name=$name;
  7608. $this->className=$className;
  7609. $this->foreignKey=$foreignKey;
  7610. foreach($options as $name=>$value)
  7611. $this->$name=$value;
  7612. }
  7613. public function mergeWith($criteria,$fromScope=false)
  7614. {
  7615. if($criteria instanceof CDbCriteria)
  7616. $criteria=$criteria->toArray();
  7617. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  7618. {
  7619. if($this->select==='*')
  7620. $this->select=$criteria['select'];
  7621. else if($criteria['select']!=='*')
  7622. {
  7623. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  7624. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  7625. $this->select=array_merge($select1,array_diff($select2,$select1));
  7626. }
  7627. }
  7628. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  7629. {
  7630. if($this->condition==='')
  7631. $this->condition=$criteria['condition'];
  7632. else if($criteria['condition']!=='')
  7633. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  7634. }
  7635. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  7636. $this->params=array_merge($this->params,$criteria['params']);
  7637. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  7638. {
  7639. if($this->order==='')
  7640. $this->order=$criteria['order'];
  7641. else if($criteria['order']!=='')
  7642. $this->order=$criteria['order'].', '.$this->order;
  7643. }
  7644. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  7645. {
  7646. if($this->group==='')
  7647. $this->group=$criteria['group'];
  7648. else if($criteria['group']!=='')
  7649. $this->group.=', '.$criteria['group'];
  7650. }
  7651. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  7652. {
  7653. if($this->join==='')
  7654. $this->join=$criteria['join'];
  7655. else if($criteria['join']!=='')
  7656. $this->join.=' '.$criteria['join'];
  7657. }
  7658. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  7659. {
  7660. if($this->having==='')
  7661. $this->having=$criteria['having'];
  7662. else if($criteria['having']!=='')
  7663. $this->having="({$this->having}) AND ({$criteria['having']})";
  7664. }
  7665. }
  7666. }
  7667. class CStatRelation extends CBaseActiveRelation
  7668. {
  7669. public $select='COUNT(*)';
  7670. public $defaultValue=0;
  7671. public function mergeWith($criteria,$fromScope=false)
  7672. {
  7673. if($criteria instanceof CDbCriteria)
  7674. $criteria=$criteria->toArray();
  7675. parent::mergeWith($criteria,$fromScope);
  7676. if(isset($criteria['defaultValue']))
  7677. $this->defaultValue=$criteria['defaultValue'];
  7678. }
  7679. }
  7680. class CActiveRelation extends CBaseActiveRelation
  7681. {
  7682. public $joinType='LEFT OUTER JOIN';
  7683. public $on='';
  7684. public $alias;
  7685. public $with=array();
  7686. public $together;
  7687. public $scopes;
  7688. public function mergeWith($criteria,$fromScope=false)
  7689. {
  7690. if($criteria instanceof CDbCriteria)
  7691. $criteria=$criteria->toArray();
  7692. if($fromScope)
  7693. {
  7694. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  7695. {
  7696. if($this->on==='')
  7697. $this->on=$criteria['condition'];
  7698. else if($criteria['condition']!=='')
  7699. $this->on="({$this->on}) AND ({$criteria['condition']})";
  7700. }
  7701. unset($criteria['condition']);
  7702. }
  7703. parent::mergeWith($criteria);
  7704. if(isset($criteria['joinType']))
  7705. $this->joinType=$criteria['joinType'];
  7706. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  7707. {
  7708. if($this->on==='')
  7709. $this->on=$criteria['on'];
  7710. else if($criteria['on']!=='')
  7711. $this->on="({$this->on}) AND ({$criteria['on']})";
  7712. }
  7713. if(isset($criteria['with']))
  7714. $this->with=$criteria['with'];
  7715. if(isset($criteria['alias']))
  7716. $this->alias=$criteria['alias'];
  7717. if(isset($criteria['together']))
  7718. $this->together=$criteria['together'];
  7719. }
  7720. }
  7721. class CBelongsToRelation extends CActiveRelation
  7722. {
  7723. }
  7724. class CHasOneRelation extends CActiveRelation
  7725. {
  7726. public $through;
  7727. }
  7728. class CHasManyRelation extends CActiveRelation
  7729. {
  7730. public $limit=-1;
  7731. public $offset=-1;
  7732. public $index;
  7733. public $through;
  7734. public function mergeWith($criteria,$fromScope=false)
  7735. {
  7736. if($criteria instanceof CDbCriteria)
  7737. $criteria=$criteria->toArray();
  7738. parent::mergeWith($criteria,$fromScope);
  7739. if(isset($criteria['limit']) && $criteria['limit']>0)
  7740. $this->limit=$criteria['limit'];
  7741. if(isset($criteria['offset']) && $criteria['offset']>=0)
  7742. $this->offset=$criteria['offset'];
  7743. if(isset($criteria['index']))
  7744. $this->index=$criteria['index'];
  7745. }
  7746. }
  7747. class CManyManyRelation extends CHasManyRelation
  7748. {
  7749. private $_junctionTableName=null;
  7750. private $_junctionForeignKeys=null;
  7751. public function getJunctionTableName()
  7752. {
  7753. if ($this->_junctionTableName===null)
  7754. $this->initJunctionData();
  7755. return $this->_junctionTableName;
  7756. }
  7757. public function getJunctionForeignKeys()
  7758. {
  7759. if ($this->_junctionForeignKeys===null)
  7760. $this->initJunctionData();
  7761. return $this->_junctionForeignKeys;
  7762. }
  7763. private function initJunctionData()
  7764. {
  7765. if(!preg_match('/^\s*(.*?)\((.*)\)\s*$/',$this->foreignKey,$matches))
  7766. 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,...)".',
  7767. array('{class}'=>$this->className,'{relation}'=>$this->name)));
  7768. $this->_junctionTableName=$matches[1];
  7769. $this->_junctionForeignKeys=preg_split('/\s*,\s*/',$matches[2],-1,PREG_SPLIT_NO_EMPTY);
  7770. }
  7771. }
  7772. class CActiveRecordMetaData
  7773. {
  7774. public $tableSchema;
  7775. public $columns;
  7776. public $relations=array();
  7777. public $attributeDefaults=array();
  7778. private $_model;
  7779. public function __construct($model)
  7780. {
  7781. $this->_model=$model;
  7782. $tableName=$model->tableName();
  7783. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  7784. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  7785. array('{class}'=>get_class($model),'{table}'=>$tableName)));
  7786. if($table->primaryKey===null)
  7787. {
  7788. $table->primaryKey=$model->primaryKey();
  7789. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  7790. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  7791. else if(is_array($table->primaryKey))
  7792. {
  7793. foreach($table->primaryKey as $name)
  7794. {
  7795. if(isset($table->columns[$name]))
  7796. $table->columns[$name]->isPrimaryKey=true;
  7797. }
  7798. }
  7799. }
  7800. $this->tableSchema=$table;
  7801. $this->columns=$table->columns;
  7802. foreach($table->columns as $name=>$column)
  7803. {
  7804. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  7805. $this->attributeDefaults[$name]=$column->defaultValue;
  7806. }
  7807. foreach($model->relations() as $name=>$config)
  7808. {
  7809. $this->addRelation($name,$config);
  7810. }
  7811. }
  7812. public function addRelation($name,$config)
  7813. {
  7814. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  7815. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  7816. else
  7817. throw new CDbException(Yii::t('yii','Active record "{class}" has an invalid configuration for relation "{relation}". It must specify the relation type, the related active record class and the foreign key.', array('{class}'=>get_class($this->_model),'{relation}'=>$name)));
  7818. }
  7819. public function hasRelation($name)
  7820. {
  7821. return isset($this->relations[$name]);
  7822. }
  7823. public function removeRelation($name)
  7824. {
  7825. unset($this->relations[$name]);
  7826. }
  7827. }
  7828. class CDbConnection extends CApplicationComponent
  7829. {
  7830. public $connectionString;
  7831. public $username='';
  7832. public $password='';
  7833. public $schemaCachingDuration=0;
  7834. public $schemaCachingExclude=array();
  7835. public $schemaCacheID='cache';
  7836. public $queryCachingDuration=0;
  7837. public $queryCachingDependency;
  7838. public $queryCachingCount=0;
  7839. public $queryCacheID='cache';
  7840. public $autoConnect=true;
  7841. public $charset;
  7842. public $emulatePrepare;
  7843. public $enableParamLogging=false;
  7844. public $enableProfiling=false;
  7845. public $tablePrefix;
  7846. public $initSQLs;
  7847. public $driverMap=array(
  7848. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  7849. 'mysqli'=>'CMysqlSchema', // MySQL
  7850. 'mysql'=>'CMysqlSchema', // MySQL
  7851. 'sqlite'=>'CSqliteSchema', // sqlite 3
  7852. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  7853. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  7854. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  7855. 'sqlsrv'=>'CMssqlSchema', // Mssql
  7856. 'oci'=>'COciSchema', // Oracle driver
  7857. );
  7858. public $pdoClass = 'PDO';
  7859. private $_attributes=array();
  7860. private $_active=false;
  7861. private $_pdo;
  7862. private $_transaction;
  7863. private $_schema;
  7864. public function __construct($dsn='',$username='',$password='')
  7865. {
  7866. $this->connectionString=$dsn;
  7867. $this->username=$username;
  7868. $this->password=$password;
  7869. }
  7870. public function __sleep()
  7871. {
  7872. $this->close();
  7873. return array_keys(get_object_vars($this));
  7874. }
  7875. public static function getAvailableDrivers()
  7876. {
  7877. return PDO::getAvailableDrivers();
  7878. }
  7879. public function init()
  7880. {
  7881. parent::init();
  7882. if($this->autoConnect)
  7883. $this->setActive(true);
  7884. }
  7885. public function getActive()
  7886. {
  7887. return $this->_active;
  7888. }
  7889. public function setActive($value)
  7890. {
  7891. if($value!=$this->_active)
  7892. {
  7893. if($value)
  7894. $this->open();
  7895. else
  7896. $this->close();
  7897. }
  7898. }
  7899. public function cache($duration, $dependency=null, $queryCount=1)
  7900. {
  7901. $this->queryCachingDuration=$duration;
  7902. $this->queryCachingDependency=$dependency;
  7903. $this->queryCachingCount=$queryCount;
  7904. return $this;
  7905. }
  7906. protected function open()
  7907. {
  7908. if($this->_pdo===null)
  7909. {
  7910. if(empty($this->connectionString))
  7911. throw new CDbException('CDbConnection.connectionString cannot be empty.');
  7912. try
  7913. {
  7914. $this->_pdo=$this->createPdoInstance();
  7915. $this->initConnection($this->_pdo);
  7916. $this->_active=true;
  7917. }
  7918. catch(PDOException $e)
  7919. {
  7920. if(YII_DEBUG)
  7921. {
  7922. throw new CDbException('CDbConnection failed to open the DB connection: '.
  7923. $e->getMessage(),(int)$e->getCode(),$e->errorInfo);
  7924. }
  7925. else
  7926. {
  7927. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  7928. throw new CDbException('CDbConnection failed to open the DB connection.',(int)$e->getCode(),$e->errorInfo);
  7929. }
  7930. }
  7931. }
  7932. }
  7933. protected function close()
  7934. {
  7935. $this->_pdo=null;
  7936. $this->_active=false;
  7937. $this->_schema=null;
  7938. }
  7939. protected function createPdoInstance()
  7940. {
  7941. $pdoClass=$this->pdoClass;
  7942. if(($pos=strpos($this->connectionString,':'))!==false)
  7943. {
  7944. $driver=strtolower(substr($this->connectionString,0,$pos));
  7945. if($driver==='mssql' || $driver==='dblib' || $driver==='sqlsrv')
  7946. $pdoClass='CMssqlPdoAdapter';
  7947. }
  7948. return new $pdoClass($this->connectionString,$this->username,
  7949. $this->password,$this->_attributes);
  7950. }
  7951. protected function initConnection($pdo)
  7952. {
  7953. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  7954. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  7955. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  7956. if($this->charset!==null)
  7957. {
  7958. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  7959. if(in_array($driver,array('pgsql','mysql','mysqli')))
  7960. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  7961. }
  7962. if($this->initSQLs!==null)
  7963. {
  7964. foreach($this->initSQLs as $sql)
  7965. $pdo->exec($sql);
  7966. }
  7967. }
  7968. public function getPdoInstance()
  7969. {
  7970. return $this->_pdo;
  7971. }
  7972. public function createCommand($query=null)
  7973. {
  7974. $this->setActive(true);
  7975. return new CDbCommand($this,$query);
  7976. }
  7977. public function getCurrentTransaction()
  7978. {
  7979. if($this->_transaction!==null)
  7980. {
  7981. if($this->_transaction->getActive())
  7982. return $this->_transaction;
  7983. }
  7984. return null;
  7985. }
  7986. public function beginTransaction()
  7987. {
  7988. $this->setActive(true);
  7989. $this->_pdo->beginTransaction();
  7990. return $this->_transaction=new CDbTransaction($this);
  7991. }
  7992. public function getSchema()
  7993. {
  7994. if($this->_schema!==null)
  7995. return $this->_schema;
  7996. else
  7997. {
  7998. $driver=$this->getDriverName();
  7999. if(isset($this->driverMap[$driver]))
  8000. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  8001. else
  8002. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  8003. array('{driver}'=>$driver)));
  8004. }
  8005. }
  8006. public function getCommandBuilder()
  8007. {
  8008. return $this->getSchema()->getCommandBuilder();
  8009. }
  8010. public function getLastInsertID($sequenceName='')
  8011. {
  8012. $this->setActive(true);
  8013. return $this->_pdo->lastInsertId($sequenceName);
  8014. }
  8015. public function quoteValue($str)
  8016. {
  8017. if(is_int($str) || is_float($str))
  8018. return $str;
  8019. $this->setActive(true);
  8020. if(($value=$this->_pdo->quote($str))!==false)
  8021. return $value;
  8022. else // the driver doesn't support quote (e.g. oci)
  8023. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  8024. }
  8025. public function quoteTableName($name)
  8026. {
  8027. return $this->getSchema()->quoteTableName($name);
  8028. }
  8029. public function quoteColumnName($name)
  8030. {
  8031. return $this->getSchema()->quoteColumnName($name);
  8032. }
  8033. public function getPdoType($type)
  8034. {
  8035. static $map=array
  8036. (
  8037. 'boolean'=>PDO::PARAM_BOOL,
  8038. 'integer'=>PDO::PARAM_INT,
  8039. 'string'=>PDO::PARAM_STR,
  8040. 'NULL'=>PDO::PARAM_NULL,
  8041. );
  8042. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  8043. }
  8044. public function getColumnCase()
  8045. {
  8046. return $this->getAttribute(PDO::ATTR_CASE);
  8047. }
  8048. public function setColumnCase($value)
  8049. {
  8050. $this->setAttribute(PDO::ATTR_CASE,$value);
  8051. }
  8052. public function getNullConversion()
  8053. {
  8054. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  8055. }
  8056. public function setNullConversion($value)
  8057. {
  8058. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  8059. }
  8060. public function getAutoCommit()
  8061. {
  8062. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  8063. }
  8064. public function setAutoCommit($value)
  8065. {
  8066. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  8067. }
  8068. public function getPersistent()
  8069. {
  8070. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  8071. }
  8072. public function setPersistent($value)
  8073. {
  8074. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  8075. }
  8076. public function getDriverName()
  8077. {
  8078. if(($pos=strpos($this->connectionString, ':'))!==false)
  8079. return strtolower(substr($this->connectionString, 0, $pos));
  8080. // return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  8081. }
  8082. public function getClientVersion()
  8083. {
  8084. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  8085. }
  8086. public function getConnectionStatus()
  8087. {
  8088. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  8089. }
  8090. public function getPrefetch()
  8091. {
  8092. return $this->getAttribute(PDO::ATTR_PREFETCH);
  8093. }
  8094. public function getServerInfo()
  8095. {
  8096. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  8097. }
  8098. public function getServerVersion()
  8099. {
  8100. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  8101. }
  8102. public function getTimeout()
  8103. {
  8104. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  8105. }
  8106. public function getAttribute($name)
  8107. {
  8108. $this->setActive(true);
  8109. return $this->_pdo->getAttribute($name);
  8110. }
  8111. public function setAttribute($name,$value)
  8112. {
  8113. if($this->_pdo instanceof PDO)
  8114. $this->_pdo->setAttribute($name,$value);
  8115. else
  8116. $this->_attributes[$name]=$value;
  8117. }
  8118. public function getAttributes()
  8119. {
  8120. return $this->_attributes;
  8121. }
  8122. public function setAttributes($values)
  8123. {
  8124. foreach($values as $name=>$value)
  8125. $this->_attributes[$name]=$value;
  8126. }
  8127. public function getStats()
  8128. {
  8129. $logger=Yii::getLogger();
  8130. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  8131. $count=count($timings);
  8132. $time=array_sum($timings);
  8133. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  8134. $count+=count($timings);
  8135. $time+=array_sum($timings);
  8136. return array($count,$time);
  8137. }
  8138. }
  8139. abstract class CDbSchema extends CComponent
  8140. {
  8141. public $columnTypes=array();
  8142. private $_tableNames=array();
  8143. private $_tables=array();
  8144. private $_connection;
  8145. private $_builder;
  8146. private $_cacheExclude=array();
  8147. abstract protected function loadTable($name);
  8148. public function __construct($conn)
  8149. {
  8150. $this->_connection=$conn;
  8151. foreach($conn->schemaCachingExclude as $name)
  8152. $this->_cacheExclude[$name]=true;
  8153. }
  8154. public function getDbConnection()
  8155. {
  8156. return $this->_connection;
  8157. }
  8158. public function getTable($name,$refresh=false)
  8159. {
  8160. if($refresh===false && isset($this->_tables[$name]))
  8161. return $this->_tables[$name];
  8162. else
  8163. {
  8164. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  8165. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  8166. else
  8167. $realName=$name;
  8168. // temporarily disable query caching
  8169. if($this->_connection->queryCachingDuration>0)
  8170. {
  8171. $qcDuration=$this->_connection->queryCachingDuration;
  8172. $this->_connection->queryCachingDuration=0;
  8173. }
  8174. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8175. {
  8176. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8177. $table=$cache->get($key);
  8178. if($refresh===true || $table===false)
  8179. {
  8180. $table=$this->loadTable($realName);
  8181. if($table!==null)
  8182. $cache->set($key,$table,$duration);
  8183. }
  8184. $this->_tables[$name]=$table;
  8185. }
  8186. else
  8187. $this->_tables[$name]=$table=$this->loadTable($realName);
  8188. if(isset($qcDuration)) // re-enable query caching
  8189. $this->_connection->queryCachingDuration=$qcDuration;
  8190. return $table;
  8191. }
  8192. }
  8193. public function getTables($schema='')
  8194. {
  8195. $tables=array();
  8196. foreach($this->getTableNames($schema) as $name)
  8197. {
  8198. if(($table=$this->getTable($name))!==null)
  8199. $tables[$name]=$table;
  8200. }
  8201. return $tables;
  8202. }
  8203. public function getTableNames($schema='')
  8204. {
  8205. if(!isset($this->_tableNames[$schema]))
  8206. $this->_tableNames[$schema]=$this->findTableNames($schema);
  8207. return $this->_tableNames[$schema];
  8208. }
  8209. public function getCommandBuilder()
  8210. {
  8211. if($this->_builder!==null)
  8212. return $this->_builder;
  8213. else
  8214. return $this->_builder=$this->createCommandBuilder();
  8215. }
  8216. public function refresh()
  8217. {
  8218. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8219. {
  8220. foreach(array_keys($this->_tables) as $name)
  8221. {
  8222. if(!isset($this->_cacheExclude[$name]))
  8223. {
  8224. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8225. $cache->delete($key);
  8226. }
  8227. }
  8228. }
  8229. $this->_tables=array();
  8230. $this->_tableNames=array();
  8231. $this->_builder=null;
  8232. }
  8233. public function quoteTableName($name)
  8234. {
  8235. if(strpos($name,'.')===false)
  8236. return $this->quoteSimpleTableName($name);
  8237. $parts=explode('.',$name);
  8238. foreach($parts as $i=>$part)
  8239. $parts[$i]=$this->quoteSimpleTableName($part);
  8240. return implode('.',$parts);
  8241. }
  8242. public function quoteSimpleTableName($name)
  8243. {
  8244. return "'".$name."'";
  8245. }
  8246. public function quoteColumnName($name)
  8247. {
  8248. if(($pos=strrpos($name,'.'))!==false)
  8249. {
  8250. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  8251. $name=substr($name,$pos+1);
  8252. }
  8253. else
  8254. $prefix='';
  8255. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  8256. }
  8257. public function quoteSimpleColumnName($name)
  8258. {
  8259. return '"'.$name.'"';
  8260. }
  8261. public function compareTableNames($name1,$name2)
  8262. {
  8263. $name1=str_replace(array('"','`',"'"),'',$name1);
  8264. $name2=str_replace(array('"','`',"'"),'',$name2);
  8265. if(($pos=strrpos($name1,'.'))!==false)
  8266. $name1=substr($name1,$pos+1);
  8267. if(($pos=strrpos($name2,'.'))!==false)
  8268. $name2=substr($name2,$pos+1);
  8269. if($this->_connection->tablePrefix!==null)
  8270. {
  8271. if(strpos($name1,'{')!==false)
  8272. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  8273. if(strpos($name2,'{')!==false)
  8274. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  8275. }
  8276. return $name1===$name2;
  8277. }
  8278. public function resetSequence($table,$value=null)
  8279. {
  8280. }
  8281. public function checkIntegrity($check=true,$schema='')
  8282. {
  8283. }
  8284. protected function createCommandBuilder()
  8285. {
  8286. return new CDbCommandBuilder($this);
  8287. }
  8288. protected function findTableNames($schema='')
  8289. {
  8290. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  8291. array('{class}'=>get_class($this))));
  8292. }
  8293. public function getColumnType($type)
  8294. {
  8295. if(isset($this->columnTypes[$type]))
  8296. return $this->columnTypes[$type];
  8297. else if(($pos=strpos($type,' '))!==false)
  8298. {
  8299. $t=substr($type,0,$pos);
  8300. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  8301. }
  8302. else
  8303. return $type;
  8304. }
  8305. public function createTable($table, $columns, $options=null)
  8306. {
  8307. $cols=array();
  8308. foreach($columns as $name=>$type)
  8309. {
  8310. if(is_string($name))
  8311. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  8312. else
  8313. $cols[]="\t".$type;
  8314. }
  8315. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  8316. return $options===null ? $sql : $sql.' '.$options;
  8317. }
  8318. public function renameTable($table, $newName)
  8319. {
  8320. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  8321. }
  8322. public function dropTable($table)
  8323. {
  8324. return "DROP TABLE ".$this->quoteTableName($table);
  8325. }
  8326. public function truncateTable($table)
  8327. {
  8328. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  8329. }
  8330. public function addColumn($table, $column, $type)
  8331. {
  8332. return 'ALTER TABLE ' . $this->quoteTableName($table)
  8333. . ' ADD ' . $this->quoteColumnName($column) . ' '
  8334. . $this->getColumnType($type);
  8335. }
  8336. public function dropColumn($table, $column)
  8337. {
  8338. return "ALTER TABLE ".$this->quoteTableName($table)
  8339. ." DROP COLUMN ".$this->quoteColumnName($column);
  8340. }
  8341. public function renameColumn($table, $name, $newName)
  8342. {
  8343. return "ALTER TABLE ".$this->quoteTableName($table)
  8344. . " RENAME COLUMN ".$this->quoteColumnName($name)
  8345. . " TO ".$this->quoteColumnName($newName);
  8346. }
  8347. public function alterColumn($table, $column, $type)
  8348. {
  8349. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  8350. . $this->quoteColumnName($column) . ' '
  8351. . $this->quoteColumnName($column) . ' '
  8352. . $this->getColumnType($type);
  8353. }
  8354. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8355. {
  8356. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  8357. foreach($columns as $i=>$col)
  8358. $columns[$i]=$this->quoteColumnName($col);
  8359. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  8360. foreach($refColumns as $i=>$col)
  8361. $refColumns[$i]=$this->quoteColumnName($col);
  8362. $sql='ALTER TABLE '.$this->quoteTableName($table)
  8363. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  8364. .' FOREIGN KEY ('.implode(', ', $columns).')'
  8365. .' REFERENCES '.$this->quoteTableName($refTable)
  8366. .' ('.implode(', ', $refColumns).')';
  8367. if($delete!==null)
  8368. $sql.=' ON DELETE '.$delete;
  8369. if($update!==null)
  8370. $sql.=' ON UPDATE '.$update;
  8371. return $sql;
  8372. }
  8373. public function dropForeignKey($name, $table)
  8374. {
  8375. return 'ALTER TABLE '.$this->quoteTableName($table)
  8376. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  8377. }
  8378. public function createIndex($name, $table, $column, $unique=false)
  8379. {
  8380. $cols=array();
  8381. $columns=preg_split('/\s*,\s*/',$column,-1,PREG_SPLIT_NO_EMPTY);
  8382. foreach($columns as $col)
  8383. {
  8384. if(strpos($col,'(')!==false)
  8385. $cols[]=$col;
  8386. else
  8387. $cols[]=$this->quoteColumnName($col);
  8388. }
  8389. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  8390. . $this->quoteTableName($name).' ON '
  8391. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  8392. }
  8393. public function dropIndex($name, $table)
  8394. {
  8395. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  8396. }
  8397. }
  8398. class CSqliteSchema extends CDbSchema
  8399. {
  8400. public $columnTypes=array(
  8401. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  8402. 'string' => 'varchar(255)',
  8403. 'text' => 'text',
  8404. 'integer' => 'integer',
  8405. 'float' => 'float',
  8406. 'decimal' => 'decimal',
  8407. 'datetime' => 'datetime',
  8408. 'timestamp' => 'timestamp',
  8409. 'time' => 'time',
  8410. 'date' => 'date',
  8411. 'binary' => 'blob',
  8412. 'boolean' => 'tinyint(1)',
  8413. 'money' => 'decimal(19,4)',
  8414. );
  8415. public function resetSequence($table,$value=null)
  8416. {
  8417. if($table->sequenceName!==null)
  8418. {
  8419. if($value===null)
  8420. $value=$this->getDbConnection()->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")->queryScalar();
  8421. else
  8422. $value=(int)$value-1;
  8423. try
  8424. {
  8425. // it's possible sqlite_sequence does not exist
  8426. $this->getDbConnection()->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")->execute();
  8427. }
  8428. catch(Exception $e)
  8429. {
  8430. }
  8431. }
  8432. }
  8433. public function checkIntegrity($check=true,$schema='')
  8434. {
  8435. // SQLite doesn't enforce integrity
  8436. return;
  8437. }
  8438. protected function findTableNames($schema='')
  8439. {
  8440. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  8441. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  8442. }
  8443. protected function createCommandBuilder()
  8444. {
  8445. return new CSqliteCommandBuilder($this);
  8446. }
  8447. protected function loadTable($name)
  8448. {
  8449. $table=new CDbTableSchema;
  8450. $table->name=$name;
  8451. $table->rawName=$this->quoteTableName($name);
  8452. if($this->findColumns($table))
  8453. {
  8454. $this->findConstraints($table);
  8455. return $table;
  8456. }
  8457. else
  8458. return null;
  8459. }
  8460. protected function findColumns($table)
  8461. {
  8462. $sql="PRAGMA table_info({$table->rawName})";
  8463. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  8464. if(empty($columns))
  8465. return false;
  8466. foreach($columns as $column)
  8467. {
  8468. $c=$this->createColumn($column);
  8469. $table->columns[$c->name]=$c;
  8470. if($c->isPrimaryKey)
  8471. {
  8472. if($table->primaryKey===null)
  8473. $table->primaryKey=$c->name;
  8474. else if(is_string($table->primaryKey))
  8475. $table->primaryKey=array($table->primaryKey,$c->name);
  8476. else
  8477. $table->primaryKey[]=$c->name;
  8478. }
  8479. }
  8480. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  8481. {
  8482. $table->sequenceName='';
  8483. $table->columns[$table->primaryKey]->autoIncrement=true;
  8484. }
  8485. return true;
  8486. }
  8487. protected function findConstraints($table)
  8488. {
  8489. $foreignKeys=array();
  8490. $sql="PRAGMA foreign_key_list({$table->rawName})";
  8491. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  8492. foreach($keys as $key)
  8493. {
  8494. $column=$table->columns[$key['from']];
  8495. $column->isForeignKey=true;
  8496. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  8497. }
  8498. $table->foreignKeys=$foreignKeys;
  8499. }
  8500. protected function createColumn($column)
  8501. {
  8502. $c=new CSqliteColumnSchema;
  8503. $c->name=$column['name'];
  8504. $c->rawName=$this->quoteColumnName($c->name);
  8505. $c->allowNull=!$column['notnull'];
  8506. $c->isPrimaryKey=$column['pk']!=0;
  8507. $c->isForeignKey=false;
  8508. $c->init(strtolower($column['type']),$column['dflt_value']);
  8509. return $c;
  8510. }
  8511. public function truncateTable($table)
  8512. {
  8513. return "DELETE FROM ".$this->quoteTableName($table);
  8514. }
  8515. public function dropColumn($table, $column)
  8516. {
  8517. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  8518. }
  8519. public function renameColumn($table, $name, $newName)
  8520. {
  8521. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  8522. }
  8523. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8524. {
  8525. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  8526. }
  8527. public function dropForeignKey($name, $table)
  8528. {
  8529. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  8530. }
  8531. public function alterColumn($table, $column, $type)
  8532. {
  8533. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  8534. }
  8535. public function dropIndex($name, $table)
  8536. {
  8537. return 'DROP INDEX '.$this->quoteTableName($name);
  8538. }
  8539. }
  8540. class CDbTableSchema extends CComponent
  8541. {
  8542. public $name;
  8543. public $rawName;
  8544. public $primaryKey;
  8545. public $sequenceName;
  8546. public $foreignKeys=array();
  8547. public $columns=array();
  8548. public function getColumn($name)
  8549. {
  8550. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  8551. }
  8552. public function getColumnNames()
  8553. {
  8554. return array_keys($this->columns);
  8555. }
  8556. }
  8557. class CDbCommand extends CComponent
  8558. {
  8559. public $params=array();
  8560. private $_connection;
  8561. private $_text;
  8562. private $_statement;
  8563. private $_paramLog=array();
  8564. private $_query;
  8565. private $_fetchMode = array(PDO::FETCH_ASSOC);
  8566. public function __construct(CDbConnection $connection,$query=null)
  8567. {
  8568. $this->_connection=$connection;
  8569. if(is_array($query))
  8570. {
  8571. foreach($query as $name=>$value)
  8572. $this->$name=$value;
  8573. }
  8574. else
  8575. $this->setText($query);
  8576. }
  8577. public function __sleep()
  8578. {
  8579. $this->_statement=null;
  8580. return array_keys(get_object_vars($this));
  8581. }
  8582. public function setFetchMode($mode)
  8583. {
  8584. $params=func_get_args();
  8585. $this->_fetchMode = $params;
  8586. return $this;
  8587. }
  8588. public function reset()
  8589. {
  8590. $this->_text=null;
  8591. $this->_query=null;
  8592. $this->_statement=null;
  8593. $this->_paramLog=array();
  8594. $this->params=array();
  8595. return $this;
  8596. }
  8597. public function getText()
  8598. {
  8599. if($this->_text=='' && !empty($this->_query))
  8600. $this->setText($this->buildQuery($this->_query));
  8601. return $this->_text;
  8602. }
  8603. public function setText($value)
  8604. {
  8605. if($this->_connection->tablePrefix!==null && $value!='')
  8606. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  8607. else
  8608. $this->_text=$value;
  8609. $this->cancel();
  8610. return $this;
  8611. }
  8612. public function getConnection()
  8613. {
  8614. return $this->_connection;
  8615. }
  8616. public function getPdoStatement()
  8617. {
  8618. return $this->_statement;
  8619. }
  8620. public function prepare()
  8621. {
  8622. if($this->_statement==null)
  8623. {
  8624. try
  8625. {
  8626. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  8627. $this->_paramLog=array();
  8628. }
  8629. catch(Exception $e)
  8630. {
  8631. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8632. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8633. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  8634. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  8635. }
  8636. }
  8637. }
  8638. public function cancel()
  8639. {
  8640. $this->_statement=null;
  8641. }
  8642. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  8643. {
  8644. $this->prepare();
  8645. if($dataType===null)
  8646. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  8647. else if($length===null)
  8648. $this->_statement->bindParam($name,$value,$dataType);
  8649. else if($driverOptions===null)
  8650. $this->_statement->bindParam($name,$value,$dataType,$length);
  8651. else
  8652. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  8653. $this->_paramLog[$name]=&$value;
  8654. return $this;
  8655. }
  8656. public function bindValue($name, $value, $dataType=null)
  8657. {
  8658. $this->prepare();
  8659. if($dataType===null)
  8660. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8661. else
  8662. $this->_statement->bindValue($name,$value,$dataType);
  8663. $this->_paramLog[$name]=$value;
  8664. return $this;
  8665. }
  8666. public function bindValues($values)
  8667. {
  8668. $this->prepare();
  8669. foreach($values as $name=>$value)
  8670. {
  8671. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8672. $this->_paramLog[$name]=$value;
  8673. }
  8674. return $this;
  8675. }
  8676. public function execute($params=array())
  8677. {
  8678. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8679. {
  8680. $p=array();
  8681. foreach($pars as $name=>$value)
  8682. $p[$name]=$name.'='.var_export($value,true);
  8683. $par='. Bound with ' .implode(', ',$p);
  8684. }
  8685. else
  8686. $par='';
  8687. try
  8688. {
  8689. if($this->_connection->enableProfiling)
  8690. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  8691. $this->prepare();
  8692. if($params===array())
  8693. $this->_statement->execute();
  8694. else
  8695. $this->_statement->execute($params);
  8696. $n=$this->_statement->rowCount();
  8697. if($this->_connection->enableProfiling)
  8698. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  8699. return $n;
  8700. }
  8701. catch(Exception $e)
  8702. {
  8703. if($this->_connection->enableProfiling)
  8704. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  8705. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8706. $message = $e->getMessage();
  8707. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  8708. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8709. if(YII_DEBUG)
  8710. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  8711. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8712. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8713. }
  8714. }
  8715. public function query($params=array())
  8716. {
  8717. return $this->queryInternal('',0,$params);
  8718. }
  8719. public function queryAll($fetchAssociative=true,$params=array())
  8720. {
  8721. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8722. }
  8723. public function queryRow($fetchAssociative=true,$params=array())
  8724. {
  8725. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8726. }
  8727. public function queryScalar($params=array())
  8728. {
  8729. $result=$this->queryInternal('fetchColumn',0,$params);
  8730. if(is_resource($result) && get_resource_type($result)==='stream')
  8731. return stream_get_contents($result);
  8732. else
  8733. return $result;
  8734. }
  8735. public function queryColumn($params=array())
  8736. {
  8737. return $this->queryInternal('fetchAll',PDO::FETCH_COLUMN,$params);
  8738. }
  8739. private function queryInternal($method,$mode,$params=array())
  8740. {
  8741. $params=array_merge($this->params,$params);
  8742. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8743. {
  8744. $p=array();
  8745. foreach($pars as $name=>$value)
  8746. $p[$name]=$name.'='.var_export($value,true);
  8747. $par='. Bound with '.implode(', ',$p);
  8748. }
  8749. else
  8750. $par='';
  8751. if($this->_connection->queryCachingCount>0 && $method!==''
  8752. && $this->_connection->queryCachingDuration>0
  8753. && $this->_connection->queryCacheID!==false
  8754. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  8755. {
  8756. $this->_connection->queryCachingCount--;
  8757. $cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
  8758. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  8759. if(($result=$cache->get($cacheKey))!==false)
  8760. {
  8761. return $result;
  8762. }
  8763. }
  8764. try
  8765. {
  8766. if($this->_connection->enableProfiling)
  8767. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8768. $this->prepare();
  8769. if($params===array())
  8770. $this->_statement->execute();
  8771. else
  8772. $this->_statement->execute($params);
  8773. if($method==='')
  8774. $result=new CDbDataReader($this);
  8775. else
  8776. {
  8777. $mode=(array)$mode;
  8778. $result=call_user_func_array(array($this->_statement, $method), $mode);
  8779. $this->_statement->closeCursor();
  8780. }
  8781. if($this->_connection->enableProfiling)
  8782. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8783. if(isset($cache,$cacheKey))
  8784. $cache->set($cacheKey, $result, $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  8785. return $result;
  8786. }
  8787. catch(Exception $e)
  8788. {
  8789. if($this->_connection->enableProfiling)
  8790. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8791. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8792. $message = $e->getMessage();
  8793. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  8794. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8795. if(YII_DEBUG)
  8796. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  8797. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8798. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8799. }
  8800. }
  8801. public function buildQuery($query)
  8802. {
  8803. $sql=!empty($query['distinct']) ? 'SELECT DISTINCT' : 'SELECT';
  8804. $sql.=' '.(!empty($query['select']) ? $query['select'] : '*');
  8805. if(!empty($query['from']))
  8806. $sql.="\nFROM ".$query['from'];
  8807. else
  8808. throw new CDbException(Yii::t('yii','The DB query must contain the "from" portion.'));
  8809. if(!empty($query['join']))
  8810. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  8811. if(!empty($query['where']))
  8812. $sql.="\nWHERE ".$query['where'];
  8813. if(!empty($query['group']))
  8814. $sql.="\nGROUP BY ".$query['group'];
  8815. if(!empty($query['having']))
  8816. $sql.="\nHAVING ".$query['having'];
  8817. if(!empty($query['order']))
  8818. $sql.="\nORDER BY ".$query['order'];
  8819. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  8820. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  8821. if($limit>=0 || $offset>0)
  8822. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  8823. if(!empty($query['union']))
  8824. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  8825. return $sql;
  8826. }
  8827. public function select($columns='*', $option='')
  8828. {
  8829. if(is_string($columns) && strpos($columns,'(')!==false)
  8830. $this->_query['select']=$columns;
  8831. else
  8832. {
  8833. if(!is_array($columns))
  8834. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8835. foreach($columns as $i=>$column)
  8836. {
  8837. if(is_object($column))
  8838. $columns[$i]=(string)$column;
  8839. else if(strpos($column,'(')===false)
  8840. {
  8841. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  8842. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  8843. else
  8844. $columns[$i]=$this->_connection->quoteColumnName($column);
  8845. }
  8846. }
  8847. $this->_query['select']=implode(', ',$columns);
  8848. }
  8849. if($option!='')
  8850. $this->_query['select']=$option.' '.$this->_query['select'];
  8851. return $this;
  8852. }
  8853. public function getSelect()
  8854. {
  8855. return isset($this->_query['select']) ? $this->_query['select'] : '';
  8856. }
  8857. public function setSelect($value)
  8858. {
  8859. $this->select($value);
  8860. }
  8861. public function selectDistinct($columns='*')
  8862. {
  8863. $this->_query['distinct']=true;
  8864. return $this->select($columns);
  8865. }
  8866. public function getDistinct()
  8867. {
  8868. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  8869. }
  8870. public function setDistinct($value)
  8871. {
  8872. $this->_query['distinct']=$value;
  8873. }
  8874. public function from($tables)
  8875. {
  8876. if(is_string($tables) && strpos($tables,'(')!==false)
  8877. $this->_query['from']=$tables;
  8878. else
  8879. {
  8880. if(!is_array($tables))
  8881. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  8882. foreach($tables as $i=>$table)
  8883. {
  8884. if(strpos($table,'(')===false)
  8885. {
  8886. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  8887. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  8888. else
  8889. $tables[$i]=$this->_connection->quoteTableName($table);
  8890. }
  8891. }
  8892. $this->_query['from']=implode(', ',$tables);
  8893. }
  8894. return $this;
  8895. }
  8896. public function getFrom()
  8897. {
  8898. return isset($this->_query['from']) ? $this->_query['from'] : '';
  8899. }
  8900. public function setFrom($value)
  8901. {
  8902. $this->from($value);
  8903. }
  8904. public function where($conditions, $params=array())
  8905. {
  8906. $this->_query['where']=$this->processConditions($conditions);
  8907. foreach($params as $name=>$value)
  8908. $this->params[$name]=$value;
  8909. return $this;
  8910. }
  8911. public function getWhere()
  8912. {
  8913. return isset($this->_query['where']) ? $this->_query['where'] : '';
  8914. }
  8915. public function setWhere($value)
  8916. {
  8917. $this->where($value);
  8918. }
  8919. public function join($table, $conditions, $params=array())
  8920. {
  8921. return $this->joinInternal('join', $table, $conditions, $params);
  8922. }
  8923. public function getJoin()
  8924. {
  8925. return isset($this->_query['join']) ? $this->_query['join'] : '';
  8926. }
  8927. public function setJoin($value)
  8928. {
  8929. $this->_query['join']=$value;
  8930. }
  8931. public function leftJoin($table, $conditions, $params=array())
  8932. {
  8933. return $this->joinInternal('left join', $table, $conditions, $params);
  8934. }
  8935. public function rightJoin($table, $conditions, $params=array())
  8936. {
  8937. return $this->joinInternal('right join', $table, $conditions, $params);
  8938. }
  8939. public function crossJoin($table)
  8940. {
  8941. return $this->joinInternal('cross join', $table);
  8942. }
  8943. public function naturalJoin($table)
  8944. {
  8945. return $this->joinInternal('natural join', $table);
  8946. }
  8947. public function group($columns)
  8948. {
  8949. if(is_string($columns) && strpos($columns,'(')!==false)
  8950. $this->_query['group']=$columns;
  8951. else
  8952. {
  8953. if(!is_array($columns))
  8954. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8955. foreach($columns as $i=>$column)
  8956. {
  8957. if(is_object($column))
  8958. $columns[$i]=(string)$column;
  8959. else if(strpos($column,'(')===false)
  8960. $columns[$i]=$this->_connection->quoteColumnName($column);
  8961. }
  8962. $this->_query['group']=implode(', ',$columns);
  8963. }
  8964. return $this;
  8965. }
  8966. public function getGroup()
  8967. {
  8968. return isset($this->_query['group']) ? $this->_query['group'] : '';
  8969. }
  8970. public function setGroup($value)
  8971. {
  8972. $this->group($value);
  8973. }
  8974. public function having($conditions, $params=array())
  8975. {
  8976. $this->_query['having']=$this->processConditions($conditions);
  8977. foreach($params as $name=>$value)
  8978. $this->params[$name]=$value;
  8979. return $this;
  8980. }
  8981. public function getHaving()
  8982. {
  8983. return isset($this->_query['having']) ? $this->_query['having'] : '';
  8984. }
  8985. public function setHaving($value)
  8986. {
  8987. $this->having($value);
  8988. }
  8989. public function order($columns)
  8990. {
  8991. if(is_string($columns) && strpos($columns,'(')!==false)
  8992. $this->_query['order']=$columns;
  8993. else
  8994. {
  8995. if(!is_array($columns))
  8996. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8997. foreach($columns as $i=>$column)
  8998. {
  8999. if(is_object($column))
  9000. $columns[$i]=(string)$column;
  9001. else if(strpos($column,'(')===false)
  9002. {
  9003. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  9004. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  9005. else
  9006. $columns[$i]=$this->_connection->quoteColumnName($column);
  9007. }
  9008. }
  9009. $this->_query['order']=implode(', ',$columns);
  9010. }
  9011. return $this;
  9012. }
  9013. public function getOrder()
  9014. {
  9015. return isset($this->_query['order']) ? $this->_query['order'] : '';
  9016. }
  9017. public function setOrder($value)
  9018. {
  9019. $this->order($value);
  9020. }
  9021. public function limit($limit, $offset=null)
  9022. {
  9023. $this->_query['limit']=(int)$limit;
  9024. if($offset!==null)
  9025. $this->offset($offset);
  9026. return $this;
  9027. }
  9028. public function getLimit()
  9029. {
  9030. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  9031. }
  9032. public function setLimit($value)
  9033. {
  9034. $this->limit($value);
  9035. }
  9036. public function offset($offset)
  9037. {
  9038. $this->_query['offset']=(int)$offset;
  9039. return $this;
  9040. }
  9041. public function getOffset()
  9042. {
  9043. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  9044. }
  9045. public function setOffset($value)
  9046. {
  9047. $this->offset($value);
  9048. }
  9049. public function union($sql)
  9050. {
  9051. if(isset($this->_query['union']) && is_string($this->_query['union']))
  9052. $this->_query['union']=array($this->_query['union']);
  9053. $this->_query['union'][]=$sql;
  9054. return $this;
  9055. }
  9056. public function getUnion()
  9057. {
  9058. return isset($this->_query['union']) ? $this->_query['union'] : '';
  9059. }
  9060. public function setUnion($value)
  9061. {
  9062. $this->_query['union']=$value;
  9063. }
  9064. public function insert($table, $columns)
  9065. {
  9066. $params=array();
  9067. $names=array();
  9068. $placeholders=array();
  9069. foreach($columns as $name=>$value)
  9070. {
  9071. $names[]=$this->_connection->quoteColumnName($name);
  9072. if($value instanceof CDbExpression)
  9073. {
  9074. $placeholders[] = $value->expression;
  9075. foreach($value->params as $n => $v)
  9076. $params[$n] = $v;
  9077. }
  9078. else
  9079. {
  9080. $placeholders[] = ':' . $name;
  9081. $params[':' . $name] = $value;
  9082. }
  9083. }
  9084. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  9085. . ' (' . implode(', ',$names) . ') VALUES ('
  9086. . implode(', ', $placeholders) . ')';
  9087. return $this->setText($sql)->execute($params);
  9088. }
  9089. public function update($table, $columns, $conditions='', $params=array())
  9090. {
  9091. $lines=array();
  9092. foreach($columns as $name=>$value)
  9093. {
  9094. if($value instanceof CDbExpression)
  9095. {
  9096. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  9097. foreach($value->params as $n => $v)
  9098. $params[$n] = $v;
  9099. }
  9100. else
  9101. {
  9102. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  9103. $params[':' . $name]=$value;
  9104. }
  9105. }
  9106. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  9107. if(($where=$this->processConditions($conditions))!='')
  9108. $sql.=' WHERE '.$where;
  9109. return $this->setText($sql)->execute($params);
  9110. }
  9111. public function delete($table, $conditions='', $params=array())
  9112. {
  9113. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  9114. if(($where=$this->processConditions($conditions))!='')
  9115. $sql.=' WHERE '.$where;
  9116. return $this->setText($sql)->execute($params);
  9117. }
  9118. public function createTable($table, $columns, $options=null)
  9119. {
  9120. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  9121. }
  9122. public function renameTable($table, $newName)
  9123. {
  9124. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  9125. }
  9126. public function dropTable($table)
  9127. {
  9128. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  9129. }
  9130. public function truncateTable($table)
  9131. {
  9132. $schema=$this->getConnection()->getSchema();
  9133. $n=$this->setText($schema->truncateTable($table))->execute();
  9134. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  9135. $schema->resetSequence($schema->getTable($table));
  9136. return $n;
  9137. }
  9138. public function addColumn($table, $column, $type)
  9139. {
  9140. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  9141. }
  9142. public function dropColumn($table, $column)
  9143. {
  9144. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  9145. }
  9146. public function renameColumn($table, $name, $newName)
  9147. {
  9148. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  9149. }
  9150. public function alterColumn($table, $column, $type)
  9151. {
  9152. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  9153. }
  9154. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9155. {
  9156. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  9157. }
  9158. public function dropForeignKey($name, $table)
  9159. {
  9160. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  9161. }
  9162. public function createIndex($name, $table, $column, $unique=false)
  9163. {
  9164. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $column, $unique))->execute();
  9165. }
  9166. public function dropIndex($name, $table)
  9167. {
  9168. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  9169. }
  9170. private function processConditions($conditions)
  9171. {
  9172. if(!is_array($conditions))
  9173. return $conditions;
  9174. else if($conditions===array())
  9175. return '';
  9176. $n=count($conditions);
  9177. $operator=strtoupper($conditions[0]);
  9178. if($operator==='OR' || $operator==='AND')
  9179. {
  9180. $parts=array();
  9181. for($i=1;$i<$n;++$i)
  9182. {
  9183. $condition=$this->processConditions($conditions[$i]);
  9184. if($condition!=='')
  9185. $parts[]='('.$condition.')';
  9186. }
  9187. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  9188. }
  9189. if(!isset($conditions[1],$conditions[2]))
  9190. return '';
  9191. $column=$conditions[1];
  9192. if(strpos($column,'(')===false)
  9193. $column=$this->_connection->quoteColumnName($column);
  9194. $values=$conditions[2];
  9195. if(!is_array($values))
  9196. $values=array($values);
  9197. if($operator==='IN' || $operator==='NOT IN')
  9198. {
  9199. if($values===array())
  9200. return $operator==='IN' ? '0=1' : '';
  9201. foreach($values as $i=>$value)
  9202. {
  9203. if(is_string($value))
  9204. $values[$i]=$this->_connection->quoteValue($value);
  9205. else
  9206. $values[$i]=(string)$value;
  9207. }
  9208. return $column.' '.$operator.' ('.implode(', ',$values).')';
  9209. }
  9210. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  9211. {
  9212. if($values===array())
  9213. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  9214. if($operator==='LIKE' || $operator==='NOT LIKE')
  9215. $andor=' AND ';
  9216. else
  9217. {
  9218. $andor=' OR ';
  9219. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  9220. }
  9221. $expressions=array();
  9222. foreach($values as $value)
  9223. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  9224. return implode($andor,$expressions);
  9225. }
  9226. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  9227. }
  9228. private function joinInternal($type, $table, $conditions='', $params=array())
  9229. {
  9230. if(strpos($table,'(')===false)
  9231. {
  9232. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9233. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9234. else
  9235. $table=$this->_connection->quoteTableName($table);
  9236. }
  9237. $conditions=$this->processConditions($conditions);
  9238. if($conditions!='')
  9239. $conditions=' ON '.$conditions;
  9240. if(isset($this->_query['join']) && is_string($this->_query['join']))
  9241. $this->_query['join']=array($this->_query['join']);
  9242. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  9243. foreach($params as $name=>$value)
  9244. $this->params[$name]=$value;
  9245. return $this;
  9246. }
  9247. }
  9248. class CDbColumnSchema extends CComponent
  9249. {
  9250. public $name;
  9251. public $rawName;
  9252. public $allowNull;
  9253. public $dbType;
  9254. public $type;
  9255. public $defaultValue;
  9256. public $size;
  9257. public $precision;
  9258. public $scale;
  9259. public $isPrimaryKey;
  9260. public $isForeignKey;
  9261. public $autoIncrement=false;
  9262. public function init($dbType, $defaultValue)
  9263. {
  9264. $this->dbType=$dbType;
  9265. $this->extractType($dbType);
  9266. $this->extractLimit($dbType);
  9267. if($defaultValue!==null)
  9268. $this->extractDefault($defaultValue);
  9269. }
  9270. protected function extractType($dbType)
  9271. {
  9272. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  9273. $this->type='integer';
  9274. else if(stripos($dbType,'bool')!==false)
  9275. $this->type='boolean';
  9276. else if(preg_match('/(real|floa|doub)/i',$dbType))
  9277. $this->type='double';
  9278. else
  9279. $this->type='string';
  9280. }
  9281. protected function extractLimit($dbType)
  9282. {
  9283. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  9284. {
  9285. $values=explode(',',$matches[1]);
  9286. $this->size=$this->precision=(int)$values[0];
  9287. if(isset($values[1]))
  9288. $this->scale=(int)$values[1];
  9289. }
  9290. }
  9291. protected function extractDefault($defaultValue)
  9292. {
  9293. $this->defaultValue=$this->typecast($defaultValue);
  9294. }
  9295. public function typecast($value)
  9296. {
  9297. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  9298. return $value;
  9299. if($value==='' && $this->allowNull)
  9300. return $this->type==='string' ? '' : null;
  9301. switch($this->type)
  9302. {
  9303. case 'string': return (string)$value;
  9304. case 'integer': return (integer)$value;
  9305. case 'boolean': return (boolean)$value;
  9306. case 'double':
  9307. default: return $value;
  9308. }
  9309. }
  9310. }
  9311. class CSqliteColumnSchema extends CDbColumnSchema
  9312. {
  9313. protected function extractDefault($defaultValue)
  9314. {
  9315. if($this->type==='string') // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  9316. $this->defaultValue=trim($defaultValue,"'\"");
  9317. else
  9318. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  9319. }
  9320. }
  9321. abstract class CValidator extends CComponent
  9322. {
  9323. public static $builtInValidators=array(
  9324. 'required'=>'CRequiredValidator',
  9325. 'filter'=>'CFilterValidator',
  9326. 'match'=>'CRegularExpressionValidator',
  9327. 'email'=>'CEmailValidator',
  9328. 'url'=>'CUrlValidator',
  9329. 'unique'=>'CUniqueValidator',
  9330. 'compare'=>'CCompareValidator',
  9331. 'length'=>'CStringValidator',
  9332. 'in'=>'CRangeValidator',
  9333. 'numerical'=>'CNumberValidator',
  9334. 'captcha'=>'CCaptchaValidator',
  9335. 'type'=>'CTypeValidator',
  9336. 'file'=>'CFileValidator',
  9337. 'default'=>'CDefaultValueValidator',
  9338. 'exist'=>'CExistValidator',
  9339. 'boolean'=>'CBooleanValidator',
  9340. 'safe'=>'CSafeValidator',
  9341. 'unsafe'=>'CUnsafeValidator',
  9342. 'date'=>'CDateValidator',
  9343. );
  9344. public $attributes;
  9345. public $message;
  9346. public $skipOnError=false;
  9347. public $on;
  9348. public $except;
  9349. public $safe=true;
  9350. public $enableClientValidation=true;
  9351. abstract protected function validateAttribute($object,$attribute);
  9352. public static function createValidator($name,$object,$attributes,$params=array())
  9353. {
  9354. if(is_string($attributes))
  9355. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  9356. if(isset($params['on']))
  9357. {
  9358. if(is_array($params['on']))
  9359. $on=$params['on'];
  9360. else
  9361. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  9362. }
  9363. else
  9364. $on=array();
  9365. if(isset($params['except']))
  9366. {
  9367. if(is_array($params['except']))
  9368. $except=$params['except'];
  9369. else
  9370. $except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
  9371. }
  9372. else
  9373. $except=array();
  9374. if(method_exists($object,$name))
  9375. {
  9376. $validator=new CInlineValidator;
  9377. $validator->attributes=$attributes;
  9378. $validator->method=$name;
  9379. if(isset($params['clientValidate']))
  9380. {
  9381. $validator->clientValidate=$params['clientValidate'];
  9382. unset($params['clientValidate']);
  9383. }
  9384. $validator->params=$params;
  9385. if(isset($params['skipOnError']))
  9386. $validator->skipOnError=$params['skipOnError'];
  9387. }
  9388. else
  9389. {
  9390. $params['attributes']=$attributes;
  9391. if(isset(self::$builtInValidators[$name]))
  9392. $className=Yii::import(self::$builtInValidators[$name],true);
  9393. else
  9394. $className=Yii::import($name,true);
  9395. $validator=new $className;
  9396. foreach($params as $name=>$value)
  9397. $validator->$name=$value;
  9398. }
  9399. $validator->on=empty($on) ? array() : array_combine($on,$on);
  9400. $validator->except=empty($except) ? array() : array_combine($except,$except);
  9401. return $validator;
  9402. }
  9403. public function validate($object,$attributes=null)
  9404. {
  9405. if(is_array($attributes))
  9406. $attributes=array_intersect($this->attributes,$attributes);
  9407. else
  9408. $attributes=$this->attributes;
  9409. foreach($attributes as $attribute)
  9410. {
  9411. if(!$this->skipOnError || !$object->hasErrors($attribute))
  9412. $this->validateAttribute($object,$attribute);
  9413. }
  9414. }
  9415. public function clientValidateAttribute($object,$attribute)
  9416. {
  9417. }
  9418. public function applyTo($scenario)
  9419. {
  9420. if(isset($this->except[$scenario]))
  9421. return false;
  9422. return empty($this->on) || isset($this->on[$scenario]);
  9423. }
  9424. protected function addError($object,$attribute,$message,$params=array())
  9425. {
  9426. $params['{attribute}']=$object->getAttributeLabel($attribute);
  9427. $object->addError($attribute,strtr($message,$params));
  9428. }
  9429. protected function isEmpty($value,$trim=false)
  9430. {
  9431. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  9432. }
  9433. }
  9434. class CStringValidator extends CValidator
  9435. {
  9436. public $max;
  9437. public $min;
  9438. public $is;
  9439. public $tooShort;
  9440. public $tooLong;
  9441. public $allowEmpty=true;
  9442. public $encoding;
  9443. protected function validateAttribute($object,$attribute)
  9444. {
  9445. $value=$object->$attribute;
  9446. if($this->allowEmpty && $this->isEmpty($value))
  9447. return;
  9448. if(function_exists('mb_strlen') && $this->encoding!==false)
  9449. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  9450. else
  9451. $length=strlen($value);
  9452. if($this->min!==null && $length<$this->min)
  9453. {
  9454. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9455. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9456. }
  9457. if($this->max!==null && $length>$this->max)
  9458. {
  9459. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9460. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9461. }
  9462. if($this->is!==null && $length!==$this->is)
  9463. {
  9464. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9465. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  9466. }
  9467. }
  9468. public function clientValidateAttribute($object,$attribute)
  9469. {
  9470. $label=$object->getAttributeLabel($attribute);
  9471. if(($message=$this->message)===null)
  9472. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9473. $message=strtr($message, array(
  9474. '{attribute}'=>$label,
  9475. '{length}'=>$this->is,
  9476. ));
  9477. if(($tooShort=$this->tooShort)===null)
  9478. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9479. $tooShort=strtr($tooShort, array(
  9480. '{attribute}'=>$label,
  9481. '{min}'=>$this->min,
  9482. ));
  9483. if(($tooLong=$this->tooLong)===null)
  9484. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9485. $tooLong=strtr($tooLong, array(
  9486. '{attribute}'=>$label,
  9487. '{max}'=>$this->max,
  9488. ));
  9489. $js='';
  9490. if($this->min!==null)
  9491. {
  9492. $js.="
  9493. if(value.length<{$this->min}) {
  9494. messages.push(".CJSON::encode($tooShort).");
  9495. }
  9496. ";
  9497. }
  9498. if($this->max!==null)
  9499. {
  9500. $js.="
  9501. if(value.length>{$this->max}) {
  9502. messages.push(".CJSON::encode($tooLong).");
  9503. }
  9504. ";
  9505. }
  9506. if($this->is!==null)
  9507. {
  9508. $js.="
  9509. if(value.length!={$this->is}) {
  9510. messages.push(".CJSON::encode($message).");
  9511. }
  9512. ";
  9513. }
  9514. if($this->allowEmpty)
  9515. {
  9516. $js="
  9517. if($.trim(value)!='') {
  9518. $js
  9519. }
  9520. ";
  9521. }
  9522. return $js;
  9523. }
  9524. }
  9525. class CRequiredValidator extends CValidator
  9526. {
  9527. public $requiredValue;
  9528. public $strict=false;
  9529. protected function validateAttribute($object,$attribute)
  9530. {
  9531. $value=$object->$attribute;
  9532. if($this->requiredValue!==null)
  9533. {
  9534. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  9535. {
  9536. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  9537. array('{value}'=>$this->requiredValue));
  9538. $this->addError($object,$attribute,$message);
  9539. }
  9540. }
  9541. else if($this->isEmpty($value,true))
  9542. {
  9543. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  9544. $this->addError($object,$attribute,$message);
  9545. }
  9546. }
  9547. public function clientValidateAttribute($object,$attribute)
  9548. {
  9549. $message=$this->message;
  9550. if($this->requiredValue!==null)
  9551. {
  9552. if($message===null)
  9553. $message=Yii::t('yii','{attribute} must be {value}.');
  9554. $message=strtr($message, array(
  9555. '{value}'=>$this->requiredValue,
  9556. '{attribute}'=>$object->getAttributeLabel($attribute),
  9557. ));
  9558. return "
  9559. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  9560. messages.push(".CJSON::encode($message).");
  9561. }
  9562. ";
  9563. }
  9564. else
  9565. {
  9566. if($message===null)
  9567. $message=Yii::t('yii','{attribute} cannot be blank.');
  9568. $message=strtr($message, array(
  9569. '{attribute}'=>$object->getAttributeLabel($attribute),
  9570. ));
  9571. return "
  9572. if($.trim(value)=='') {
  9573. messages.push(".CJSON::encode($message).");
  9574. }
  9575. ";
  9576. }
  9577. }
  9578. }
  9579. class CNumberValidator extends CValidator
  9580. {
  9581. public $integerOnly=false;
  9582. public $allowEmpty=true;
  9583. public $max;
  9584. public $min;
  9585. public $tooBig;
  9586. public $tooSmall;
  9587. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  9588. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  9589. protected function validateAttribute($object,$attribute)
  9590. {
  9591. $value=$object->$attribute;
  9592. if($this->allowEmpty && $this->isEmpty($value))
  9593. return;
  9594. if($this->integerOnly)
  9595. {
  9596. if(!preg_match($this->integerPattern,"$value"))
  9597. {
  9598. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  9599. $this->addError($object,$attribute,$message);
  9600. }
  9601. }
  9602. else
  9603. {
  9604. if(!preg_match($this->numberPattern,"$value"))
  9605. {
  9606. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  9607. $this->addError($object,$attribute,$message);
  9608. }
  9609. }
  9610. if($this->min!==null && $value<$this->min)
  9611. {
  9612. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9613. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9614. }
  9615. if($this->max!==null && $value>$this->max)
  9616. {
  9617. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9618. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9619. }
  9620. }
  9621. public function clientValidateAttribute($object,$attribute)
  9622. {
  9623. $label=$object->getAttributeLabel($attribute);
  9624. if(($message=$this->message)===null)
  9625. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  9626. $message=strtr($message, array(
  9627. '{attribute}'=>$label,
  9628. ));
  9629. if(($tooBig=$this->tooBig)===null)
  9630. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9631. $tooBig=strtr($tooBig, array(
  9632. '{attribute}'=>$label,
  9633. '{max}'=>$this->max,
  9634. ));
  9635. if(($tooSmall=$this->tooSmall)===null)
  9636. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9637. $tooSmall=strtr($tooSmall, array(
  9638. '{attribute}'=>$label,
  9639. '{min}'=>$this->min,
  9640. ));
  9641. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  9642. $js="
  9643. if(!value.match($pattern)) {
  9644. messages.push(".CJSON::encode($message).");
  9645. }
  9646. ";
  9647. if($this->min!==null)
  9648. {
  9649. $js.="
  9650. if(value<{$this->min}) {
  9651. messages.push(".CJSON::encode($tooSmall).");
  9652. }
  9653. ";
  9654. }
  9655. if($this->max!==null)
  9656. {
  9657. $js.="
  9658. if(value>{$this->max}) {
  9659. messages.push(".CJSON::encode($tooBig).");
  9660. }
  9661. ";
  9662. }
  9663. if($this->allowEmpty)
  9664. {
  9665. $js="
  9666. if($.trim(value)!='') {
  9667. $js
  9668. }
  9669. ";
  9670. }
  9671. return $js;
  9672. }
  9673. }
  9674. class CListIterator implements Iterator
  9675. {
  9676. private $_d;
  9677. private $_i;
  9678. private $_c;
  9679. public function __construct(&$data)
  9680. {
  9681. $this->_d=&$data;
  9682. $this->_i=0;
  9683. $this->_c=count($this->_d);
  9684. }
  9685. public function rewind()
  9686. {
  9687. $this->_i=0;
  9688. }
  9689. public function key()
  9690. {
  9691. return $this->_i;
  9692. }
  9693. public function current()
  9694. {
  9695. return $this->_d[$this->_i];
  9696. }
  9697. public function next()
  9698. {
  9699. $this->_i++;
  9700. }
  9701. public function valid()
  9702. {
  9703. return $this->_i<$this->_c;
  9704. }
  9705. }
  9706. interface IApplicationComponent
  9707. {
  9708. public function init();
  9709. public function getIsInitialized();
  9710. }
  9711. interface ICache
  9712. {
  9713. public function get($id);
  9714. public function mget($ids);
  9715. public function set($id,$value,$expire=0,$dependency=null);
  9716. public function add($id,$value,$expire=0,$dependency=null);
  9717. public function delete($id);
  9718. public function flush();
  9719. }
  9720. interface ICacheDependency
  9721. {
  9722. public function evaluateDependency();
  9723. public function getHasChanged();
  9724. }
  9725. interface IStatePersister
  9726. {
  9727. public function load();
  9728. public function save($state);
  9729. }
  9730. interface IFilter
  9731. {
  9732. public function filter($filterChain);
  9733. }
  9734. interface IAction
  9735. {
  9736. public function getId();
  9737. public function getController();
  9738. }
  9739. interface IWebServiceProvider
  9740. {
  9741. public function beforeWebMethod($service);
  9742. public function afterWebMethod($service);
  9743. }
  9744. interface IViewRenderer
  9745. {
  9746. public function renderFile($context,$file,$data,$return);
  9747. }
  9748. interface IUserIdentity
  9749. {
  9750. public function authenticate();
  9751. public function getIsAuthenticated();
  9752. public function getId();
  9753. public function getName();
  9754. public function getPersistentStates();
  9755. }
  9756. interface IWebUser
  9757. {
  9758. public function getId();
  9759. public function getName();
  9760. public function getIsGuest();
  9761. public function checkAccess($operation,$params=array());
  9762. public function loginRequired();
  9763. }
  9764. interface IAuthManager
  9765. {
  9766. public function checkAccess($itemName,$userId,$params=array());
  9767. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  9768. public function removeAuthItem($name);
  9769. public function getAuthItems($type=null,$userId=null);
  9770. public function getAuthItem($name);
  9771. public function saveAuthItem($item,$oldName=null);
  9772. public function addItemChild($itemName,$childName);
  9773. public function removeItemChild($itemName,$childName);
  9774. public function hasItemChild($itemName,$childName);
  9775. public function getItemChildren($itemName);
  9776. public function assign($itemName,$userId,$bizRule=null,$data=null);
  9777. public function revoke($itemName,$userId);
  9778. public function isAssigned($itemName,$userId);
  9779. public function getAuthAssignment($itemName,$userId);
  9780. public function getAuthAssignments($userId);
  9781. public function saveAuthAssignment($assignment);
  9782. public function clearAll();
  9783. public function clearAuthAssignments();
  9784. public function save();
  9785. public function executeBizRule($bizRule,$params,$data);
  9786. }
  9787. interface IBehavior
  9788. {
  9789. public function attach($component);
  9790. public function detach($component);
  9791. public function getEnabled();
  9792. public function setEnabled($value);
  9793. }
  9794. interface IWidgetFactory
  9795. {
  9796. public function createWidget($owner,$className,$properties=array());
  9797. }
  9798. interface IDataProvider
  9799. {
  9800. public function getId();
  9801. public function getItemCount($refresh=false);
  9802. public function getTotalItemCount($refresh=false);
  9803. public function getData($refresh=false);
  9804. public function getKeys($refresh=false);
  9805. public function getSort();
  9806. public function getPagination();
  9807. }
  9808. interface ILogFilter
  9809. {
  9810. public function filter(&$logs);
  9811. }
  9812. ?>