PageRenderTime 137ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/yii/framework/yiilite.php

https://bitbucket.org/alxkolm/dry_test
PHP | 9618 lines | 9563 code | 2 blank | 53 comment | 814 complexity | 01eb1cfa6cf2fcd9486a9ce290f6ad1a MD5 | raw file
  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-2011 Yii Software LLC
  19. * @license http://www.yiiframework.com/license/
  20. * @version $Id: yiilite.php 3322 2011-06-26 17:38:50Z qiang.xue $
  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.8';
  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.',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.',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::$_coreClasses[$className]))
  210. include(YII_PATH.self::$_coreClasses[$className]);
  211. else if(isset(self::$classMap[$className]))
  212. include(self::$classMap[$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. break;
  227. }
  228. }
  229. }
  230. else
  231. include($className.'.php');
  232. }
  233. else // class name with namespace in PHP 5.3
  234. {
  235. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  236. if(($path=self::getPathOfAlias($namespace))!==false)
  237. include($path.'.php');
  238. else
  239. return false;
  240. }
  241. return class_exists($className,false) || interface_exists($className,false);
  242. }
  243. return true;
  244. }
  245. public static function trace($msg,$category='application')
  246. {
  247. if(YII_DEBUG)
  248. self::log($msg,CLogger::LEVEL_TRACE,$category);
  249. }
  250. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  251. {
  252. if(self::$_logger===null)
  253. self::$_logger=new CLogger;
  254. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  255. {
  256. $traces=debug_backtrace();
  257. $count=0;
  258. foreach($traces as $trace)
  259. {
  260. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  261. {
  262. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  263. if(++$count>=YII_TRACE_LEVEL)
  264. break;
  265. }
  266. }
  267. }
  268. self::$_logger->log($msg,$level,$category);
  269. }
  270. public static function beginProfile($token,$category='application')
  271. {
  272. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  273. }
  274. public static function endProfile($token,$category='application')
  275. {
  276. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  277. }
  278. public static function getLogger()
  279. {
  280. if(self::$_logger!==null)
  281. return self::$_logger;
  282. else
  283. return self::$_logger=new CLogger;
  284. }
  285. public static function setLogger($logger)
  286. {
  287. self::$_logger=$logger;
  288. }
  289. public static function powered()
  290. {
  291. return 'Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>.';
  292. }
  293. public static function t($category,$message,$params=array(),$source=null,$language=null)
  294. {
  295. if(self::$_app!==null)
  296. {
  297. if($source===null)
  298. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  299. if(($source=self::$_app->getComponent($source))!==null)
  300. $message=$source->translate($category,$message,$language);
  301. }
  302. if($params===array())
  303. return $message;
  304. if(!is_array($params))
  305. $params=array($params);
  306. if(isset($params[0])) // number choice
  307. {
  308. if(strpos($message,'|')!==false)
  309. {
  310. if(strpos($message,'#')===false)
  311. {
  312. $chunks=explode('|',$message);
  313. $expressions=self::$_app->getLocale($language)->getPluralRules();
  314. if($n=min(count($chunks),count($expressions)))
  315. {
  316. for($i=0;$i<$n;$i++)
  317. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  318. $message=implode('|',$chunks);
  319. }
  320. }
  321. $message=CChoiceFormat::format($message,$params[0]);
  322. }
  323. if(!isset($params['{n}']))
  324. $params['{n}']=$params[0];
  325. unset($params[0]);
  326. }
  327. return $params!==array() ? strtr($message,$params) : $message;
  328. }
  329. public static function registerAutoloader($callback, $append=false)
  330. {
  331. if($append)
  332. {
  333. self::$enableIncludePath=false;
  334. spl_autoload_register($callback);
  335. }
  336. else
  337. {
  338. spl_autoload_unregister(array('YiiBase','autoload'));
  339. spl_autoload_register($callback);
  340. spl_autoload_register(array('YiiBase','autoload'));
  341. }
  342. }
  343. private static $_coreClasses=array(
  344. 'CApplication' => '/base/CApplication.php',
  345. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  346. 'CBehavior' => '/base/CBehavior.php',
  347. 'CComponent' => '/base/CComponent.php',
  348. 'CErrorEvent' => '/base/CErrorEvent.php',
  349. 'CErrorHandler' => '/base/CErrorHandler.php',
  350. 'CException' => '/base/CException.php',
  351. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  352. 'CHttpException' => '/base/CHttpException.php',
  353. 'CModel' => '/base/CModel.php',
  354. 'CModelBehavior' => '/base/CModelBehavior.php',
  355. 'CModelEvent' => '/base/CModelEvent.php',
  356. 'CModule' => '/base/CModule.php',
  357. 'CSecurityManager' => '/base/CSecurityManager.php',
  358. 'CStatePersister' => '/base/CStatePersister.php',
  359. 'CApcCache' => '/caching/CApcCache.php',
  360. 'CCache' => '/caching/CCache.php',
  361. 'CDbCache' => '/caching/CDbCache.php',
  362. 'CDummyCache' => '/caching/CDummyCache.php',
  363. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  364. 'CFileCache' => '/caching/CFileCache.php',
  365. 'CMemCache' => '/caching/CMemCache.php',
  366. 'CWinCache' => '/caching/CWinCache.php',
  367. 'CXCache' => '/caching/CXCache.php',
  368. 'CZendDataCache' => '/caching/CZendDataCache.php',
  369. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  370. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  371. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  372. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  373. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  374. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  375. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  376. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  377. 'CConfiguration' => '/collections/CConfiguration.php',
  378. 'CList' => '/collections/CList.php',
  379. 'CListIterator' => '/collections/CListIterator.php',
  380. 'CMap' => '/collections/CMap.php',
  381. 'CMapIterator' => '/collections/CMapIterator.php',
  382. 'CQueue' => '/collections/CQueue.php',
  383. 'CQueueIterator' => '/collections/CQueueIterator.php',
  384. 'CStack' => '/collections/CStack.php',
  385. 'CStackIterator' => '/collections/CStackIterator.php',
  386. 'CTypedList' => '/collections/CTypedList.php',
  387. 'CTypedMap' => '/collections/CTypedMap.php',
  388. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  389. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  390. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  391. 'CHelpCommand' => '/console/CHelpCommand.php',
  392. 'CDbCommand' => '/db/CDbCommand.php',
  393. 'CDbConnection' => '/db/CDbConnection.php',
  394. 'CDbDataReader' => '/db/CDbDataReader.php',
  395. 'CDbException' => '/db/CDbException.php',
  396. 'CDbMigration' => '/db/CDbMigration.php',
  397. 'CDbTransaction' => '/db/CDbTransaction.php',
  398. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  399. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  400. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  401. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  402. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  403. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  404. 'CDbExpression' => '/db/schema/CDbExpression.php',
  405. 'CDbSchema' => '/db/schema/CDbSchema.php',
  406. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  407. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  408. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  409. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  410. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  411. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  412. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  413. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  414. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  415. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  416. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  417. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  418. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  419. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  420. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  421. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  422. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  423. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  424. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  425. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  426. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  427. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  428. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  429. 'CLocale' => '/i18n/CLocale.php',
  430. 'CMessageSource' => '/i18n/CMessageSource.php',
  431. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  432. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  433. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  434. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  435. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  436. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  437. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  438. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  439. 'CLogFilter' => '/logging/CLogFilter.php',
  440. 'CLogRoute' => '/logging/CLogRoute.php',
  441. 'CLogRouter' => '/logging/CLogRouter.php',
  442. 'CLogger' => '/logging/CLogger.php',
  443. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  444. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  445. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  446. 'CFileHelper' => '/utils/CFileHelper.php',
  447. 'CFormatter' => '/utils/CFormatter.php',
  448. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  449. 'CPropertyValue' => '/utils/CPropertyValue.php',
  450. 'CTimestamp' => '/utils/CTimestamp.php',
  451. 'CVarDumper' => '/utils/CVarDumper.php',
  452. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  453. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  454. 'CCompareValidator' => '/validators/CCompareValidator.php',
  455. 'CDateValidator' => '/validators/CDateValidator.php',
  456. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  457. 'CEmailValidator' => '/validators/CEmailValidator.php',
  458. 'CExistValidator' => '/validators/CExistValidator.php',
  459. 'CFileValidator' => '/validators/CFileValidator.php',
  460. 'CFilterValidator' => '/validators/CFilterValidator.php',
  461. 'CInlineValidator' => '/validators/CInlineValidator.php',
  462. 'CNumberValidator' => '/validators/CNumberValidator.php',
  463. 'CRangeValidator' => '/validators/CRangeValidator.php',
  464. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  465. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  466. 'CSafeValidator' => '/validators/CSafeValidator.php',
  467. 'CStringValidator' => '/validators/CStringValidator.php',
  468. 'CTypeValidator' => '/validators/CTypeValidator.php',
  469. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  470. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  471. 'CUrlValidator' => '/validators/CUrlValidator.php',
  472. 'CValidator' => '/validators/CValidator.php',
  473. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  474. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  475. 'CAssetManager' => '/web/CAssetManager.php',
  476. 'CBaseController' => '/web/CBaseController.php',
  477. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  478. 'CClientScript' => '/web/CClientScript.php',
  479. 'CController' => '/web/CController.php',
  480. 'CDataProvider' => '/web/CDataProvider.php',
  481. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  482. 'CExtController' => '/web/CExtController.php',
  483. 'CFormModel' => '/web/CFormModel.php',
  484. 'CHttpCookie' => '/web/CHttpCookie.php',
  485. 'CHttpRequest' => '/web/CHttpRequest.php',
  486. 'CHttpSession' => '/web/CHttpSession.php',
  487. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  488. 'COutputEvent' => '/web/COutputEvent.php',
  489. 'CPagination' => '/web/CPagination.php',
  490. 'CSort' => '/web/CSort.php',
  491. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  492. 'CTheme' => '/web/CTheme.php',
  493. 'CThemeManager' => '/web/CThemeManager.php',
  494. 'CUploadedFile' => '/web/CUploadedFile.php',
  495. 'CUrlManager' => '/web/CUrlManager.php',
  496. 'CWebApplication' => '/web/CWebApplication.php',
  497. 'CWebModule' => '/web/CWebModule.php',
  498. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  499. 'CAction' => '/web/actions/CAction.php',
  500. 'CInlineAction' => '/web/actions/CInlineAction.php',
  501. 'CViewAction' => '/web/actions/CViewAction.php',
  502. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  503. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  504. 'CAuthItem' => '/web/auth/CAuthItem.php',
  505. 'CAuthManager' => '/web/auth/CAuthManager.php',
  506. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  507. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  508. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  509. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  510. 'CWebUser' => '/web/auth/CWebUser.php',
  511. 'CFilter' => '/web/filters/CFilter.php',
  512. 'CFilterChain' => '/web/filters/CFilterChain.php',
  513. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  514. 'CForm' => '/web/form/CForm.php',
  515. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  516. 'CFormElement' => '/web/form/CFormElement.php',
  517. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  518. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  519. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  520. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  521. 'CHtml' => '/web/helpers/CHtml.php',
  522. 'CJSON' => '/web/helpers/CJSON.php',
  523. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  524. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  525. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  526. 'CWebService' => '/web/services/CWebService.php',
  527. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  528. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  529. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  530. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  531. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  532. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  533. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  534. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  535. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  536. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  537. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  538. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  539. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  540. 'COutputCache' => '/web/widgets/COutputCache.php',
  541. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  542. 'CStarRating' => '/web/widgets/CStarRating.php',
  543. 'CTabView' => '/web/widgets/CTabView.php',
  544. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  545. 'CTreeView' => '/web/widgets/CTreeView.php',
  546. 'CWidget' => '/web/widgets/CWidget.php',
  547. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  548. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  549. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  550. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  551. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  552. );
  553. }
  554. spl_autoload_register(array('YiiBase','autoload'));
  555. class Yii extends YiiBase
  556. {
  557. }
  558. class CComponent
  559. {
  560. private $_e;
  561. private $_m;
  562. public function __get($name)
  563. {
  564. $getter='get'.$name;
  565. if(method_exists($this,$getter))
  566. return $this->$getter();
  567. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  568. {
  569. // duplicating getEventHandlers() here for performance
  570. $name=strtolower($name);
  571. if(!isset($this->_e[$name]))
  572. $this->_e[$name]=new CList;
  573. return $this->_e[$name];
  574. }
  575. else if(isset($this->_m[$name]))
  576. return $this->_m[$name];
  577. else if(is_array($this->_m))
  578. {
  579. foreach($this->_m as $object)
  580. {
  581. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  582. return $object->$name;
  583. }
  584. }
  585. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  586. array('{class}'=>get_class($this), '{property}'=>$name)));
  587. }
  588. public function __set($name,$value)
  589. {
  590. $setter='set'.$name;
  591. if(method_exists($this,$setter))
  592. return $this->$setter($value);
  593. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  594. {
  595. // duplicating getEventHandlers() here for performance
  596. $name=strtolower($name);
  597. if(!isset($this->_e[$name]))
  598. $this->_e[$name]=new CList;
  599. return $this->_e[$name]->add($value);
  600. }
  601. else if(is_array($this->_m))
  602. {
  603. foreach($this->_m as $object)
  604. {
  605. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  606. return $object->$name=$value;
  607. }
  608. }
  609. if(method_exists($this,'get'.$name))
  610. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  611. array('{class}'=>get_class($this), '{property}'=>$name)));
  612. else
  613. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  614. array('{class}'=>get_class($this), '{property}'=>$name)));
  615. }
  616. public function __isset($name)
  617. {
  618. $getter='get'.$name;
  619. if(method_exists($this,$getter))
  620. return $this->$getter()!==null;
  621. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  622. {
  623. $name=strtolower($name);
  624. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  625. }
  626. else if(is_array($this->_m))
  627. {
  628. if(isset($this->_m[$name]))
  629. return true;
  630. foreach($this->_m as $object)
  631. {
  632. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  633. return true;
  634. }
  635. }
  636. return false;
  637. }
  638. public function __unset($name)
  639. {
  640. $setter='set'.$name;
  641. if(method_exists($this,$setter))
  642. $this->$setter(null);
  643. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  644. unset($this->_e[strtolower($name)]);
  645. else if(is_array($this->_m))
  646. {
  647. if(isset($this->_m[$name]))
  648. $this->detachBehavior($name);
  649. else
  650. {
  651. foreach($this->_m as $object)
  652. {
  653. if($object->getEnabled())
  654. {
  655. if(property_exists($object,$name))
  656. return $object->$name=null;
  657. else if($object->canSetProperty($name))
  658. return $object->$setter(null);
  659. }
  660. }
  661. }
  662. }
  663. else if(method_exists($this,'get'.$name))
  664. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  665. array('{class}'=>get_class($this), '{property}'=>$name)));
  666. }
  667. public function __call($name,$parameters)
  668. {
  669. if($this->_m!==null)
  670. {
  671. foreach($this->_m as $object)
  672. {
  673. if($object->getEnabled() && method_exists($object,$name))
  674. return call_user_func_array(array($object,$name),$parameters);
  675. }
  676. }
  677. if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)
  678. return call_user_func_array($this->$name, $parameters);
  679. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  680. array('{class}'=>get_class($this), '{name}'=>$name)));
  681. }
  682. public function asa($behavior)
  683. {
  684. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  685. }
  686. public function attachBehaviors($behaviors)
  687. {
  688. foreach($behaviors as $name=>$behavior)
  689. $this->attachBehavior($name,$behavior);
  690. }
  691. public function detachBehaviors()
  692. {
  693. if($this->_m!==null)
  694. {
  695. foreach($this->_m as $name=>$behavior)
  696. $this->detachBehavior($name);
  697. $this->_m=null;
  698. }
  699. }
  700. public function attachBehavior($name,$behavior)
  701. {
  702. if(!($behavior instanceof IBehavior))
  703. $behavior=Yii::createComponent($behavior);
  704. $behavior->setEnabled(true);
  705. $behavior->attach($this);
  706. return $this->_m[$name]=$behavior;
  707. }
  708. public function detachBehavior($name)
  709. {
  710. if(isset($this->_m[$name]))
  711. {
  712. $this->_m[$name]->detach($this);
  713. $behavior=$this->_m[$name];
  714. unset($this->_m[$name]);
  715. return $behavior;
  716. }
  717. }
  718. public function enableBehaviors()
  719. {
  720. if($this->_m!==null)
  721. {
  722. foreach($this->_m as $behavior)
  723. $behavior->setEnabled(true);
  724. }
  725. }
  726. public function disableBehaviors()
  727. {
  728. if($this->_m!==null)
  729. {
  730. foreach($this->_m as $behavior)
  731. $behavior->setEnabled(false);
  732. }
  733. }
  734. public function enableBehavior($name)
  735. {
  736. if(isset($this->_m[$name]))
  737. $this->_m[$name]->setEnabled(true);
  738. }
  739. public function disableBehavior($name)
  740. {
  741. if(isset($this->_m[$name]))
  742. $this->_m[$name]->setEnabled(false);
  743. }
  744. public function hasProperty($name)
  745. {
  746. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  747. }
  748. public function canGetProperty($name)
  749. {
  750. return method_exists($this,'get'.$name);
  751. }
  752. public function canSetProperty($name)
  753. {
  754. return method_exists($this,'set'.$name);
  755. }
  756. public function hasEvent($name)
  757. {
  758. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  759. }
  760. public function hasEventHandler($name)
  761. {
  762. $name=strtolower($name);
  763. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  764. }
  765. public function getEventHandlers($name)
  766. {
  767. if($this->hasEvent($name))
  768. {
  769. $name=strtolower($name);
  770. if(!isset($this->_e[$name]))
  771. $this->_e[$name]=new CList;
  772. return $this->_e[$name];
  773. }
  774. else
  775. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  776. array('{class}'=>get_class($this), '{event}'=>$name)));
  777. }
  778. public function attachEventHandler($name,$handler)
  779. {
  780. $this->getEventHandlers($name)->add($handler);
  781. }
  782. public function detachEventHandler($name,$handler)
  783. {
  784. if($this->hasEventHandler($name))
  785. return $this->getEventHandlers($name)->remove($handler)!==false;
  786. else
  787. return false;
  788. }
  789. public function raiseEvent($name,$event)
  790. {
  791. $name=strtolower($name);
  792. if(isset($this->_e[$name]))
  793. {
  794. foreach($this->_e[$name] as $handler)
  795. {
  796. if(is_string($handler))
  797. call_user_func($handler,$event);
  798. else if(is_callable($handler,true))
  799. {
  800. if(is_array($handler))
  801. {
  802. // an array: 0 - object, 1 - method name
  803. list($object,$method)=$handler;
  804. if(is_string($object)) // static method call
  805. call_user_func($handler,$event);
  806. else if(method_exists($object,$method))
  807. $object->$method($event);
  808. else
  809. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  810. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  811. }
  812. else // PHP 5.3: anonymous function
  813. call_user_func($handler,$event);
  814. }
  815. else
  816. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  817. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  818. // stop further handling if param.handled is set true
  819. if(($event instanceof CEvent) && $event->handled)
  820. return;
  821. }
  822. }
  823. else if(YII_DEBUG && !$this->hasEvent($name))
  824. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  825. array('{class}'=>get_class($this), '{event}'=>$name)));
  826. }
  827. public function evaluateExpression($_expression_,$_data_=array())
  828. {
  829. if(is_string($_expression_))
  830. {
  831. extract($_data_);
  832. return eval('return '.$_expression_.';');
  833. }
  834. else
  835. {
  836. $_data_[]=$this;
  837. return call_user_func_array($_expression_, $_data_);
  838. }
  839. }
  840. }
  841. class CEvent extends CComponent
  842. {
  843. public $sender;
  844. public $handled=false;
  845. public $params;
  846. public function __construct($sender=null,$params=null)
  847. {
  848. $this->sender=$sender;
  849. $this->params=$params;
  850. }
  851. }
  852. class CEnumerable
  853. {
  854. }
  855. abstract class CModule extends CComponent
  856. {
  857. public $preload=array();
  858. public $behaviors=array();
  859. private $_id;
  860. private $_parentModule;
  861. private $_basePath;
  862. private $_modulePath;
  863. private $_params;
  864. private $_modules=array();
  865. private $_moduleConfig=array();
  866. private $_components=array();
  867. private $_componentConfig=array();
  868. public function __construct($id,$parent,$config=null)
  869. {
  870. $this->_id=$id;
  871. $this->_parentModule=$parent;
  872. // set basePath at early as possible to avoid trouble
  873. if(is_string($config))
  874. $config=require($config);
  875. if(isset($config['basePath']))
  876. {
  877. $this->setBasePath($config['basePath']);
  878. unset($config['basePath']);
  879. }
  880. Yii::setPathOfAlias($id,$this->getBasePath());
  881. $this->preinit();
  882. $this->configure($config);
  883. $this->attachBehaviors($this->behaviors);
  884. $this->preloadComponents();
  885. $this->init();
  886. }
  887. public function __get($name)
  888. {
  889. if($this->hasComponent($name))
  890. return $this->getComponent($name);
  891. else
  892. return parent::__get($name);
  893. }
  894. public function __isset($name)
  895. {
  896. if($this->hasComponent($name))
  897. return $this->getComponent($name)!==null;
  898. else
  899. return parent::__isset($name);
  900. }
  901. public function getId()
  902. {
  903. return $this->_id;
  904. }
  905. public function setId($id)
  906. {
  907. $this->_id=$id;
  908. }
  909. public function getBasePath()
  910. {
  911. if($this->_basePath===null)
  912. {
  913. $class=new ReflectionClass(get_class($this));
  914. $this->_basePath=dirname($class->getFileName());
  915. }
  916. return $this->_basePath;
  917. }
  918. public function setBasePath($path)
  919. {
  920. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  921. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  922. array('{path}'=>$path)));
  923. }
  924. public function getParams()
  925. {
  926. if($this->_params!==null)
  927. return $this->_params;
  928. else
  929. {
  930. $this->_params=new CAttributeCollection;
  931. $this->_params->caseSensitive=true;
  932. return $this->_params;
  933. }
  934. }
  935. public function setParams($value)
  936. {
  937. $params=$this->getParams();
  938. foreach($value as $k=>$v)
  939. $params->add($k,$v);
  940. }
  941. public function getModulePath()
  942. {
  943. if($this->_modulePath!==null)
  944. return $this->_modulePath;
  945. else
  946. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  947. }
  948. public function setModulePath($value)
  949. {
  950. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  951. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  952. array('{path}'=>$value)));
  953. }
  954. public function setImport($aliases)
  955. {
  956. foreach($aliases as $alias)
  957. Yii::import($alias);
  958. }
  959. public function setAliases($mappings)
  960. {
  961. foreach($mappings as $name=>$alias)
  962. {
  963. if(($path=Yii::getPathOfAlias($alias))!==false)
  964. Yii::setPathOfAlias($name,$path);
  965. else
  966. Yii::setPathOfAlias($name,$alias);
  967. }
  968. }
  969. public function getParentModule()
  970. {
  971. return $this->_parentModule;
  972. }
  973. public function getModule($id)
  974. {
  975. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  976. return $this->_modules[$id];
  977. else if(isset($this->_moduleConfig[$id]))
  978. {
  979. $config=$this->_moduleConfig[$id];
  980. if(!isset($config['enabled']) || $config['enabled'])
  981. {
  982. $class=$config['class'];
  983. unset($config['class'], $config['enabled']);
  984. if($this===Yii::app())
  985. $module=Yii::createComponent($class,$id,null,$config);
  986. else
  987. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  988. return $this->_modules[$id]=$module;
  989. }
  990. }
  991. }
  992. public function hasModule($id)
  993. {
  994. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  995. }
  996. public function getModules()
  997. {
  998. return $this->_moduleConfig;
  999. }
  1000. public function setModules($modules)
  1001. {
  1002. foreach($modules as $id=>$module)
  1003. {
  1004. if(is_int($id))
  1005. {
  1006. $id=$module;
  1007. $module=array();
  1008. }
  1009. if(!isset($module['class']))
  1010. {
  1011. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1012. $module['class']=$id.'.'.ucfirst($id).'Module';
  1013. }
  1014. if(isset($this->_moduleConfig[$id]))
  1015. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1016. else
  1017. $this->_moduleConfig[$id]=$module;
  1018. }
  1019. }
  1020. public function hasComponent($id)
  1021. {
  1022. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1023. }
  1024. public function getComponent($id,$createIfNull=true)
  1025. {
  1026. if(isset($this->_components[$id]))
  1027. return $this->_components[$id];
  1028. else if(isset($this->_componentConfig[$id]) && $createIfNull)
  1029. {
  1030. $config=$this->_componentConfig[$id];
  1031. if(!isset($config['enabled']) || $config['enabled'])
  1032. {
  1033. unset($config['enabled']);
  1034. $component=Yii::createComponent($config);
  1035. $component->init();
  1036. return $this->_components[$id]=$component;
  1037. }
  1038. }
  1039. }
  1040. public function setComponent($id,$component)
  1041. {
  1042. if($component===null)
  1043. unset($this->_components[$id]);
  1044. else
  1045. {
  1046. $this->_components[$id]=$component;
  1047. if(!$component->getIsInitialized())
  1048. $component->init();
  1049. }
  1050. }
  1051. public function getComponents($loadedOnly=true)
  1052. {
  1053. if($loadedOnly)
  1054. return $this->_components;
  1055. else
  1056. return array_merge($this->_componentConfig, $this->_components);
  1057. }
  1058. public function setComponents($components,$merge=true)
  1059. {
  1060. foreach($components as $id=>$component)
  1061. {
  1062. if($component instanceof IApplicationComponent)
  1063. $this->setComponent($id,$component);
  1064. else if(isset($this->_componentConfig[$id]) && $merge)
  1065. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1066. else
  1067. $this->_componentConfig[$id]=$component;
  1068. }
  1069. }
  1070. public function configure($config)
  1071. {
  1072. if(is_array($config))
  1073. {
  1074. foreach($config as $key=>$value)
  1075. $this->$key=$value;
  1076. }
  1077. }
  1078. protected function preloadComponents()
  1079. {
  1080. foreach($this->preload as $id)
  1081. $this->getComponent($id);
  1082. }
  1083. protected function preinit()
  1084. {
  1085. }
  1086. protected function init()
  1087. {
  1088. }
  1089. }
  1090. abstract class CApplication extends CModule
  1091. {
  1092. public $name='My Application';
  1093. public $charset='UTF-8';
  1094. public $sourceLanguage='en_us';
  1095. private $_id;
  1096. private $_basePath;
  1097. private $_runtimePath;
  1098. private $_extensionPath;
  1099. private $_globalState;
  1100. private $_stateChanged;
  1101. private $_ended=false;
  1102. private $_language;
  1103. private $_homeUrl;
  1104. abstract public function processRequest();
  1105. public function __construct($config=null)
  1106. {
  1107. Yii::setApplication($this);
  1108. // set basePath at early as possible to avoid trouble
  1109. if(is_string($config))
  1110. $config=require($config);
  1111. if(isset($config['basePath']))
  1112. {
  1113. $this->setBasePath($config['basePath']);
  1114. unset($config['basePath']);
  1115. }
  1116. else
  1117. $this->setBasePath('protected');
  1118. Yii::setPathOfAlias('application',$this->getBasePath());
  1119. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1120. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1121. $this->preinit();
  1122. $this->initSystemHandlers();
  1123. $this->registerCoreComponents();
  1124. $this->configure($config);
  1125. $this->attachBehaviors($this->behaviors);
  1126. $this->preloadComponents();
  1127. $this->init();
  1128. }
  1129. public function run()
  1130. {
  1131. if($this->hasEventHandler('onBeginRequest'))
  1132. $this->onBeginRequest(new CEvent($this));
  1133. $this->processRequest();
  1134. if($this->hasEventHandler('onEndRequest'))
  1135. $this->onEndRequest(new CEvent($this));
  1136. }
  1137. public function end($status=0, $exit=true)
  1138. {
  1139. if($this->hasEventHandler('onEndRequest'))
  1140. $this->onEndRequest(new CEvent($this));
  1141. if($exit)
  1142. exit($status);
  1143. }
  1144. public function onBeginRequest($event)
  1145. {
  1146. $this->raiseEvent('onBeginRequest',$event);
  1147. }
  1148. public function onEndRequest($event)
  1149. {
  1150. if(!$this->_ended)
  1151. {
  1152. $this->_ended=true;
  1153. $this->raiseEvent('onEndRequest',$event);
  1154. }
  1155. }
  1156. public function getId()
  1157. {
  1158. if($this->_id!==null)
  1159. return $this->_id;
  1160. else
  1161. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1162. }
  1163. public function setId($id)
  1164. {
  1165. $this->_id=$id;
  1166. }
  1167. public function getBasePath()
  1168. {
  1169. return $this->_basePath;
  1170. }
  1171. public function setBasePath($path)
  1172. {
  1173. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1174. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1175. array('{path}'=>$path)));
  1176. }
  1177. public function getRuntimePath()
  1178. {
  1179. if($this->_runtimePath!==null)
  1180. return $this->_runtimePath;
  1181. else
  1182. {
  1183. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1184. return $this->_runtimePath;
  1185. }
  1186. }
  1187. public function setRuntimePath($path)
  1188. {
  1189. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1190. 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.',
  1191. array('{path}'=>$path)));
  1192. $this->_runtimePath=$runtimePath;
  1193. }
  1194. public function getExtensionPath()
  1195. {
  1196. return Yii::getPathOfAlias('ext');
  1197. }
  1198. public function setExtensionPath($path)
  1199. {
  1200. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1201. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1202. array('{path}'=>$path)));
  1203. Yii::setPathOfAlias('ext',$extensionPath);
  1204. }
  1205. public function getLanguage()
  1206. {
  1207. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1208. }
  1209. public function setLanguage($language)
  1210. {
  1211. $this->_language=$language;
  1212. }
  1213. public function getTimeZone()
  1214. {
  1215. return date_default_timezone_get();
  1216. }
  1217. public function setTimeZone($value)
  1218. {
  1219. date_default_timezone_set($value);
  1220. }
  1221. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1222. {
  1223. if($srcLanguage===null)
  1224. $srcLanguage=$this->sourceLanguage;
  1225. if($language===null)
  1226. $language=$this->getLanguage();
  1227. if($language===$srcLanguage)
  1228. return $srcFile;
  1229. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1230. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1231. }
  1232. public function getLocale($localeID=null)
  1233. {
  1234. return CLocale::getInstance($localeID===null?$this->getLanguage():$localeID);
  1235. }
  1236. public function getLocaleDataPath()
  1237. {
  1238. return CLocale::$dataPath===null ? Yii::getPathOfAlias('system.i18n.data') : CLocale::$dataPath;
  1239. }
  1240. public function setLocaleDataPath($value)
  1241. {
  1242. CLocale::$dataPath=$value;
  1243. }
  1244. public function getNumberFormatter()
  1245. {
  1246. return $this->getLocale()->getNumberFormatter();
  1247. }
  1248. public function getDateFormatter()
  1249. {
  1250. return $this->getLocale()->getDateFormatter();
  1251. }
  1252. public function getDb()
  1253. {
  1254. return $this->getComponent('db');
  1255. }
  1256. public function getErrorHandler()
  1257. {
  1258. return $this->getComponent('errorHandler');
  1259. }
  1260. public function getSecurityManager()
  1261. {
  1262. return $this->getComponent('securityManager');
  1263. }
  1264. public function getStatePersister()
  1265. {
  1266. return $this->getComponent('statePersister');
  1267. }
  1268. public function getCache()
  1269. {
  1270. return $this->getComponent('cache');
  1271. }
  1272. public function getCoreMessages()
  1273. {
  1274. return $this->getComponent('coreMessages');
  1275. }
  1276. public function getMessages()
  1277. {
  1278. return $this->getComponent('messages');
  1279. }
  1280. public function getRequest()
  1281. {
  1282. return $this->getComponent('request');
  1283. }
  1284. public function getUrlManager()
  1285. {
  1286. return $this->getComponent('urlManager');
  1287. }
  1288. public function getController()
  1289. {
  1290. return null;
  1291. }
  1292. public function createUrl($route,$params=array(),$ampersand='&')
  1293. {
  1294. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1295. }
  1296. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1297. {
  1298. $url=$this->createUrl($route,$params,$ampersand);
  1299. if(strpos($url,'http')===0)
  1300. return $url;
  1301. else
  1302. return $this->getRequest()->getHostInfo($schema).$url;
  1303. }
  1304. public function getBaseUrl($absolute=false)
  1305. {
  1306. return $this->getRequest()->getBaseUrl($absolute);
  1307. }
  1308. public function getHomeUrl()
  1309. {
  1310. if($this->_homeUrl===null)
  1311. {
  1312. if($this->getUrlManager()->showScriptName)
  1313. return $this->getRequest()->getScriptUrl();
  1314. else
  1315. return $this->getRequest()->getBaseUrl().'/';
  1316. }
  1317. else
  1318. return $this->_homeUrl;
  1319. }
  1320. public function setHomeUrl($value)
  1321. {
  1322. $this->_homeUrl=$value;
  1323. }
  1324. public function getGlobalState($key,$defaultValue=null)
  1325. {
  1326. if($this->_globalState===null)
  1327. $this->loadGlobalState();
  1328. if(isset($this->_globalState[$key]))
  1329. return $this->_globalState[$key];
  1330. else
  1331. return $defaultValue;
  1332. }
  1333. public function setGlobalState($key,$value,$defaultValue=null)
  1334. {
  1335. if($this->_globalState===null)
  1336. $this->loadGlobalState();
  1337. $changed=$this->_stateChanged;
  1338. if($value===$defaultValue)
  1339. {
  1340. if(isset($this->_globalState[$key]))
  1341. {
  1342. unset($this->_globalState[$key]);
  1343. $this->_stateChanged=true;
  1344. }
  1345. }
  1346. else if(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1347. {
  1348. $this->_globalState[$key]=$value;
  1349. $this->_stateChanged=true;
  1350. }
  1351. if($this->_stateChanged!==$changed)
  1352. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1353. }
  1354. public function clearGlobalState($key)
  1355. {
  1356. $this->setGlobalState($key,true,true);
  1357. }
  1358. public function loadGlobalState()
  1359. {
  1360. $persister=$this->getStatePersister();
  1361. if(($this->_globalState=$persister->load())===null)
  1362. $this->_globalState=array();
  1363. $this->_stateChanged=false;
  1364. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1365. }
  1366. public function saveGlobalState()
  1367. {
  1368. if($this->_stateChanged)
  1369. {
  1370. $this->_stateChanged=false;
  1371. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1372. $this->getStatePersister()->save($this->_globalState);
  1373. }
  1374. }
  1375. public function handleException($exception)
  1376. {
  1377. // disable error capturing to avoid recursive errors
  1378. restore_error_handler();
  1379. restore_exception_handler();
  1380. $category='exception.'.get_class($exception);
  1381. if($exception instanceof CHttpException)
  1382. $category.='.'.$exception->statusCode;
  1383. // php <5.2 doesn't support string conversion auto-magically
  1384. $message=$exception->__toString();
  1385. if(isset($_SERVER['REQUEST_URI']))
  1386. $message.=' REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1387. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1388. try
  1389. {
  1390. $event=new CExceptionEvent($this,$exception);
  1391. $this->onException($event);
  1392. if(!$event->handled)
  1393. {
  1394. // try an error handler
  1395. if(($handler=$this->getErrorHandler())!==null)
  1396. $handler->handle($event);
  1397. else
  1398. $this->displayException($exception);
  1399. }
  1400. }
  1401. catch(Exception $e)
  1402. {
  1403. $this->displayException($e);
  1404. }
  1405. try
  1406. {
  1407. $this->end(1);
  1408. }
  1409. catch(Exception $e)
  1410. {
  1411. // use the most primitive way to log error
  1412. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1413. $msg .= $e->getTraceAsString()."\n";
  1414. $msg .= "Previous exception:\n";
  1415. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1416. $msg .= $exception->getTraceAsString()."\n";
  1417. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1418. error_log($msg);
  1419. exit(1);
  1420. }
  1421. }
  1422. public function handleError($code,$message,$file,$line)
  1423. {
  1424. if($code & error_reporting())
  1425. {
  1426. // disable error capturing to avoid recursive errors
  1427. restore_error_handler();
  1428. restore_exception_handler();
  1429. $log="$message ($file:$line)\nStack trace:\n";
  1430. $trace=debug_backtrace();
  1431. // skip the first 3 stacks as they do not tell the error position
  1432. if(count($trace)>3)
  1433. $trace=array_slice($trace,3);
  1434. foreach($trace as $i=>$t)
  1435. {
  1436. if(!isset($t['file']))
  1437. $t['file']='unknown';
  1438. if(!isset($t['line']))
  1439. $t['line']=0;
  1440. if(!isset($t['function']))
  1441. $t['function']='unknown';
  1442. $log.="#$i {$t['file']}({$t['line']}): ";
  1443. if(isset($t['object']) && is_object($t['object']))
  1444. $log.=get_class($t['object']).'->';
  1445. $log.="{$t['function']}()\n";
  1446. }
  1447. if(isset($_SERVER['REQUEST_URI']))
  1448. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1449. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1450. try
  1451. {
  1452. Yii::import('CErrorEvent',true);
  1453. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1454. $this->onError($event);
  1455. if(!$event->handled)
  1456. {
  1457. // try an error handler
  1458. if(($handler=$this->getErrorHandler())!==null)
  1459. $handler->handle($event);
  1460. else
  1461. $this->displayError($code,$message,$file,$line);
  1462. }
  1463. }
  1464. catch(Exception $e)
  1465. {
  1466. $this->displayException($e);
  1467. }
  1468. try
  1469. {
  1470. $this->end(1);
  1471. }
  1472. catch(Exception $e)
  1473. {
  1474. // use the most primitive way to log error
  1475. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1476. $msg .= $e->getTraceAsString()."\n";
  1477. $msg .= "Previous error:\n";
  1478. $msg .= $log."\n";
  1479. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1480. error_log($msg);
  1481. exit(1);
  1482. }
  1483. }
  1484. }
  1485. public function onException($event)
  1486. {
  1487. $this->raiseEvent('onException',$event);
  1488. }
  1489. public function onError($event)
  1490. {
  1491. $this->raiseEvent('onError',$event);
  1492. }
  1493. public function displayError($code,$message,$file,$line)
  1494. {
  1495. if(YII_DEBUG)
  1496. {
  1497. echo "<h1>PHP Error [$code]</h1>\n";
  1498. echo "<p>$message ($file:$line)</p>\n";
  1499. echo '<pre>';
  1500. $trace=debug_backtrace();
  1501. // skip the first 3 stacks as they do not tell the error position
  1502. if(count($trace)>3)
  1503. $trace=array_slice($trace,3);
  1504. foreach($trace as $i=>$t)
  1505. {
  1506. if(!isset($t['file']))
  1507. $t['file']='unknown';
  1508. if(!isset($t['line']))
  1509. $t['line']=0;
  1510. if(!isset($t['function']))
  1511. $t['function']='unknown';
  1512. echo "#$i {$t['file']}({$t['line']}): ";
  1513. if(isset($t['object']) && is_object($t['object']))
  1514. echo get_class($t['object']).'->';
  1515. echo "{$t['function']}()\n";
  1516. }
  1517. echo '</pre>';
  1518. }
  1519. else
  1520. {
  1521. echo "<h1>PHP Error [$code]</h1>\n";
  1522. echo "<p>$message</p>\n";
  1523. }
  1524. }
  1525. public function displayException($exception)
  1526. {
  1527. if(YII_DEBUG)
  1528. {
  1529. echo '<h1>'.get_class($exception)."</h1>\n";
  1530. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1531. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1532. }
  1533. else
  1534. {
  1535. echo '<h1>'.get_class($exception)."</h1>\n";
  1536. echo '<p>'.$exception->getMessage().'</p>';
  1537. }
  1538. }
  1539. protected function initSystemHandlers()
  1540. {
  1541. if(YII_ENABLE_EXCEPTION_HANDLER)
  1542. set_exception_handler(array($this,'handleException'));
  1543. if(YII_ENABLE_ERROR_HANDLER)
  1544. set_error_handler(array($this,'handleError'),error_reporting());
  1545. }
  1546. protected function registerCoreComponents()
  1547. {
  1548. $components=array(
  1549. 'coreMessages'=>array(
  1550. 'class'=>'CPhpMessageSource',
  1551. 'language'=>'en_us',
  1552. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1553. ),
  1554. 'db'=>array(
  1555. 'class'=>'CDbConnection',
  1556. ),
  1557. 'messages'=>array(
  1558. 'class'=>'CPhpMessageSource',
  1559. ),
  1560. 'errorHandler'=>array(
  1561. 'class'=>'CErrorHandler',
  1562. ),
  1563. 'securityManager'=>array(
  1564. 'class'=>'CSecurityManager',
  1565. ),
  1566. 'statePersister'=>array(
  1567. 'class'=>'CStatePersister',
  1568. ),
  1569. 'urlManager'=>array(
  1570. 'class'=>'CUrlManager',
  1571. ),
  1572. 'request'=>array(
  1573. 'class'=>'CHttpRequest',
  1574. ),
  1575. 'format'=>array(
  1576. 'class'=>'CFormatter',
  1577. ),
  1578. );
  1579. $this->setComponents($components);
  1580. }
  1581. }
  1582. class CWebApplication extends CApplication
  1583. {
  1584. public $defaultController='site';
  1585. public $layout='main';
  1586. public $controllerMap=array();
  1587. public $catchAllRequest;
  1588. private $_controllerPath;
  1589. private $_viewPath;
  1590. private $_systemViewPath;
  1591. private $_layoutPath;
  1592. private $_controller;
  1593. private $_theme;
  1594. public function processRequest()
  1595. {
  1596. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1597. {
  1598. $route=$this->catchAllRequest[0];
  1599. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1600. $_GET[$name]=$value;
  1601. }
  1602. else
  1603. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1604. $this->runController($route);
  1605. }
  1606. protected function registerCoreComponents()
  1607. {
  1608. parent::registerCoreComponents();
  1609. $components=array(
  1610. 'session'=>array(
  1611. 'class'=>'CHttpSession',
  1612. ),
  1613. 'assetManager'=>array(
  1614. 'class'=>'CAssetManager',
  1615. ),
  1616. 'user'=>array(
  1617. 'class'=>'CWebUser',
  1618. ),
  1619. 'themeManager'=>array(
  1620. 'class'=>'CThemeManager',
  1621. ),
  1622. 'authManager'=>array(
  1623. 'class'=>'CPhpAuthManager',
  1624. ),
  1625. 'clientScript'=>array(
  1626. 'class'=>'CClientScript',
  1627. ),
  1628. 'widgetFactory'=>array(
  1629. 'class'=>'CWidgetFactory',
  1630. ),
  1631. );
  1632. $this->setComponents($components);
  1633. }
  1634. public function getAuthManager()
  1635. {
  1636. return $this->getComponent('authManager');
  1637. }
  1638. public function getAssetManager()
  1639. {
  1640. return $this->getComponent('assetManager');
  1641. }
  1642. public function getSession()
  1643. {
  1644. return $this->getComponent('session');
  1645. }
  1646. public function getUser()
  1647. {
  1648. return $this->getComponent('user');
  1649. }
  1650. public function getViewRenderer()
  1651. {
  1652. return $this->getComponent('viewRenderer');
  1653. }
  1654. public function getClientScript()
  1655. {
  1656. return $this->getComponent('clientScript');
  1657. }
  1658. public function getWidgetFactory()
  1659. {
  1660. return $this->getComponent('widgetFactory');
  1661. }
  1662. public function getThemeManager()
  1663. {
  1664. return $this->getComponent('themeManager');
  1665. }
  1666. public function getTheme()
  1667. {
  1668. if(is_string($this->_theme))
  1669. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1670. return $this->_theme;
  1671. }
  1672. public function setTheme($value)
  1673. {
  1674. $this->_theme=$value;
  1675. }
  1676. public function runController($route)
  1677. {
  1678. if(($ca=$this->createController($route))!==null)
  1679. {
  1680. list($controller,$actionID)=$ca;
  1681. $oldController=$this->_controller;
  1682. $this->_controller=$controller;
  1683. $controller->init();
  1684. $controller->run($actionID);
  1685. $this->_controller=$oldController;
  1686. }
  1687. else
  1688. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1689. array('{route}'=>$route===''?$this->defaultController:$route)));
  1690. }
  1691. public function createController($route,$owner=null)
  1692. {
  1693. if($owner===null)
  1694. $owner=$this;
  1695. if(($route=trim($route,'/'))==='')
  1696. $route=$owner->defaultController;
  1697. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1698. $route.='/';
  1699. while(($pos=strpos($route,'/'))!==false)
  1700. {
  1701. $id=substr($route,0,$pos);
  1702. if(!preg_match('/^\w+$/',$id))
  1703. return null;
  1704. if(!$caseSensitive)
  1705. $id=strtolower($id);
  1706. $route=(string)substr($route,$pos+1);
  1707. if(!isset($basePath)) // first segment
  1708. {
  1709. if(isset($owner->controllerMap[$id]))
  1710. {
  1711. return array(
  1712. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1713. $this->parseActionParams($route),
  1714. );
  1715. }
  1716. if(($module=$owner->getModule($id))!==null)
  1717. return $this->createController($route,$module);
  1718. $basePath=$owner->getControllerPath();
  1719. $controllerID='';
  1720. }
  1721. else
  1722. $controllerID.='/';
  1723. $className=ucfirst($id).'Controller';
  1724. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1725. if(is_file($classFile))
  1726. {
  1727. if(!class_exists($className,false))
  1728. require($classFile);
  1729. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1730. {
  1731. $id[0]=strtolower($id[0]);
  1732. return array(
  1733. new $className($controllerID.$id,$owner===$this?null:$owner),
  1734. $this->parseActionParams($route),
  1735. );
  1736. }
  1737. return null;
  1738. }
  1739. $controllerID.=$id;
  1740. $basePath.=DIRECTORY_SEPARATOR.$id;
  1741. }
  1742. }
  1743. protected function parseActionParams($pathInfo)
  1744. {
  1745. if(($pos=strpos($pathInfo,'/'))!==false)
  1746. {
  1747. $manager=$this->getUrlManager();
  1748. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1749. $actionID=substr($pathInfo,0,$pos);
  1750. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1751. }
  1752. else
  1753. return $pathInfo;
  1754. }
  1755. public function getController()
  1756. {
  1757. return $this->_controller;
  1758. }
  1759. public function setController($value)
  1760. {
  1761. $this->_controller=$value;
  1762. }
  1763. public function getControllerPath()
  1764. {
  1765. if($this->_controllerPath!==null)
  1766. return $this->_controllerPath;
  1767. else
  1768. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1769. }
  1770. public function setControllerPath($value)
  1771. {
  1772. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1773. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1774. array('{path}'=>$value)));
  1775. }
  1776. public function getViewPath()
  1777. {
  1778. if($this->_viewPath!==null)
  1779. return $this->_viewPath;
  1780. else
  1781. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1782. }
  1783. public function setViewPath($path)
  1784. {
  1785. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1786. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1787. array('{path}'=>$path)));
  1788. }
  1789. public function getSystemViewPath()
  1790. {
  1791. if($this->_systemViewPath!==null)
  1792. return $this->_systemViewPath;
  1793. else
  1794. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1795. }
  1796. public function setSystemViewPath($path)
  1797. {
  1798. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1799. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1800. array('{path}'=>$path)));
  1801. }
  1802. public function getLayoutPath()
  1803. {
  1804. if($this->_layoutPath!==null)
  1805. return $this->_layoutPath;
  1806. else
  1807. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1808. }
  1809. public function setLayoutPath($path)
  1810. {
  1811. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1812. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1813. array('{path}'=>$path)));
  1814. }
  1815. public function beforeControllerAction($controller,$action)
  1816. {
  1817. return true;
  1818. }
  1819. public function afterControllerAction($controller,$action)
  1820. {
  1821. }
  1822. public function findModule($id)
  1823. {
  1824. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1825. {
  1826. do
  1827. {
  1828. if(($m=$module->getModule($id))!==null)
  1829. return $m;
  1830. } while(($module=$module->getParentModule())!==null);
  1831. }
  1832. if(($m=$this->getModule($id))!==null)
  1833. return $m;
  1834. }
  1835. protected function init()
  1836. {
  1837. parent::init();
  1838. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1839. $this->getRequest();
  1840. }
  1841. }
  1842. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1843. {
  1844. private $_d=array();
  1845. private $_r=false;
  1846. public function __construct($data=null,$readOnly=false)
  1847. {
  1848. if($data!==null)
  1849. $this->copyFrom($data);
  1850. $this->setReadOnly($readOnly);
  1851. }
  1852. public function getReadOnly()
  1853. {
  1854. return $this->_r;
  1855. }
  1856. protected function setReadOnly($value)
  1857. {
  1858. $this->_r=$value;
  1859. }
  1860. public function getIterator()
  1861. {
  1862. return new CMapIterator($this->_d);
  1863. }
  1864. public function count()
  1865. {
  1866. return $this->getCount();
  1867. }
  1868. public function getCount()
  1869. {
  1870. return count($this->_d);
  1871. }
  1872. public function getKeys()
  1873. {
  1874. return array_keys($this->_d);
  1875. }
  1876. public function itemAt($key)
  1877. {
  1878. if(isset($this->_d[$key]))
  1879. return $this->_d[$key];
  1880. else
  1881. return null;
  1882. }
  1883. public function add($key,$value)
  1884. {
  1885. if(!$this->_r)
  1886. {
  1887. if($key===null)
  1888. $this->_d[]=$value;
  1889. else
  1890. $this->_d[$key]=$value;
  1891. }
  1892. else
  1893. throw new CException(Yii::t('yii','The map is read only.'));
  1894. }
  1895. public function remove($key)
  1896. {
  1897. if(!$this->_r)
  1898. {
  1899. if(isset($this->_d[$key]))
  1900. {
  1901. $value=$this->_d[$key];
  1902. unset($this->_d[$key]);
  1903. return $value;
  1904. }
  1905. else
  1906. {
  1907. // it is possible the value is null, which is not detected by isset
  1908. unset($this->_d[$key]);
  1909. return null;
  1910. }
  1911. }
  1912. else
  1913. throw new CException(Yii::t('yii','The map is read only.'));
  1914. }
  1915. public function clear()
  1916. {
  1917. foreach(array_keys($this->_d) as $key)
  1918. $this->remove($key);
  1919. }
  1920. public function contains($key)
  1921. {
  1922. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  1923. }
  1924. public function toArray()
  1925. {
  1926. return $this->_d;
  1927. }
  1928. public function copyFrom($data)
  1929. {
  1930. if(is_array($data) || $data instanceof Traversable)
  1931. {
  1932. if($this->getCount()>0)
  1933. $this->clear();
  1934. if($data instanceof CMap)
  1935. $data=$data->_d;
  1936. foreach($data as $key=>$value)
  1937. $this->add($key,$value);
  1938. }
  1939. else if($data!==null)
  1940. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1941. }
  1942. public function mergeWith($data,$recursive=true)
  1943. {
  1944. if(is_array($data) || $data instanceof Traversable)
  1945. {
  1946. if($data instanceof CMap)
  1947. $data=$data->_d;
  1948. if($recursive)
  1949. {
  1950. if($data instanceof Traversable)
  1951. {
  1952. $d=array();
  1953. foreach($data as $key=>$value)
  1954. $d[$key]=$value;
  1955. $this->_d=self::mergeArray($this->_d,$d);
  1956. }
  1957. else
  1958. $this->_d=self::mergeArray($this->_d,$data);
  1959. }
  1960. else
  1961. {
  1962. foreach($data as $key=>$value)
  1963. $this->add($key,$value);
  1964. }
  1965. }
  1966. else if($data!==null)
  1967. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  1968. }
  1969. public static function mergeArray($a,$b)
  1970. {
  1971. foreach($b as $k=>$v)
  1972. {
  1973. if(is_integer($k))
  1974. isset($a[$k]) ? $a[]=$v : $a[$k]=$v;
  1975. else if(is_array($v) && isset($a[$k]) && is_array($a[$k]))
  1976. $a[$k]=self::mergeArray($a[$k],$v);
  1977. else
  1978. $a[$k]=$v;
  1979. }
  1980. return $a;
  1981. }
  1982. public function offsetExists($offset)
  1983. {
  1984. return $this->contains($offset);
  1985. }
  1986. public function offsetGet($offset)
  1987. {
  1988. return $this->itemAt($offset);
  1989. }
  1990. public function offsetSet($offset,$item)
  1991. {
  1992. $this->add($offset,$item);
  1993. }
  1994. public function offsetUnset($offset)
  1995. {
  1996. $this->remove($offset);
  1997. }
  1998. }
  1999. class CLogger extends CComponent
  2000. {
  2001. const LEVEL_TRACE='trace';
  2002. const LEVEL_WARNING='warning';
  2003. const LEVEL_ERROR='error';
  2004. const LEVEL_INFO='info';
  2005. const LEVEL_PROFILE='profile';
  2006. public $autoFlush=10000;
  2007. public $autoDump=false;
  2008. private $_logs=array();
  2009. private $_logCount=0;
  2010. private $_levels;
  2011. private $_categories;
  2012. private $_timings;
  2013. public function log($message,$level='info',$category='application')
  2014. {
  2015. $this->_logs[]=array($message,$level,$category,microtime(true));
  2016. $this->_logCount++;
  2017. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush)
  2018. $this->flush($this->autoDump);
  2019. }
  2020. public function getLogs($levels='',$categories='')
  2021. {
  2022. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2023. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2024. if(empty($levels) && empty($categories))
  2025. return $this->_logs;
  2026. else if(empty($levels))
  2027. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByCategory'))));
  2028. else if(empty($categories))
  2029. return array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  2030. else
  2031. {
  2032. $ret=array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevel'))));
  2033. return array_values(array_filter(array_filter($ret,array($this,'filterByCategory'))));
  2034. }
  2035. }
  2036. private function filterByCategory($value)
  2037. {
  2038. foreach($this->_categories as $category)
  2039. {
  2040. $cat=strtolower($value[2]);
  2041. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2042. return $value;
  2043. }
  2044. return false;
  2045. }
  2046. private function filterByLevel($value)
  2047. {
  2048. return in_array(strtolower($value[1]),$this->_levels)?$value:false;
  2049. }
  2050. public function getExecutionTime()
  2051. {
  2052. return microtime(true)-YII_BEGIN_TIME;
  2053. }
  2054. public function getMemoryUsage()
  2055. {
  2056. if(function_exists('memory_get_usage'))
  2057. return memory_get_usage();
  2058. else
  2059. {
  2060. $output=array();
  2061. if(strncmp(PHP_OS,'WIN',3)===0)
  2062. {
  2063. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2064. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2065. }
  2066. else
  2067. {
  2068. $pid=getmypid();
  2069. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2070. $output=explode(" ",$output[0]);
  2071. return isset($output[1]) ? $output[1]*1024 : 0;
  2072. }
  2073. }
  2074. }
  2075. public function getProfilingResults($token=null,$category=null,$refresh=false)
  2076. {
  2077. if($this->_timings===null || $refresh)
  2078. $this->calculateTimings();
  2079. if($token===null && $category===null)
  2080. return $this->_timings;
  2081. $results=array();
  2082. foreach($this->_timings as $timing)
  2083. {
  2084. if(($category===null || $timing[1]===$category) && ($token===null || $timing[0]===$token))
  2085. $results[]=$timing[2];
  2086. }
  2087. return $results;
  2088. }
  2089. private function calculateTimings()
  2090. {
  2091. $this->_timings=array();
  2092. $stack=array();
  2093. foreach($this->_logs as $log)
  2094. {
  2095. if($log[1]!==CLogger::LEVEL_PROFILE)
  2096. continue;
  2097. list($message,$level,$category,$timestamp)=$log;
  2098. if(!strncasecmp($message,'begin:',6))
  2099. {
  2100. $log[0]=substr($message,6);
  2101. $stack[]=$log;
  2102. }
  2103. else if(!strncasecmp($message,'end:',4))
  2104. {
  2105. $token=substr($message,4);
  2106. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2107. {
  2108. $delta=$log[3]-$last[3];
  2109. $this->_timings[]=array($message,$category,$delta);
  2110. }
  2111. else
  2112. 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.',
  2113. array('{token}'=>$token)));
  2114. }
  2115. }
  2116. $now=microtime(true);
  2117. while(($last=array_pop($stack))!==null)
  2118. {
  2119. $delta=$now-$last[3];
  2120. $this->_timings[]=array($last[0],$last[2],$delta);
  2121. }
  2122. }
  2123. public function flush($dumpLogs=false)
  2124. {
  2125. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2126. $this->_logs=array();
  2127. $this->_logCount=0;
  2128. }
  2129. public function onFlush($event)
  2130. {
  2131. $this->raiseEvent('onFlush', $event);
  2132. }
  2133. }
  2134. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2135. {
  2136. public $behaviors=array();
  2137. private $_initialized=false;
  2138. public function init()
  2139. {
  2140. $this->attachBehaviors($this->behaviors);
  2141. $this->_initialized=true;
  2142. }
  2143. public function getIsInitialized()
  2144. {
  2145. return $this->_initialized;
  2146. }
  2147. }
  2148. class CHttpRequest extends CApplicationComponent
  2149. {
  2150. public $enableCookieValidation=false;
  2151. public $enableCsrfValidation=false;
  2152. public $csrfTokenName='YII_CSRF_TOKEN';
  2153. public $csrfCookie;
  2154. private $_requestUri;
  2155. private $_pathInfo;
  2156. private $_scriptFile;
  2157. private $_scriptUrl;
  2158. private $_hostInfo;
  2159. private $_baseUrl;
  2160. private $_cookies;
  2161. private $_preferredLanguage;
  2162. private $_csrfToken;
  2163. private $_deleteParams;
  2164. private $_putParams;
  2165. public function init()
  2166. {
  2167. parent::init();
  2168. $this->normalizeRequest();
  2169. }
  2170. protected function normalizeRequest()
  2171. {
  2172. // normalize request
  2173. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2174. {
  2175. if(isset($_GET))
  2176. $_GET=$this->stripSlashes($_GET);
  2177. if(isset($_POST))
  2178. $_POST=$this->stripSlashes($_POST);
  2179. if(isset($_REQUEST))
  2180. $_REQUEST=$this->stripSlashes($_REQUEST);
  2181. if(isset($_COOKIE))
  2182. $_COOKIE=$this->stripSlashes($_COOKIE);
  2183. }
  2184. if($this->enableCsrfValidation)
  2185. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2186. }
  2187. public function stripSlashes(&$data)
  2188. {
  2189. return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
  2190. }
  2191. public function getParam($name,$defaultValue=null)
  2192. {
  2193. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2194. }
  2195. public function getQuery($name,$defaultValue=null)
  2196. {
  2197. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2198. }
  2199. public function getPost($name,$defaultValue=null)
  2200. {
  2201. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2202. }
  2203. public function getDelete($name,$defaultValue=null)
  2204. {
  2205. if($this->_deleteParams===null)
  2206. $this->_deleteParams=$this->getIsDeleteRequest() ? $this->getRestParams() : array();
  2207. return isset($this->_deleteParams[$name]) ? $this->_deleteParams[$name] : $defaultValue;
  2208. }
  2209. public function getPut($name,$defaultValue=null)
  2210. {
  2211. if($this->_putParams===null)
  2212. $this->_putParams=$this->getIsPutRequest() ? $this->getRestParams() : array();
  2213. return isset($this->_putParams[$name]) ? $this->_putParams[$name] : $defaultValue;
  2214. }
  2215. protected function getRestParams()
  2216. {
  2217. $result=array();
  2218. if(function_exists('mb_parse_str'))
  2219. mb_parse_str(file_get_contents('php://input'), $result);
  2220. else
  2221. parse_str(file_get_contents('php://input'), $result);
  2222. return $result;
  2223. }
  2224. public function getUrl()
  2225. {
  2226. return $this->getRequestUri();
  2227. }
  2228. public function getHostInfo($schema='')
  2229. {
  2230. if($this->_hostInfo===null)
  2231. {
  2232. if($secure=$this->getIsSecureConnection())
  2233. $http='https';
  2234. else
  2235. $http='http';
  2236. if(isset($_SERVER['HTTP_HOST']))
  2237. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2238. else
  2239. {
  2240. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2241. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2242. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2243. $this->_hostInfo.=':'.$port;
  2244. }
  2245. }
  2246. if($schema!=='')
  2247. {
  2248. $secure=$this->getIsSecureConnection();
  2249. if($secure && $schema==='https' || !$secure && $schema==='http')
  2250. return $this->_hostInfo;
  2251. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2252. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2253. $port=':'.$port;
  2254. else
  2255. $port='';
  2256. $pos=strpos($this->_hostInfo,':');
  2257. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2258. }
  2259. else
  2260. return $this->_hostInfo;
  2261. }
  2262. public function setHostInfo($value)
  2263. {
  2264. $this->_hostInfo=rtrim($value,'/');
  2265. }
  2266. public function getBaseUrl($absolute=false)
  2267. {
  2268. if($this->_baseUrl===null)
  2269. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2270. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2271. }
  2272. public function setBaseUrl($value)
  2273. {
  2274. $this->_baseUrl=$value;
  2275. }
  2276. public function getScriptUrl()
  2277. {
  2278. if($this->_scriptUrl===null)
  2279. {
  2280. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2281. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2282. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2283. else if(basename($_SERVER['PHP_SELF'])===$scriptName)
  2284. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2285. else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2286. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2287. else if(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2288. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2289. else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2290. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2291. else
  2292. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2293. }
  2294. return $this->_scriptUrl;
  2295. }
  2296. public function setScriptUrl($value)
  2297. {
  2298. $this->_scriptUrl='/'.trim($value,'/');
  2299. }
  2300. public function getPathInfo()
  2301. {
  2302. if($this->_pathInfo===null)
  2303. {
  2304. $pathInfo=$this->getRequestUri();
  2305. if(($pos=strpos($pathInfo,'?'))!==false)
  2306. $pathInfo=substr($pathInfo,0,$pos);
  2307. $pathInfo=urldecode($pathInfo);
  2308. $scriptUrl=$this->getScriptUrl();
  2309. $baseUrl=$this->getBaseUrl();
  2310. if(strpos($pathInfo,$scriptUrl)===0)
  2311. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2312. else if($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2313. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2314. else if(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2315. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2316. else
  2317. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2318. $this->_pathInfo=trim($pathInfo,'/');
  2319. }
  2320. return $this->_pathInfo;
  2321. }
  2322. public function getRequestUri()
  2323. {
  2324. if($this->_requestUri===null)
  2325. {
  2326. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2327. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2328. else if(isset($_SERVER['REQUEST_URI']))
  2329. {
  2330. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2331. if(isset($_SERVER['HTTP_HOST']))
  2332. {
  2333. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2334. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2335. }
  2336. else
  2337. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2338. }
  2339. else if(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2340. {
  2341. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2342. if(!empty($_SERVER['QUERY_STRING']))
  2343. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2344. }
  2345. else
  2346. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2347. }
  2348. return $this->_requestUri;
  2349. }
  2350. public function getQueryString()
  2351. {
  2352. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2353. }
  2354. public function getIsSecureConnection()
  2355. {
  2356. return isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'],'on');
  2357. }
  2358. public function getRequestType()
  2359. {
  2360. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2361. }
  2362. public function getIsPostRequest()
  2363. {
  2364. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2365. }
  2366. public function getIsDeleteRequest()
  2367. {
  2368. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE');
  2369. }
  2370. public function getIsPutRequest()
  2371. {
  2372. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT');
  2373. }
  2374. public function getIsAjaxRequest()
  2375. {
  2376. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2377. }
  2378. public function getServerName()
  2379. {
  2380. return $_SERVER['SERVER_NAME'];
  2381. }
  2382. public function getServerPort()
  2383. {
  2384. return $_SERVER['SERVER_PORT'];
  2385. }
  2386. public function getUrlReferrer()
  2387. {
  2388. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2389. }
  2390. public function getUserAgent()
  2391. {
  2392. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2393. }
  2394. public function getUserHostAddress()
  2395. {
  2396. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2397. }
  2398. public function getUserHost()
  2399. {
  2400. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2401. }
  2402. public function getScriptFile()
  2403. {
  2404. if($this->_scriptFile!==null)
  2405. return $this->_scriptFile;
  2406. else
  2407. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2408. }
  2409. public function getBrowser($userAgent=null)
  2410. {
  2411. return get_browser($userAgent,true);
  2412. }
  2413. public function getAcceptTypes()
  2414. {
  2415. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2416. }
  2417. private $_port;
  2418. public function getPort()
  2419. {
  2420. if($this->_port===null)
  2421. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2422. return $this->_port;
  2423. }
  2424. public function setPort($value)
  2425. {
  2426. $this->_port=(int)$value;
  2427. $this->_hostInfo=null;
  2428. }
  2429. private $_securePort;
  2430. public function getSecurePort()
  2431. {
  2432. if($this->_securePort===null)
  2433. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2434. return $this->_securePort;
  2435. }
  2436. public function setSecurePort($value)
  2437. {
  2438. $this->_securePort=(int)$value;
  2439. $this->_hostInfo=null;
  2440. }
  2441. public function getCookies()
  2442. {
  2443. if($this->_cookies!==null)
  2444. return $this->_cookies;
  2445. else
  2446. return $this->_cookies=new CCookieCollection($this);
  2447. }
  2448. public function redirect($url,$terminate=true,$statusCode=302)
  2449. {
  2450. if(strpos($url,'/')===0)
  2451. $url=$this->getHostInfo().$url;
  2452. header('Location: '.$url, true, $statusCode);
  2453. if($terminate)
  2454. Yii::app()->end();
  2455. }
  2456. public function getPreferredLanguage()
  2457. {
  2458. if($this->_preferredLanguage===null)
  2459. {
  2460. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && ($n=preg_match_all('/([\w\-_]+)\s*(;\s*q\s*=\s*(\d*\.\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))>0)
  2461. {
  2462. $languages=array();
  2463. for($i=0;$i<$n;++$i)
  2464. $languages[$matches[1][$i]]=empty($matches[3][$i]) ? 1.0 : floatval($matches[3][$i]);
  2465. arsort($languages);
  2466. foreach($languages as $language=>$pref)
  2467. return $this->_preferredLanguage=CLocale::getCanonicalID($language);
  2468. }
  2469. return $this->_preferredLanguage=false;
  2470. }
  2471. return $this->_preferredLanguage;
  2472. }
  2473. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2474. {
  2475. if($mimeType===null)
  2476. {
  2477. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2478. $mimeType='text/plain';
  2479. }
  2480. header('Pragma: public');
  2481. header('Expires: 0');
  2482. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2483. header("Content-type: $mimeType");
  2484. if(ini_get("output_handler")=='')
  2485. header('Content-Length: '.(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content)));
  2486. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2487. header('Content-Transfer-Encoding: binary');
  2488. if($terminate)
  2489. {
  2490. // clean up the application first because the file downloading could take long time
  2491. // which may cause timeout of some resources (such as DB connection)
  2492. Yii::app()->end(0,false);
  2493. echo $content;
  2494. exit(0);
  2495. }
  2496. else
  2497. echo $content;
  2498. }
  2499. public function xSendFile($filePath, $options=array())
  2500. {
  2501. if(!is_file($filePath))
  2502. return false;
  2503. if(!isset($options['saveName']))
  2504. $options['saveName']=basename($filePath);
  2505. if(!isset($options['mimeType']))
  2506. {
  2507. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2508. $options['mimeType']='text/plain';
  2509. }
  2510. if(!isset($options['xHeader']))
  2511. $options['xHeader']='X-Sendfile';
  2512. header('Content-type: '.$options['mimeType']);
  2513. header('Content-Disposition: attachment; filename="'.$options['saveName'].'"');
  2514. header(trim($options['xHeader']).': '.$filePath);
  2515. if(!isset($options['terminate']) || $options['terminate'])
  2516. Yii::app()->end();
  2517. return true;
  2518. }
  2519. public function getCsrfToken()
  2520. {
  2521. if($this->_csrfToken===null)
  2522. {
  2523. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2524. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2525. {
  2526. $cookie=$this->createCsrfCookie();
  2527. $this->_csrfToken=$cookie->value;
  2528. $this->getCookies()->add($cookie->name,$cookie);
  2529. }
  2530. }
  2531. return $this->_csrfToken;
  2532. }
  2533. protected function createCsrfCookie()
  2534. {
  2535. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2536. if(is_array($this->csrfCookie))
  2537. {
  2538. foreach($this->csrfCookie as $name=>$value)
  2539. $cookie->$name=$value;
  2540. }
  2541. return $cookie;
  2542. }
  2543. public function validateCsrfToken($event)
  2544. {
  2545. if($this->getIsPostRequest())
  2546. {
  2547. // only validate POST requests
  2548. $cookies=$this->getCookies();
  2549. if($cookies->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName]))
  2550. {
  2551. $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value;
  2552. $tokenFromPost=$_POST[$this->csrfTokenName];
  2553. $valid=$tokenFromCookie===$tokenFromPost;
  2554. }
  2555. else
  2556. $valid=false;
  2557. if(!$valid)
  2558. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2559. }
  2560. }
  2561. }
  2562. class CCookieCollection extends CMap
  2563. {
  2564. private $_request;
  2565. private $_initialized=false;
  2566. public function __construct(CHttpRequest $request)
  2567. {
  2568. $this->_request=$request;
  2569. $this->copyfrom($this->getCookies());
  2570. $this->_initialized=true;
  2571. }
  2572. public function getRequest()
  2573. {
  2574. return $this->_request;
  2575. }
  2576. protected function getCookies()
  2577. {
  2578. $cookies=array();
  2579. if($this->_request->enableCookieValidation)
  2580. {
  2581. $sm=Yii::app()->getSecurityManager();
  2582. foreach($_COOKIE as $name=>$value)
  2583. {
  2584. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  2585. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  2586. }
  2587. }
  2588. else
  2589. {
  2590. foreach($_COOKIE as $name=>$value)
  2591. $cookies[$name]=new CHttpCookie($name,$value);
  2592. }
  2593. return $cookies;
  2594. }
  2595. public function add($name,$cookie)
  2596. {
  2597. if($cookie instanceof CHttpCookie)
  2598. {
  2599. $this->remove($name);
  2600. parent::add($name,$cookie);
  2601. if($this->_initialized)
  2602. $this->addCookie($cookie);
  2603. }
  2604. else
  2605. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  2606. }
  2607. public function remove($name)
  2608. {
  2609. if(($cookie=parent::remove($name))!==null)
  2610. {
  2611. if($this->_initialized)
  2612. $this->removeCookie($cookie);
  2613. }
  2614. return $cookie;
  2615. }
  2616. protected function addCookie($cookie)
  2617. {
  2618. $value=$cookie->value;
  2619. if($this->_request->enableCookieValidation)
  2620. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  2621. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2622. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2623. else
  2624. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  2625. }
  2626. protected function removeCookie($cookie)
  2627. {
  2628. if(version_compare(PHP_VERSION,'5.2.0','>='))
  2629. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  2630. else
  2631. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure);
  2632. }
  2633. }
  2634. class CUrlManager extends CApplicationComponent
  2635. {
  2636. const CACHE_KEY='Yii.CUrlManager.rules';
  2637. const GET_FORMAT='get';
  2638. const PATH_FORMAT='path';
  2639. public $rules=array();
  2640. public $urlSuffix='';
  2641. public $showScriptName=true;
  2642. public $appendParams=true;
  2643. public $routeVar='r';
  2644. public $caseSensitive=true;
  2645. public $matchValue=false;
  2646. public $cacheID='cache';
  2647. public $useStrictParsing=false;
  2648. public $urlRuleClass='CUrlRule';
  2649. private $_urlFormat=self::GET_FORMAT;
  2650. private $_rules=array();
  2651. private $_baseUrl;
  2652. public function init()
  2653. {
  2654. parent::init();
  2655. $this->processRules();
  2656. }
  2657. protected function processRules()
  2658. {
  2659. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  2660. return;
  2661. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  2662. {
  2663. $hash=md5(serialize($this->rules));
  2664. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  2665. {
  2666. $this->_rules=$data[0];
  2667. return;
  2668. }
  2669. }
  2670. foreach($this->rules as $pattern=>$route)
  2671. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2672. if(isset($cache))
  2673. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  2674. }
  2675. public function addRules($rules)
  2676. {
  2677. foreach($rules as $pattern=>$route)
  2678. $this->_rules[]=$this->createUrlRule($route,$pattern);
  2679. }
  2680. protected function createUrlRule($route,$pattern)
  2681. {
  2682. if(is_array($route) && isset($route['class']))
  2683. return $route;
  2684. else
  2685. return new $this->urlRuleClass($route,$pattern);
  2686. }
  2687. public function createUrl($route,$params=array(),$ampersand='&')
  2688. {
  2689. unset($params[$this->routeVar]);
  2690. foreach($params as &$param)
  2691. if($param===null)
  2692. $param='';
  2693. if(isset($params['#']))
  2694. {
  2695. $anchor='#'.$params['#'];
  2696. unset($params['#']);
  2697. }
  2698. else
  2699. $anchor='';
  2700. $route=trim($route,'/');
  2701. foreach($this->_rules as $i=>$rule)
  2702. {
  2703. if(is_array($rule))
  2704. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2705. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  2706. {
  2707. if($rule->hasHostInfo)
  2708. return $url==='' ? '/'.$anchor : $url.$anchor;
  2709. else
  2710. return $this->getBaseUrl().'/'.$url.$anchor;
  2711. }
  2712. }
  2713. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  2714. }
  2715. protected function createUrlDefault($route,$params,$ampersand)
  2716. {
  2717. if($this->getUrlFormat()===self::PATH_FORMAT)
  2718. {
  2719. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  2720. if($this->appendParams)
  2721. {
  2722. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  2723. return $route==='' ? $url : $url.$this->urlSuffix;
  2724. }
  2725. else
  2726. {
  2727. if($route!=='')
  2728. $url.=$this->urlSuffix;
  2729. $query=$this->createPathInfo($params,'=',$ampersand);
  2730. return $query==='' ? $url : $url.'?'.$query;
  2731. }
  2732. }
  2733. else
  2734. {
  2735. $url=$this->getBaseUrl();
  2736. if(!$this->showScriptName)
  2737. $url.='/';
  2738. if($route!=='')
  2739. {
  2740. $url.='?'.$this->routeVar.'='.$route;
  2741. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2742. $url.=$ampersand.$query;
  2743. }
  2744. else if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  2745. $url.='?'.$query;
  2746. return $url;
  2747. }
  2748. }
  2749. public function parseUrl($request)
  2750. {
  2751. if($this->getUrlFormat()===self::PATH_FORMAT)
  2752. {
  2753. $rawPathInfo=$request->getPathInfo();
  2754. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  2755. foreach($this->_rules as $i=>$rule)
  2756. {
  2757. if(is_array($rule))
  2758. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  2759. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  2760. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  2761. }
  2762. if($this->useStrictParsing)
  2763. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  2764. array('{route}'=>$pathInfo)));
  2765. else
  2766. return $pathInfo;
  2767. }
  2768. else if(isset($_GET[$this->routeVar]))
  2769. return $_GET[$this->routeVar];
  2770. else if(isset($_POST[$this->routeVar]))
  2771. return $_POST[$this->routeVar];
  2772. else
  2773. return '';
  2774. }
  2775. public function parsePathInfo($pathInfo)
  2776. {
  2777. if($pathInfo==='')
  2778. return;
  2779. $segs=explode('/',$pathInfo.'/');
  2780. $n=count($segs);
  2781. for($i=0;$i<$n-1;$i+=2)
  2782. {
  2783. $key=$segs[$i];
  2784. if($key==='') continue;
  2785. $value=$segs[$i+1];
  2786. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  2787. {
  2788. $name=substr($key,0,$pos);
  2789. for($j=$m-1;$j>=0;--$j)
  2790. {
  2791. if($matches[1][$j]==='')
  2792. $value=array($value);
  2793. else
  2794. $value=array($matches[1][$j]=>$value);
  2795. }
  2796. if(isset($_GET[$name]) && is_array($_GET[$name]))
  2797. $value=CMap::mergeArray($_GET[$name],$value);
  2798. $_REQUEST[$name]=$_GET[$name]=$value;
  2799. }
  2800. else
  2801. $_REQUEST[$key]=$_GET[$key]=$value;
  2802. }
  2803. }
  2804. public function createPathInfo($params,$equal,$ampersand, $key=null)
  2805. {
  2806. $pairs = array();
  2807. foreach($params as $k => $v)
  2808. {
  2809. if ($key!==null)
  2810. $k = $key.'['.$k.']';
  2811. if (is_array($v))
  2812. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  2813. else
  2814. $pairs[]=urlencode($k).$equal.urlencode($v);
  2815. }
  2816. return implode($ampersand,$pairs);
  2817. }
  2818. public function removeUrlSuffix($pathInfo,$urlSuffix)
  2819. {
  2820. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  2821. return substr($pathInfo,0,-strlen($urlSuffix));
  2822. else
  2823. return $pathInfo;
  2824. }
  2825. public function getBaseUrl()
  2826. {
  2827. if($this->_baseUrl!==null)
  2828. return $this->_baseUrl;
  2829. else
  2830. {
  2831. if($this->showScriptName)
  2832. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  2833. else
  2834. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  2835. return $this->_baseUrl;
  2836. }
  2837. }
  2838. public function setBaseUrl($value)
  2839. {
  2840. $this->_baseUrl=$value;
  2841. }
  2842. public function getUrlFormat()
  2843. {
  2844. return $this->_urlFormat;
  2845. }
  2846. public function setUrlFormat($value)
  2847. {
  2848. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  2849. $this->_urlFormat=$value;
  2850. else
  2851. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  2852. }
  2853. }
  2854. abstract class CBaseUrlRule extends CComponent
  2855. {
  2856. public $hasHostInfo=false;
  2857. abstract public function createUrl($manager,$route,$params,$ampersand);
  2858. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  2859. }
  2860. class CUrlRule extends CBaseUrlRule
  2861. {
  2862. public $urlSuffix;
  2863. public $caseSensitive;
  2864. public $defaultParams=array();
  2865. public $matchValue;
  2866. public $verb;
  2867. public $parsingOnly=false;
  2868. public $route;
  2869. public $references=array();
  2870. public $routePattern;
  2871. public $pattern;
  2872. public $template;
  2873. public $params=array();
  2874. public $append;
  2875. public $hasHostInfo;
  2876. public function __construct($route,$pattern)
  2877. {
  2878. if(is_array($route))
  2879. {
  2880. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  2881. {
  2882. if(isset($route[$name]))
  2883. $this->$name=$route[$name];
  2884. }
  2885. if(isset($route['pattern']))
  2886. $pattern=$route['pattern'];
  2887. $route=$route[0];
  2888. }
  2889. $this->route=trim($route,'/');
  2890. $tr2['/']=$tr['/']='\\/';
  2891. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  2892. {
  2893. foreach($matches2[1] as $name)
  2894. $this->references[$name]="<$name>";
  2895. }
  2896. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  2897. if($this->verb!==null)
  2898. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  2899. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  2900. {
  2901. $tokens=array_combine($matches[1],$matches[2]);
  2902. foreach($tokens as $name=>$value)
  2903. {
  2904. if($value==='')
  2905. $value='[^\/]+';
  2906. $tr["<$name>"]="(?P<$name>$value)";
  2907. if(isset($this->references[$name]))
  2908. $tr2["<$name>"]=$tr["<$name>"];
  2909. else
  2910. $this->params[$name]=$value;
  2911. }
  2912. }
  2913. $p=rtrim($pattern,'*');
  2914. $this->append=$p!==$pattern;
  2915. $p=trim($p,'/');
  2916. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  2917. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  2918. if($this->append)
  2919. $this->pattern.='/u';
  2920. else
  2921. $this->pattern.='$/u';
  2922. if($this->references!==array())
  2923. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  2924. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  2925. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  2926. array('{route}'=>$route,'{pattern}'=>$pattern)));
  2927. }
  2928. public function createUrl($manager,$route,$params,$ampersand)
  2929. {
  2930. if($this->parsingOnly)
  2931. return false;
  2932. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  2933. $case='';
  2934. else
  2935. $case='i';
  2936. $tr=array();
  2937. if($route!==$this->route)
  2938. {
  2939. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  2940. {
  2941. foreach($this->references as $key=>$name)
  2942. $tr[$name]=$matches[$key];
  2943. }
  2944. else
  2945. return false;
  2946. }
  2947. foreach($this->defaultParams as $key=>$value)
  2948. {
  2949. if(isset($params[$key]))
  2950. {
  2951. if($params[$key]==$value)
  2952. unset($params[$key]);
  2953. else
  2954. return false;
  2955. }
  2956. }
  2957. foreach($this->params as $key=>$value)
  2958. if(!isset($params[$key]))
  2959. return false;
  2960. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  2961. {
  2962. foreach($this->params as $key=>$value)
  2963. {
  2964. if(!preg_match('/'.$value.'/'.$case,$params[$key]))
  2965. return false;
  2966. }
  2967. }
  2968. foreach($this->params as $key=>$value)
  2969. {
  2970. $tr["<$key>"]=urlencode($params[$key]);
  2971. unset($params[$key]);
  2972. }
  2973. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  2974. $url=strtr($this->template,$tr);
  2975. if($this->hasHostInfo)
  2976. {
  2977. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  2978. if(stripos($url,$hostInfo)===0)
  2979. $url=substr($url,strlen($hostInfo));
  2980. }
  2981. if(empty($params))
  2982. return $url!=='' ? $url.$suffix : $url;
  2983. if($this->append)
  2984. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  2985. else
  2986. {
  2987. if($url!=='')
  2988. $url.=$suffix;
  2989. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  2990. }
  2991. return $url;
  2992. }
  2993. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  2994. {
  2995. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  2996. return false;
  2997. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  2998. $case='';
  2999. else
  3000. $case='i';
  3001. if($this->urlSuffix!==null)
  3002. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3003. // URL suffix required, but not found in the requested URL
  3004. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3005. {
  3006. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3007. if($urlSuffix!='' && $urlSuffix!=='/')
  3008. return false;
  3009. }
  3010. if($this->hasHostInfo)
  3011. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3012. $pathInfo.='/';
  3013. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3014. {
  3015. foreach($this->defaultParams as $name=>$value)
  3016. {
  3017. if(!isset($_GET[$name]))
  3018. $_REQUEST[$name]=$_GET[$name]=$value;
  3019. }
  3020. $tr=array();
  3021. foreach($matches as $key=>$value)
  3022. {
  3023. if(isset($this->references[$key]))
  3024. $tr[$this->references[$key]]=$value;
  3025. else if(isset($this->params[$key]))
  3026. $_REQUEST[$key]=$_GET[$key]=$value;
  3027. }
  3028. if($pathInfo!==$matches[0]) // there're additional GET params
  3029. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3030. if($this->routePattern!==null)
  3031. return strtr($this->route,$tr);
  3032. else
  3033. return $this->route;
  3034. }
  3035. else
  3036. return false;
  3037. }
  3038. }
  3039. abstract class CBaseController extends CComponent
  3040. {
  3041. private $_widgetStack=array();
  3042. abstract public function getViewFile($viewName);
  3043. public function renderFile($viewFile,$data=null,$return=false)
  3044. {
  3045. $widgetCount=count($this->_widgetStack);
  3046. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3047. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3048. else
  3049. $content=$this->renderInternal($viewFile,$data,$return);
  3050. if(count($this->_widgetStack)===$widgetCount)
  3051. return $content;
  3052. else
  3053. {
  3054. $widget=end($this->_widgetStack);
  3055. 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.',
  3056. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3057. }
  3058. }
  3059. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3060. {
  3061. // we use special variable names here to avoid conflict when extracting data
  3062. if(is_array($_data_))
  3063. extract($_data_,EXTR_PREFIX_SAME,'data');
  3064. else
  3065. $data=$_data_;
  3066. if($_return_)
  3067. {
  3068. ob_start();
  3069. ob_implicit_flush(false);
  3070. require($_viewFile_);
  3071. return ob_get_clean();
  3072. }
  3073. else
  3074. require($_viewFile_);
  3075. }
  3076. public function createWidget($className,$properties=array())
  3077. {
  3078. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3079. $widget->init();
  3080. return $widget;
  3081. }
  3082. public function widget($className,$properties=array(),$captureOutput=false)
  3083. {
  3084. if($captureOutput)
  3085. {
  3086. ob_start();
  3087. ob_implicit_flush(false);
  3088. $widget=$this->createWidget($className,$properties);
  3089. $widget->run();
  3090. return ob_get_clean();
  3091. }
  3092. else
  3093. {
  3094. $widget=$this->createWidget($className,$properties);
  3095. $widget->run();
  3096. return $widget;
  3097. }
  3098. }
  3099. public function beginWidget($className,$properties=array())
  3100. {
  3101. $widget=$this->createWidget($className,$properties);
  3102. $this->_widgetStack[]=$widget;
  3103. return $widget;
  3104. }
  3105. public function endWidget($id='')
  3106. {
  3107. if(($widget=array_pop($this->_widgetStack))!==null)
  3108. {
  3109. $widget->run();
  3110. return $widget;
  3111. }
  3112. else
  3113. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3114. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3115. }
  3116. public function beginClip($id,$properties=array())
  3117. {
  3118. $properties['id']=$id;
  3119. $this->beginWidget('CClipWidget',$properties);
  3120. }
  3121. public function endClip()
  3122. {
  3123. $this->endWidget('CClipWidget');
  3124. }
  3125. public function beginCache($id,$properties=array())
  3126. {
  3127. $properties['id']=$id;
  3128. $cache=$this->beginWidget('COutputCache',$properties);
  3129. if($cache->getIsContentCached())
  3130. {
  3131. $this->endCache();
  3132. return false;
  3133. }
  3134. else
  3135. return true;
  3136. }
  3137. public function endCache()
  3138. {
  3139. $this->endWidget('COutputCache');
  3140. }
  3141. public function beginContent($view=null,$data=array())
  3142. {
  3143. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3144. }
  3145. public function endContent()
  3146. {
  3147. $this->endWidget('CContentDecorator');
  3148. }
  3149. }
  3150. class CController extends CBaseController
  3151. {
  3152. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3153. public $layout;
  3154. public $defaultAction='index';
  3155. private $_id;
  3156. private $_action;
  3157. private $_pageTitle;
  3158. private $_cachingStack;
  3159. private $_clips;
  3160. private $_dynamicOutput;
  3161. private $_pageStates;
  3162. private $_module;
  3163. public function __construct($id,$module=null)
  3164. {
  3165. $this->_id=$id;
  3166. $this->_module=$module;
  3167. $this->attachBehaviors($this->behaviors());
  3168. }
  3169. public function init()
  3170. {
  3171. }
  3172. public function filters()
  3173. {
  3174. return array();
  3175. }
  3176. public function actions()
  3177. {
  3178. return array();
  3179. }
  3180. public function behaviors()
  3181. {
  3182. return array();
  3183. }
  3184. public function accessRules()
  3185. {
  3186. return array();
  3187. }
  3188. public function run($actionID)
  3189. {
  3190. if(($action=$this->createAction($actionID))!==null)
  3191. {
  3192. if(($parent=$this->getModule())===null)
  3193. $parent=Yii::app();
  3194. if($parent->beforeControllerAction($this,$action))
  3195. {
  3196. $this->runActionWithFilters($action,$this->filters());
  3197. $parent->afterControllerAction($this,$action);
  3198. }
  3199. }
  3200. else
  3201. $this->missingAction($actionID);
  3202. }
  3203. public function runActionWithFilters($action,$filters)
  3204. {
  3205. if(empty($filters))
  3206. $this->runAction($action);
  3207. else
  3208. {
  3209. $priorAction=$this->_action;
  3210. $this->_action=$action;
  3211. CFilterChain::create($this,$action,$filters)->run();
  3212. $this->_action=$priorAction;
  3213. }
  3214. }
  3215. public function runAction($action)
  3216. {
  3217. $priorAction=$this->_action;
  3218. $this->_action=$action;
  3219. if($this->beforeAction($action))
  3220. {
  3221. if($action->runWithParams($this->getActionParams())===false)
  3222. $this->invalidActionParams($action);
  3223. else
  3224. $this->afterAction($action);
  3225. }
  3226. $this->_action=$priorAction;
  3227. }
  3228. public function getActionParams()
  3229. {
  3230. return $_GET;
  3231. }
  3232. public function invalidActionParams($action)
  3233. {
  3234. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3235. }
  3236. public function processOutput($output)
  3237. {
  3238. Yii::app()->getClientScript()->render($output);
  3239. // if using page caching, we should delay dynamic output replacement
  3240. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3241. {
  3242. $output=$this->processDynamicOutput($output);
  3243. $this->_dynamicOutput=null;
  3244. }
  3245. if($this->_pageStates===null)
  3246. $this->_pageStates=$this->loadPageStates();
  3247. if(!empty($this->_pageStates))
  3248. $this->savePageStates($this->_pageStates,$output);
  3249. return $output;
  3250. }
  3251. public function processDynamicOutput($output)
  3252. {
  3253. if($this->_dynamicOutput)
  3254. {
  3255. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3256. }
  3257. return $output;
  3258. }
  3259. protected function replaceDynamicOutput($matches)
  3260. {
  3261. $content=$matches[0];
  3262. if(isset($this->_dynamicOutput[$matches[1]]))
  3263. {
  3264. $content=$this->_dynamicOutput[$matches[1]];
  3265. $this->_dynamicOutput[$matches[1]]=null;
  3266. }
  3267. return $content;
  3268. }
  3269. public function createAction($actionID)
  3270. {
  3271. if($actionID==='')
  3272. $actionID=$this->defaultAction;
  3273. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3274. return new CInlineAction($this,$actionID);
  3275. else
  3276. {
  3277. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3278. if($action!==null && !method_exists($action,'run'))
  3279. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3280. return $action;
  3281. }
  3282. }
  3283. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3284. {
  3285. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3286. {
  3287. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3288. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3289. }
  3290. else if($pos===false)
  3291. return null;
  3292. // the action is defined in a provider
  3293. $prefix=substr($actionID,0,$pos+1);
  3294. if(!isset($actionMap[$prefix]))
  3295. return null;
  3296. $actionID=(string)substr($actionID,$pos+1);
  3297. $provider=$actionMap[$prefix];
  3298. if(is_string($provider))
  3299. $providerType=$provider;
  3300. else if(is_array($provider) && isset($provider['class']))
  3301. {
  3302. $providerType=$provider['class'];
  3303. if(isset($provider[$actionID]))
  3304. {
  3305. if(is_string($provider[$actionID]))
  3306. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3307. else
  3308. $config=array_merge($provider[$actionID],$config);
  3309. }
  3310. }
  3311. else
  3312. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3313. $class=Yii::import($providerType,true);
  3314. $map=call_user_func(array($class,'actions'));
  3315. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3316. }
  3317. public function missingAction($actionID)
  3318. {
  3319. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3320. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3321. }
  3322. public function getAction()
  3323. {
  3324. return $this->_action;
  3325. }
  3326. public function setAction($value)
  3327. {
  3328. $this->_action=$value;
  3329. }
  3330. public function getId()
  3331. {
  3332. return $this->_id;
  3333. }
  3334. public function getUniqueId()
  3335. {
  3336. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3337. }
  3338. public function getRoute()
  3339. {
  3340. if(($action=$this->getAction())!==null)
  3341. return $this->getUniqueId().'/'.$action->getId();
  3342. else
  3343. return $this->getUniqueId();
  3344. }
  3345. public function getModule()
  3346. {
  3347. return $this->_module;
  3348. }
  3349. public function getViewPath()
  3350. {
  3351. if(($module=$this->getModule())===null)
  3352. $module=Yii::app();
  3353. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3354. }
  3355. public function getViewFile($viewName)
  3356. {
  3357. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3358. return $viewFile;
  3359. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3360. if(($module=$this->getModule())!==null)
  3361. $moduleViewPath=$module->getViewPath();
  3362. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3363. }
  3364. public function getLayoutFile($layoutName)
  3365. {
  3366. if($layoutName===false)
  3367. return false;
  3368. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3369. return $layoutFile;
  3370. if(empty($layoutName))
  3371. {
  3372. $module=$this->getModule();
  3373. while($module!==null)
  3374. {
  3375. if($module->layout===false)
  3376. return false;
  3377. if(!empty($module->layout))
  3378. break;
  3379. $module=$module->getParentModule();
  3380. }
  3381. if($module===null)
  3382. $module=Yii::app();
  3383. $layoutName=$module->layout;
  3384. }
  3385. else if(($module=$this->getModule())===null)
  3386. $module=Yii::app();
  3387. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3388. }
  3389. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3390. {
  3391. if(empty($viewName))
  3392. return false;
  3393. if($moduleViewPath===null)
  3394. $moduleViewPath=$basePath;
  3395. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3396. $extension=$renderer->fileExtension;
  3397. else
  3398. $extension='.php';
  3399. if($viewName[0]==='/')
  3400. {
  3401. if(strncmp($viewName,'//',2)===0)
  3402. $viewFile=$basePath.$viewName;
  3403. else
  3404. $viewFile=$moduleViewPath.$viewName;
  3405. }
  3406. else if(strpos($viewName,'.'))
  3407. $viewFile=Yii::getPathOfAlias($viewName);
  3408. else
  3409. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3410. if(is_file($viewFile.$extension))
  3411. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3412. else if($extension!=='.php' && is_file($viewFile.'.php'))
  3413. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3414. else
  3415. return false;
  3416. }
  3417. public function getClips()
  3418. {
  3419. if($this->_clips!==null)
  3420. return $this->_clips;
  3421. else
  3422. return $this->_clips=new CMap;
  3423. }
  3424. public function forward($route,$exit=true)
  3425. {
  3426. if(strpos($route,'/')===false)
  3427. $this->run($route);
  3428. else
  3429. {
  3430. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3431. $route=$module->getId().'/'.$route;
  3432. Yii::app()->runController($route);
  3433. }
  3434. if($exit)
  3435. Yii::app()->end();
  3436. }
  3437. public function render($view,$data=null,$return=false)
  3438. {
  3439. if($this->beforeRender($view))
  3440. {
  3441. $output=$this->renderPartial($view,$data,true);
  3442. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3443. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3444. $this->afterRender($view,$output);
  3445. $output=$this->processOutput($output);
  3446. if($return)
  3447. return $output;
  3448. else
  3449. echo $output;
  3450. }
  3451. }
  3452. protected function beforeRender($view)
  3453. {
  3454. return true;
  3455. }
  3456. protected function afterRender($view, &$output)
  3457. {
  3458. }
  3459. public function renderText($text,$return=false)
  3460. {
  3461. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3462. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3463. $text=$this->processOutput($text);
  3464. if($return)
  3465. return $text;
  3466. else
  3467. echo $text;
  3468. }
  3469. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3470. {
  3471. if(($viewFile=$this->getViewFile($view))!==false)
  3472. {
  3473. $output=$this->renderFile($viewFile,$data,true);
  3474. if($processOutput)
  3475. $output=$this->processOutput($output);
  3476. if($return)
  3477. return $output;
  3478. else
  3479. echo $output;
  3480. }
  3481. else
  3482. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3483. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3484. }
  3485. public function renderClip($name,$params=array(),$return=false)
  3486. {
  3487. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  3488. if($return)
  3489. return $text;
  3490. else
  3491. echo $text;
  3492. }
  3493. public function renderDynamic($callback)
  3494. {
  3495. $n=count($this->_dynamicOutput);
  3496. echo "<###dynamic-$n###>";
  3497. $params=func_get_args();
  3498. array_shift($params);
  3499. $this->renderDynamicInternal($callback,$params);
  3500. }
  3501. public function renderDynamicInternal($callback,$params)
  3502. {
  3503. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3504. if(is_string($callback) && method_exists($this,$callback))
  3505. $callback=array($this,$callback);
  3506. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3507. }
  3508. public function createUrl($route,$params=array(),$ampersand='&')
  3509. {
  3510. if($route==='')
  3511. $route=$this->getId().'/'.$this->getAction()->getId();
  3512. else if(strpos($route,'/')===false)
  3513. $route=$this->getId().'/'.$route;
  3514. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3515. $route=$module->getId().'/'.$route;
  3516. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3517. }
  3518. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3519. {
  3520. $url=$this->createUrl($route,$params,$ampersand);
  3521. if(strpos($url,'http')===0)
  3522. return $url;
  3523. else
  3524. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  3525. }
  3526. public function getPageTitle()
  3527. {
  3528. if($this->_pageTitle!==null)
  3529. return $this->_pageTitle;
  3530. else
  3531. {
  3532. $name=ucfirst(basename($this->getId()));
  3533. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3534. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3535. else
  3536. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3537. }
  3538. }
  3539. public function setPageTitle($value)
  3540. {
  3541. $this->_pageTitle=$value;
  3542. }
  3543. public function redirect($url,$terminate=true,$statusCode=302)
  3544. {
  3545. if(is_array($url))
  3546. {
  3547. $route=isset($url[0]) ? $url[0] : '';
  3548. $url=$this->createUrl($route,array_splice($url,1));
  3549. }
  3550. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  3551. }
  3552. public function refresh($terminate=true,$anchor='')
  3553. {
  3554. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  3555. }
  3556. public function recordCachingAction($context,$method,$params)
  3557. {
  3558. if($this->_cachingStack) // record only when there is an active output cache
  3559. {
  3560. foreach($this->_cachingStack as $cache)
  3561. $cache->recordAction($context,$method,$params);
  3562. }
  3563. }
  3564. public function getCachingStack($createIfNull=true)
  3565. {
  3566. if(!$this->_cachingStack)
  3567. $this->_cachingStack=new CStack;
  3568. return $this->_cachingStack;
  3569. }
  3570. public function isCachingStackEmpty()
  3571. {
  3572. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  3573. }
  3574. protected function beforeAction($action)
  3575. {
  3576. return true;
  3577. }
  3578. protected function afterAction($action)
  3579. {
  3580. }
  3581. public function filterPostOnly($filterChain)
  3582. {
  3583. if(Yii::app()->getRequest()->getIsPostRequest())
  3584. $filterChain->run();
  3585. else
  3586. throw new CHttpException(400,Yii::t('yii','Your request is not valid.'));
  3587. }
  3588. public function filterAjaxOnly($filterChain)
  3589. {
  3590. if(Yii::app()->getRequest()->getIsAjaxRequest())
  3591. $filterChain->run();
  3592. else
  3593. throw new CHttpException(400,Yii::t('yii','Your request is not valid.'));
  3594. }
  3595. public function filterAccessControl($filterChain)
  3596. {
  3597. $filter=new CAccessControlFilter;
  3598. $filter->setRules($this->accessRules());
  3599. $filter->filter($filterChain);
  3600. }
  3601. public function paginate($itemCount,$pageSize=null,$pageVar=null)
  3602. {
  3603. $pages=new CPagination($itemCount);
  3604. if($pageSize!==null)
  3605. $pages->pageSize=$pageSize;
  3606. if($pageVar!==null)
  3607. $pages->pageVar=$pageVar;
  3608. return $pages;
  3609. }
  3610. public function getPageState($name,$defaultValue=null)
  3611. {
  3612. if($this->_pageStates===null)
  3613. $this->_pageStates=$this->loadPageStates();
  3614. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  3615. }
  3616. public function setPageState($name,$value,$defaultValue=null)
  3617. {
  3618. if($this->_pageStates===null)
  3619. $this->_pageStates=$this->loadPageStates();
  3620. if($value===$defaultValue)
  3621. unset($this->_pageStates[$name]);
  3622. else
  3623. $this->_pageStates[$name]=$value;
  3624. $params=func_get_args();
  3625. $this->recordCachingAction('','setPageState',$params);
  3626. }
  3627. public function clearPageStates()
  3628. {
  3629. $this->_pageStates=array();
  3630. }
  3631. protected function loadPageStates()
  3632. {
  3633. if(!empty($_POST[self::STATE_INPUT_NAME]))
  3634. {
  3635. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  3636. {
  3637. if(extension_loaded('zlib'))
  3638. $data=@gzuncompress($data);
  3639. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  3640. return unserialize($data);
  3641. }
  3642. }
  3643. return array();
  3644. }
  3645. protected function savePageStates($states,&$output)
  3646. {
  3647. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  3648. if(extension_loaded('zlib'))
  3649. $data=gzcompress($data);
  3650. $value=base64_encode($data);
  3651. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  3652. }
  3653. }
  3654. abstract class CAction extends CComponent implements IAction
  3655. {
  3656. private $_id;
  3657. private $_controller;
  3658. public function __construct($controller,$id)
  3659. {
  3660. $this->_controller=$controller;
  3661. $this->_id=$id;
  3662. }
  3663. public function getController()
  3664. {
  3665. return $this->_controller;
  3666. }
  3667. public function getId()
  3668. {
  3669. return $this->_id;
  3670. }
  3671. public function runWithParams($params)
  3672. {
  3673. $method=new ReflectionMethod($this, 'run');
  3674. if($method->getNumberOfParameters()>0)
  3675. return $this->runWithParamsInternal($this, $method, $params);
  3676. else
  3677. return $this->run();
  3678. }
  3679. protected function runWithParamsInternal($object, $method, $params)
  3680. {
  3681. $ps=array();
  3682. foreach($method->getParameters() as $i=>$param)
  3683. {
  3684. $name=$param->getName();
  3685. if(isset($params[$name]))
  3686. {
  3687. if($param->isArray())
  3688. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  3689. else if(!is_array($params[$name]))
  3690. $ps[]=$params[$name];
  3691. else
  3692. return false;
  3693. }
  3694. else if($param->isDefaultValueAvailable())
  3695. $ps[]=$param->getDefaultValue();
  3696. else
  3697. return false;
  3698. }
  3699. $method->invokeArgs($object,$ps);
  3700. return true;
  3701. }
  3702. }
  3703. class CInlineAction extends CAction
  3704. {
  3705. public function run()
  3706. {
  3707. $method='action'.$this->getId();
  3708. $this->getController()->$method();
  3709. }
  3710. public function runWithParams($params)
  3711. {
  3712. $methodName='action'.$this->getId();
  3713. $controller=$this->getController();
  3714. $method=new ReflectionMethod($controller, $methodName);
  3715. if($method->getNumberOfParameters()>0)
  3716. return $this->runWithParamsInternal($controller, $method, $params);
  3717. else
  3718. return $controller->$methodName();
  3719. }
  3720. }
  3721. class CWebUser extends CApplicationComponent implements IWebUser
  3722. {
  3723. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  3724. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  3725. const STATES_VAR='__states';
  3726. const AUTH_TIMEOUT_VAR='__timeout';
  3727. public $allowAutoLogin=false;
  3728. public $guestName='Guest';
  3729. public $loginUrl=array('/site/login');
  3730. public $identityCookie;
  3731. public $authTimeout;
  3732. public $autoRenewCookie=false;
  3733. public $autoUpdateFlash=true;
  3734. private $_keyPrefix;
  3735. private $_access=array();
  3736. public function __get($name)
  3737. {
  3738. if($this->hasState($name))
  3739. return $this->getState($name);
  3740. else
  3741. return parent::__get($name);
  3742. }
  3743. public function __set($name,$value)
  3744. {
  3745. if($this->hasState($name))
  3746. $this->setState($name,$value);
  3747. else
  3748. parent::__set($name,$value);
  3749. }
  3750. public function __isset($name)
  3751. {
  3752. if($this->hasState($name))
  3753. return $this->getState($name)!==null;
  3754. else
  3755. return parent::__isset($name);
  3756. }
  3757. public function __unset($name)
  3758. {
  3759. if($this->hasState($name))
  3760. $this->setState($name,null);
  3761. else
  3762. parent::__unset($name);
  3763. }
  3764. public function init()
  3765. {
  3766. parent::init();
  3767. Yii::app()->getSession()->open();
  3768. if($this->getIsGuest() && $this->allowAutoLogin)
  3769. $this->restoreFromCookie();
  3770. else if($this->autoRenewCookie && $this->allowAutoLogin)
  3771. $this->renewCookie();
  3772. if($this->autoUpdateFlash)
  3773. $this->updateFlash();
  3774. $this->updateAuthStatus();
  3775. }
  3776. public function login($identity,$duration=0)
  3777. {
  3778. $id=$identity->getId();
  3779. $states=$identity->getPersistentStates();
  3780. if($this->beforeLogin($id,$states,false))
  3781. {
  3782. $this->changeIdentity($id,$identity->getName(),$states);
  3783. if($duration>0)
  3784. {
  3785. if($this->allowAutoLogin)
  3786. $this->saveToCookie($duration);
  3787. else
  3788. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  3789. array('{class}'=>get_class($this))));
  3790. }
  3791. $this->afterLogin(false);
  3792. }
  3793. }
  3794. public function logout($destroySession=true)
  3795. {
  3796. if($this->beforeLogout())
  3797. {
  3798. if($this->allowAutoLogin)
  3799. {
  3800. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  3801. if($this->identityCookie!==null)
  3802. {
  3803. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3804. $cookie->value=null;
  3805. $cookie->expire=0;
  3806. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  3807. }
  3808. }
  3809. if($destroySession)
  3810. Yii::app()->getSession()->destroy();
  3811. else
  3812. $this->clearStates();
  3813. $this->afterLogout();
  3814. }
  3815. }
  3816. public function getIsGuest()
  3817. {
  3818. return $this->getState('__id')===null;
  3819. }
  3820. public function getId()
  3821. {
  3822. return $this->getState('__id');
  3823. }
  3824. public function setId($value)
  3825. {
  3826. $this->setState('__id',$value);
  3827. }
  3828. public function getName()
  3829. {
  3830. if(($name=$this->getState('__name'))!==null)
  3831. return $name;
  3832. else
  3833. return $this->guestName;
  3834. }
  3835. public function setName($value)
  3836. {
  3837. $this->setState('__name',$value);
  3838. }
  3839. public function getReturnUrl($defaultUrl=null)
  3840. {
  3841. return $this->getState('__returnUrl', $defaultUrl===null ? Yii::app()->getRequest()->getScriptUrl() : CHtml::normalizeUrl($defaultUrl));
  3842. }
  3843. public function setReturnUrl($value)
  3844. {
  3845. $this->setState('__returnUrl',$value);
  3846. }
  3847. public function loginRequired()
  3848. {
  3849. $app=Yii::app();
  3850. $request=$app->getRequest();
  3851. if(!$request->getIsAjaxRequest())
  3852. $this->setReturnUrl($request->getUrl());
  3853. if(($url=$this->loginUrl)!==null)
  3854. {
  3855. if(is_array($url))
  3856. {
  3857. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  3858. $url=$app->createUrl($route,array_splice($url,1));
  3859. }
  3860. $request->redirect($url);
  3861. }
  3862. else
  3863. throw new CHttpException(403,Yii::t('yii','Login Required'));
  3864. }
  3865. protected function beforeLogin($id,$states,$fromCookie)
  3866. {
  3867. return true;
  3868. }
  3869. protected function afterLogin($fromCookie)
  3870. {
  3871. }
  3872. protected function beforeLogout()
  3873. {
  3874. return true;
  3875. }
  3876. protected function afterLogout()
  3877. {
  3878. }
  3879. protected function restoreFromCookie()
  3880. {
  3881. $app=Yii::app();
  3882. $cookie=$app->getRequest()->getCookies()->itemAt($this->getStateKeyPrefix());
  3883. if($cookie && !empty($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  3884. {
  3885. $data=@unserialize($data);
  3886. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3887. {
  3888. list($id,$name,$duration,$states)=$data;
  3889. if($this->beforeLogin($id,$states,true))
  3890. {
  3891. $this->changeIdentity($id,$name,$states);
  3892. if($this->autoRenewCookie)
  3893. {
  3894. $cookie->expire=time()+$duration;
  3895. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  3896. }
  3897. $this->afterLogin(true);
  3898. }
  3899. }
  3900. }
  3901. }
  3902. protected function renewCookie()
  3903. {
  3904. $cookies=Yii::app()->getRequest()->getCookies();
  3905. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  3906. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  3907. {
  3908. $data=@unserialize($data);
  3909. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  3910. {
  3911. $cookie->expire=time()+$data[2];
  3912. $cookies->add($cookie->name,$cookie);
  3913. }
  3914. }
  3915. }
  3916. protected function saveToCookie($duration)
  3917. {
  3918. $app=Yii::app();
  3919. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  3920. $cookie->expire=time()+$duration;
  3921. $data=array(
  3922. $this->getId(),
  3923. $this->getName(),
  3924. $duration,
  3925. $this->saveIdentityStates(),
  3926. );
  3927. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  3928. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  3929. }
  3930. protected function createIdentityCookie($name)
  3931. {
  3932. $cookie=new CHttpCookie($name,'');
  3933. if(is_array($this->identityCookie))
  3934. {
  3935. foreach($this->identityCookie as $name=>$value)
  3936. $cookie->$name=$value;
  3937. }
  3938. return $cookie;
  3939. }
  3940. public function getStateKeyPrefix()
  3941. {
  3942. if($this->_keyPrefix!==null)
  3943. return $this->_keyPrefix;
  3944. else
  3945. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  3946. }
  3947. public function setStateKeyPrefix($value)
  3948. {
  3949. $this->_keyPrefix=$value;
  3950. }
  3951. public function getState($key,$defaultValue=null)
  3952. {
  3953. $key=$this->getStateKeyPrefix().$key;
  3954. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  3955. }
  3956. public function setState($key,$value,$defaultValue=null)
  3957. {
  3958. $key=$this->getStateKeyPrefix().$key;
  3959. if($value===$defaultValue)
  3960. unset($_SESSION[$key]);
  3961. else
  3962. $_SESSION[$key]=$value;
  3963. }
  3964. public function hasState($key)
  3965. {
  3966. $key=$this->getStateKeyPrefix().$key;
  3967. return isset($_SESSION[$key]);
  3968. }
  3969. public function clearStates()
  3970. {
  3971. $keys=array_keys($_SESSION);
  3972. $prefix=$this->getStateKeyPrefix();
  3973. $n=strlen($prefix);
  3974. foreach($keys as $key)
  3975. {
  3976. if(!strncmp($key,$prefix,$n))
  3977. unset($_SESSION[$key]);
  3978. }
  3979. }
  3980. public function getFlashes($delete=true)
  3981. {
  3982. $flashes=array();
  3983. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  3984. $keys=array_keys($_SESSION);
  3985. $n=strlen($prefix);
  3986. foreach($keys as $key)
  3987. {
  3988. if(!strncmp($key,$prefix,$n))
  3989. {
  3990. $flashes[substr($key,$n)]=$_SESSION[$key];
  3991. if($delete)
  3992. unset($_SESSION[$key]);
  3993. }
  3994. }
  3995. if($delete)
  3996. $this->setState(self::FLASH_COUNTERS,array());
  3997. return $flashes;
  3998. }
  3999. public function getFlash($key,$defaultValue=null,$delete=true)
  4000. {
  4001. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4002. if($delete)
  4003. $this->setFlash($key,null);
  4004. return $value;
  4005. }
  4006. public function setFlash($key,$value,$defaultValue=null)
  4007. {
  4008. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4009. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4010. if($value===$defaultValue)
  4011. unset($counters[$key]);
  4012. else
  4013. $counters[$key]=0;
  4014. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4015. }
  4016. public function hasFlash($key)
  4017. {
  4018. return $this->getFlash($key, null, false)!==null;
  4019. }
  4020. protected function changeIdentity($id,$name,$states)
  4021. {
  4022. Yii::app()->getSession()->regenerateID();
  4023. $this->setId($id);
  4024. $this->setName($name);
  4025. $this->loadIdentityStates($states);
  4026. }
  4027. protected function saveIdentityStates()
  4028. {
  4029. $states=array();
  4030. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4031. $states[$name]=$this->getState($name);
  4032. return $states;
  4033. }
  4034. protected function loadIdentityStates($states)
  4035. {
  4036. $names=array();
  4037. if(is_array($states))
  4038. {
  4039. foreach($states as $name=>$value)
  4040. {
  4041. $this->setState($name,$value);
  4042. $names[$name]=true;
  4043. }
  4044. }
  4045. $this->setState(self::STATES_VAR,$names);
  4046. }
  4047. protected function updateFlash()
  4048. {
  4049. $counters=$this->getState(self::FLASH_COUNTERS);
  4050. if(!is_array($counters))
  4051. return;
  4052. foreach($counters as $key=>$count)
  4053. {
  4054. if($count)
  4055. {
  4056. unset($counters[$key]);
  4057. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4058. }
  4059. else
  4060. $counters[$key]++;
  4061. }
  4062. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4063. }
  4064. protected function updateAuthStatus()
  4065. {
  4066. if($this->authTimeout!==null && !$this->getIsGuest())
  4067. {
  4068. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4069. if ($expires!==null && $expires < time())
  4070. $this->logout(false);
  4071. else
  4072. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4073. }
  4074. }
  4075. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4076. {
  4077. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4078. return $this->_access[$operation];
  4079. else
  4080. return $this->_access[$operation]=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4081. }
  4082. }
  4083. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4084. {
  4085. public $autoStart=true;
  4086. public function init()
  4087. {
  4088. parent::init();
  4089. if($this->autoStart)
  4090. $this->open();
  4091. register_shutdown_function(array($this,'close'));
  4092. }
  4093. public function getUseCustomStorage()
  4094. {
  4095. return false;
  4096. }
  4097. public function open()
  4098. {
  4099. if($this->getUseCustomStorage())
  4100. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4101. if(@session_start()===false && YII_DEBUG)
  4102. {
  4103. $message=Yii::t('yii','Failed to start session.');
  4104. if(function_exists('error_get_last'))
  4105. {
  4106. $error=error_get_last();
  4107. if(isset($error['message']))
  4108. $message=$error['message'];
  4109. }
  4110. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4111. }
  4112. }
  4113. public function close()
  4114. {
  4115. if(session_id()!=='')
  4116. @session_write_close();
  4117. }
  4118. public function destroy()
  4119. {
  4120. if(session_id()!=='')
  4121. {
  4122. @session_unset();
  4123. @session_destroy();
  4124. }
  4125. }
  4126. public function getIsStarted()
  4127. {
  4128. return session_id()!=='';
  4129. }
  4130. public function getSessionID()
  4131. {
  4132. return session_id();
  4133. }
  4134. public function setSessionID($value)
  4135. {
  4136. session_id($value);
  4137. }
  4138. public function regenerateID($deleteOldSession=false)
  4139. {
  4140. session_regenerate_id($deleteOldSession);
  4141. }
  4142. public function getSessionName()
  4143. {
  4144. return session_name();
  4145. }
  4146. public function setSessionName($value)
  4147. {
  4148. session_name($value);
  4149. }
  4150. public function getSavePath()
  4151. {
  4152. return session_save_path();
  4153. }
  4154. public function setSavePath($value)
  4155. {
  4156. if(is_dir($value))
  4157. session_save_path($value);
  4158. else
  4159. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4160. array('{path}'=>$value)));
  4161. }
  4162. public function getCookieParams()
  4163. {
  4164. return session_get_cookie_params();
  4165. }
  4166. public function setCookieParams($value)
  4167. {
  4168. $data=session_get_cookie_params();
  4169. extract($data);
  4170. extract($value);
  4171. if(isset($httponly))
  4172. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4173. else
  4174. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4175. }
  4176. public function getCookieMode()
  4177. {
  4178. if(ini_get('session.use_cookies')==='0')
  4179. return 'none';
  4180. else if(ini_get('session.use_only_cookies')==='0')
  4181. return 'allow';
  4182. else
  4183. return 'only';
  4184. }
  4185. public function setCookieMode($value)
  4186. {
  4187. if($value==='none')
  4188. ini_set('session.use_cookies','0');
  4189. else if($value==='allow')
  4190. {
  4191. ini_set('session.use_cookies','1');
  4192. ini_set('session.use_only_cookies','0');
  4193. }
  4194. else if($value==='only')
  4195. {
  4196. ini_set('session.use_cookies','1');
  4197. ini_set('session.use_only_cookies','1');
  4198. }
  4199. else
  4200. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4201. }
  4202. public function getGCProbability()
  4203. {
  4204. return (int)ini_get('session.gc_probability');
  4205. }
  4206. public function setGCProbability($value)
  4207. {
  4208. $value=(int)$value;
  4209. if($value>=0 && $value<=100)
  4210. {
  4211. ini_set('session.gc_probability',$value);
  4212. ini_set('session.gc_divisor','100');
  4213. }
  4214. else
  4215. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be an integer between 0 and 100.',
  4216. array('{value}'=>$value)));
  4217. }
  4218. public function getUseTransparentSessionID()
  4219. {
  4220. return ini_get('session.use_trans_sid')==1;
  4221. }
  4222. public function setUseTransparentSessionID($value)
  4223. {
  4224. ini_set('session.use_trans_sid',$value?'1':'0');
  4225. }
  4226. public function getTimeout()
  4227. {
  4228. return (int)ini_get('session.gc_maxlifetime');
  4229. }
  4230. public function setTimeout($value)
  4231. {
  4232. ini_set('session.gc_maxlifetime',$value);
  4233. }
  4234. public function openSession($savePath,$sessionName)
  4235. {
  4236. return true;
  4237. }
  4238. public function closeSession()
  4239. {
  4240. return true;
  4241. }
  4242. public function readSession($id)
  4243. {
  4244. return '';
  4245. }
  4246. public function writeSession($id,$data)
  4247. {
  4248. return true;
  4249. }
  4250. public function destroySession($id)
  4251. {
  4252. return true;
  4253. }
  4254. public function gcSession($maxLifetime)
  4255. {
  4256. return true;
  4257. }
  4258. //------ The following methods enable CHttpSession to be CMap-like -----
  4259. public function getIterator()
  4260. {
  4261. return new CHttpSessionIterator;
  4262. }
  4263. public function getCount()
  4264. {
  4265. return count($_SESSION);
  4266. }
  4267. public function count()
  4268. {
  4269. return $this->getCount();
  4270. }
  4271. public function getKeys()
  4272. {
  4273. return array_keys($_SESSION);
  4274. }
  4275. public function get($key,$defaultValue=null)
  4276. {
  4277. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4278. }
  4279. public function itemAt($key)
  4280. {
  4281. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4282. }
  4283. public function add($key,$value)
  4284. {
  4285. $_SESSION[$key]=$value;
  4286. }
  4287. public function remove($key)
  4288. {
  4289. if(isset($_SESSION[$key]))
  4290. {
  4291. $value=$_SESSION[$key];
  4292. unset($_SESSION[$key]);
  4293. return $value;
  4294. }
  4295. else
  4296. return null;
  4297. }
  4298. public function clear()
  4299. {
  4300. foreach(array_keys($_SESSION) as $key)
  4301. unset($_SESSION[$key]);
  4302. }
  4303. public function contains($key)
  4304. {
  4305. return isset($_SESSION[$key]);
  4306. }
  4307. public function toArray()
  4308. {
  4309. return $_SESSION;
  4310. }
  4311. public function offsetExists($offset)
  4312. {
  4313. return isset($_SESSION[$offset]);
  4314. }
  4315. public function offsetGet($offset)
  4316. {
  4317. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4318. }
  4319. public function offsetSet($offset,$item)
  4320. {
  4321. $_SESSION[$offset]=$item;
  4322. }
  4323. public function offsetUnset($offset)
  4324. {
  4325. unset($_SESSION[$offset]);
  4326. }
  4327. }
  4328. class CHtml
  4329. {
  4330. const ID_PREFIX='yt';
  4331. public static $errorSummaryCss='errorSummary';
  4332. public static $errorMessageCss='errorMessage';
  4333. public static $errorCss='error';
  4334. public static $requiredCss='required';
  4335. public static $beforeRequiredLabel='';
  4336. public static $afterRequiredLabel=' <span class="required">*</span>';
  4337. public static $count=0;
  4338. public static function encode($text)
  4339. {
  4340. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4341. }
  4342. public static function decode($text)
  4343. {
  4344. return htmlspecialchars_decode($text,ENT_QUOTES);
  4345. }
  4346. public static function encodeArray($data)
  4347. {
  4348. $d=array();
  4349. foreach($data as $key=>$value)
  4350. {
  4351. if(is_string($key))
  4352. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4353. if(is_string($value))
  4354. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4355. else if(is_array($value))
  4356. $value=self::encodeArray($value);
  4357. $d[$key]=$value;
  4358. }
  4359. return $d;
  4360. }
  4361. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4362. {
  4363. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4364. if($content===false)
  4365. return $closeTag ? $html.' />' : $html.'>';
  4366. else
  4367. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4368. }
  4369. public static function openTag($tag,$htmlOptions=array())
  4370. {
  4371. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4372. }
  4373. public static function closeTag($tag)
  4374. {
  4375. return '</'.$tag.'>';
  4376. }
  4377. public static function cdata($text)
  4378. {
  4379. return '<![CDATA[' . $text . ']]>';
  4380. }
  4381. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4382. {
  4383. if($name!==null)
  4384. $options['name']=$name;
  4385. if($httpEquiv!==null)
  4386. $options['http-equiv']=$httpEquiv;
  4387. $options['content']=$content;
  4388. return self::tag('meta',$options);
  4389. }
  4390. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4391. {
  4392. if($relation!==null)
  4393. $options['rel']=$relation;
  4394. if($type!==null)
  4395. $options['type']=$type;
  4396. if($href!==null)
  4397. $options['href']=$href;
  4398. if($media!==null)
  4399. $options['media']=$media;
  4400. return self::tag('link',$options);
  4401. }
  4402. public static function css($text,$media='')
  4403. {
  4404. if($media!=='')
  4405. $media=' media="'.$media.'"';
  4406. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4407. }
  4408. public static function refresh($seconds, $url='')
  4409. {
  4410. $content="$seconds";
  4411. if($url!=='')
  4412. $content.=';'.self::normalizeUrl($url);
  4413. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4414. }
  4415. public static function cssFile($url,$media='')
  4416. {
  4417. if($media!=='')
  4418. $media=' media="'.$media.'"';
  4419. return '<link rel="stylesheet" type="text/css" href="'.self::encode($url).'"'.$media.' />';
  4420. }
  4421. public static function script($text)
  4422. {
  4423. return "<script type=\"text/javascript\">\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</script>";
  4424. }
  4425. public static function scriptFile($url)
  4426. {
  4427. return '<script type="text/javascript" src="'.self::encode($url).'"></script>';
  4428. }
  4429. public static function form($action='',$method='post',$htmlOptions=array())
  4430. {
  4431. return self::beginForm($action,$method,$htmlOptions);
  4432. }
  4433. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4434. {
  4435. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4436. $htmlOptions['method']=$method;
  4437. $form=self::tag('form',$htmlOptions,false,false);
  4438. $hiddens=array();
  4439. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4440. {
  4441. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4442. {
  4443. if(($pos=strpos($pair,'='))!==false)
  4444. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4445. }
  4446. }
  4447. $request=Yii::app()->request;
  4448. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4449. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4450. if($hiddens!==array())
  4451. $form.="\n".self::tag('div',array('style'=>'display:none'),implode("\n",$hiddens));
  4452. return $form;
  4453. }
  4454. public static function endForm()
  4455. {
  4456. return '</form>';
  4457. }
  4458. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4459. {
  4460. return self::form($action,$method,$htmlOptions)."\n".
  4461. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4462. }
  4463. public static function pageStateField($value)
  4464. {
  4465. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4466. }
  4467. public static function link($text,$url='#',$htmlOptions=array())
  4468. {
  4469. if($url!=='')
  4470. $htmlOptions['href']=self::normalizeUrl($url);
  4471. self::clientChange('click',$htmlOptions);
  4472. return self::tag('a',$htmlOptions,$text);
  4473. }
  4474. public static function mailto($text,$email='',$htmlOptions=array())
  4475. {
  4476. if($email==='')
  4477. $email=$text;
  4478. return self::link($text,'mailto:'.$email,$htmlOptions);
  4479. }
  4480. public static function image($src,$alt='',$htmlOptions=array())
  4481. {
  4482. $htmlOptions['src']=$src;
  4483. $htmlOptions['alt']=$alt;
  4484. return self::tag('img',$htmlOptions);
  4485. }
  4486. public static function button($label='button',$htmlOptions=array())
  4487. {
  4488. if(!isset($htmlOptions['name']))
  4489. {
  4490. if(!array_key_exists('name',$htmlOptions))
  4491. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4492. }
  4493. if(!isset($htmlOptions['type']))
  4494. $htmlOptions['type']='button';
  4495. if(!isset($htmlOptions['value']))
  4496. $htmlOptions['value']=$label;
  4497. self::clientChange('click',$htmlOptions);
  4498. return self::tag('input',$htmlOptions);
  4499. }
  4500. public static function htmlButton($label='button',$htmlOptions=array())
  4501. {
  4502. if(!isset($htmlOptions['name']))
  4503. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4504. if(!isset($htmlOptions['type']))
  4505. $htmlOptions['type']='button';
  4506. self::clientChange('click',$htmlOptions);
  4507. return self::tag('button',$htmlOptions,$label);
  4508. }
  4509. public static function submitButton($label='submit',$htmlOptions=array())
  4510. {
  4511. $htmlOptions['type']='submit';
  4512. return self::button($label,$htmlOptions);
  4513. }
  4514. public static function resetButton($label='reset',$htmlOptions=array())
  4515. {
  4516. $htmlOptions['type']='reset';
  4517. return self::button($label,$htmlOptions);
  4518. }
  4519. public static function imageButton($src,$htmlOptions=array())
  4520. {
  4521. $htmlOptions['src']=$src;
  4522. $htmlOptions['type']='image';
  4523. return self::button('submit',$htmlOptions);
  4524. }
  4525. public static function linkButton($label='submit',$htmlOptions=array())
  4526. {
  4527. if(!isset($htmlOptions['submit']))
  4528. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  4529. return self::link($label,'#',$htmlOptions);
  4530. }
  4531. public static function label($label,$for,$htmlOptions=array())
  4532. {
  4533. if($for===false)
  4534. unset($htmlOptions['for']);
  4535. else
  4536. $htmlOptions['for']=$for;
  4537. if(isset($htmlOptions['required']))
  4538. {
  4539. if($htmlOptions['required'])
  4540. {
  4541. if(isset($htmlOptions['class']))
  4542. $htmlOptions['class'].=' '.self::$requiredCss;
  4543. else
  4544. $htmlOptions['class']=self::$requiredCss;
  4545. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  4546. }
  4547. unset($htmlOptions['required']);
  4548. }
  4549. return self::tag('label',$htmlOptions,$label);
  4550. }
  4551. public static function textField($name,$value='',$htmlOptions=array())
  4552. {
  4553. self::clientChange('change',$htmlOptions);
  4554. return self::inputField('text',$name,$value,$htmlOptions);
  4555. }
  4556. public static function hiddenField($name,$value='',$htmlOptions=array())
  4557. {
  4558. return self::inputField('hidden',$name,$value,$htmlOptions);
  4559. }
  4560. public static function passwordField($name,$value='',$htmlOptions=array())
  4561. {
  4562. self::clientChange('change',$htmlOptions);
  4563. return self::inputField('password',$name,$value,$htmlOptions);
  4564. }
  4565. public static function fileField($name,$value='',$htmlOptions=array())
  4566. {
  4567. return self::inputField('file',$name,$value,$htmlOptions);
  4568. }
  4569. public static function textArea($name,$value='',$htmlOptions=array())
  4570. {
  4571. $htmlOptions['name']=$name;
  4572. if(!isset($htmlOptions['id']))
  4573. $htmlOptions['id']=self::getIdByName($name);
  4574. else if($htmlOptions['id']===false)
  4575. unset($htmlOptions['id']);
  4576. self::clientChange('change',$htmlOptions);
  4577. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  4578. }
  4579. public static function radioButton($name,$checked=false,$htmlOptions=array())
  4580. {
  4581. if($checked)
  4582. $htmlOptions['checked']='checked';
  4583. else
  4584. unset($htmlOptions['checked']);
  4585. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4586. self::clientChange('click',$htmlOptions);
  4587. if(array_key_exists('uncheckValue',$htmlOptions))
  4588. {
  4589. $uncheck=$htmlOptions['uncheckValue'];
  4590. unset($htmlOptions['uncheckValue']);
  4591. }
  4592. else
  4593. $uncheck=null;
  4594. if($uncheck!==null)
  4595. {
  4596. // add a hidden field so that if the radio button is not selected, it still submits a value
  4597. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4598. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4599. else
  4600. $uncheckOptions=array('id'=>false);
  4601. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4602. }
  4603. else
  4604. $hidden='';
  4605. // add a hidden field so that if the radio button is not selected, it still submits a value
  4606. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  4607. }
  4608. public static function checkBox($name,$checked=false,$htmlOptions=array())
  4609. {
  4610. if($checked)
  4611. $htmlOptions['checked']='checked';
  4612. else
  4613. unset($htmlOptions['checked']);
  4614. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  4615. self::clientChange('click',$htmlOptions);
  4616. if(array_key_exists('uncheckValue',$htmlOptions))
  4617. {
  4618. $uncheck=$htmlOptions['uncheckValue'];
  4619. unset($htmlOptions['uncheckValue']);
  4620. }
  4621. else
  4622. $uncheck=null;
  4623. if($uncheck!==null)
  4624. {
  4625. // add a hidden field so that if the radio button is not selected, it still submits a value
  4626. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  4627. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  4628. else
  4629. $uncheckOptions=array('id'=>false);
  4630. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  4631. }
  4632. else
  4633. $hidden='';
  4634. // add a hidden field so that if the checkbox is not selected, it still submits a value
  4635. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  4636. }
  4637. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  4638. {
  4639. $htmlOptions['name']=$name;
  4640. if(!isset($htmlOptions['id']))
  4641. $htmlOptions['id']=self::getIdByName($name);
  4642. else if($htmlOptions['id']===false)
  4643. unset($htmlOptions['id']);
  4644. self::clientChange('change',$htmlOptions);
  4645. $options="\n".self::listOptions($select,$data,$htmlOptions);
  4646. return self::tag('select',$htmlOptions,$options);
  4647. }
  4648. public static function listBox($name,$select,$data,$htmlOptions=array())
  4649. {
  4650. if(!isset($htmlOptions['size']))
  4651. $htmlOptions['size']=4;
  4652. if(isset($htmlOptions['multiple']))
  4653. {
  4654. if(substr($name,-2)!=='[]')
  4655. $name.='[]';
  4656. }
  4657. return self::dropDownList($name,$select,$data,$htmlOptions);
  4658. }
  4659. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  4660. {
  4661. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4662. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4663. unset($htmlOptions['template'],$htmlOptions['separator']);
  4664. if(substr($name,-2)!=='[]')
  4665. $name.='[]';
  4666. if(isset($htmlOptions['checkAll']))
  4667. {
  4668. $checkAllLabel=$htmlOptions['checkAll'];
  4669. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  4670. }
  4671. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  4672. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4673. unset($htmlOptions['labelOptions']);
  4674. $items=array();
  4675. $baseID=self::getIdByName($name);
  4676. $id=0;
  4677. $checkAll=true;
  4678. foreach($data as $value=>$label)
  4679. {
  4680. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  4681. $checkAll=$checkAll && $checked;
  4682. $htmlOptions['value']=$value;
  4683. $htmlOptions['id']=$baseID.'_'.$id++;
  4684. $option=self::checkBox($name,$checked,$htmlOptions);
  4685. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4686. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4687. }
  4688. if(isset($checkAllLabel))
  4689. {
  4690. $htmlOptions['value']=1;
  4691. $htmlOptions['id']=$id=$baseID.'_all';
  4692. $option=self::checkBox($id,$checkAll,$htmlOptions);
  4693. $label=self::label($checkAllLabel,$id,$labelOptions);
  4694. $item=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4695. if($checkAllLast)
  4696. $items[]=$item;
  4697. else
  4698. array_unshift($items,$item);
  4699. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  4700. $js=<<<EOD
  4701. jQuery('#$id').click(function() {
  4702. jQuery("input[name='$name']").attr('checked', this.checked);
  4703. });
  4704. jQuery("input[name='$name']").click(function() {
  4705. jQuery('#$id').attr('checked', !jQuery("input[name='$name']:not(:checked)").length);
  4706. });
  4707. jQuery('#$id').attr('checked', !jQuery("input[name='$name']:not(:checked)").length);
  4708. EOD;
  4709. $cs=Yii::app()->getClientScript();
  4710. $cs->registerCoreScript('jquery');
  4711. $cs->registerScript($id,$js);
  4712. }
  4713. return implode($separator,$items);
  4714. }
  4715. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  4716. {
  4717. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  4718. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:"<br/>\n";
  4719. unset($htmlOptions['template'],$htmlOptions['separator']);
  4720. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  4721. unset($htmlOptions['labelOptions']);
  4722. $items=array();
  4723. $baseID=self::getIdByName($name);
  4724. $id=0;
  4725. foreach($data as $value=>$label)
  4726. {
  4727. $checked=!strcmp($value,$select);
  4728. $htmlOptions['value']=$value;
  4729. $htmlOptions['id']=$baseID.'_'.$id++;
  4730. $option=self::radioButton($name,$checked,$htmlOptions);
  4731. $label=self::label($label,$htmlOptions['id'],$labelOptions);
  4732. $items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
  4733. }
  4734. return implode($separator,$items);
  4735. }
  4736. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  4737. {
  4738. if(!isset($htmlOptions['href']))
  4739. $htmlOptions['href']='#';
  4740. $ajaxOptions['url']=$url;
  4741. $htmlOptions['ajax']=$ajaxOptions;
  4742. self::clientChange('click',$htmlOptions);
  4743. return self::tag('a',$htmlOptions,$text);
  4744. }
  4745. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4746. {
  4747. $ajaxOptions['url']=$url;
  4748. $htmlOptions['ajax']=$ajaxOptions;
  4749. return self::button($label,$htmlOptions);
  4750. }
  4751. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  4752. {
  4753. $ajaxOptions['type']='POST';
  4754. $htmlOptions['type']='submit';
  4755. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  4756. }
  4757. public static function ajax($options)
  4758. {
  4759. Yii::app()->getClientScript()->registerCoreScript('jquery');
  4760. if(!isset($options['url']))
  4761. $options['url']='js:location.href';
  4762. else
  4763. $options['url']=self::normalizeUrl($options['url']);
  4764. if(!isset($options['cache']))
  4765. $options['cache']=false;
  4766. if(!isset($options['data']) && isset($options['type']))
  4767. $options['data']='js:jQuery(this).parents("form").serialize()';
  4768. foreach(array('beforeSend','complete','error','success') as $name)
  4769. {
  4770. if(isset($options[$name]) && strpos($options[$name],'js:')!==0)
  4771. $options[$name]='js:'.$options[$name];
  4772. }
  4773. if(isset($options['update']))
  4774. {
  4775. if(!isset($options['success']))
  4776. $options['success']='js:function(html){jQuery("'.$options['update'].'").html(html)}';
  4777. unset($options['update']);
  4778. }
  4779. if(isset($options['replace']))
  4780. {
  4781. if(!isset($options['success']))
  4782. $options['success']='js:function(html){jQuery("'.$options['replace'].'").replaceWith(html)}';
  4783. unset($options['replace']);
  4784. }
  4785. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  4786. }
  4787. public static function asset($path,$hashByName=false)
  4788. {
  4789. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  4790. }
  4791. public static function normalizeUrl($url)
  4792. {
  4793. if(is_array($url))
  4794. {
  4795. if(isset($url[0]))
  4796. {
  4797. if(($c=Yii::app()->getController())!==null)
  4798. $url=$c->createUrl($url[0],array_splice($url,1));
  4799. else
  4800. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  4801. }
  4802. else
  4803. $url='';
  4804. }
  4805. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  4806. }
  4807. protected static function inputField($type,$name,$value,$htmlOptions)
  4808. {
  4809. $htmlOptions['type']=$type;
  4810. $htmlOptions['value']=$value;
  4811. $htmlOptions['name']=$name;
  4812. if(!isset($htmlOptions['id']))
  4813. $htmlOptions['id']=self::getIdByName($name);
  4814. else if($htmlOptions['id']===false)
  4815. unset($htmlOptions['id']);
  4816. return self::tag('input',$htmlOptions);
  4817. }
  4818. public static function activeLabel($model,$attribute,$htmlOptions=array())
  4819. {
  4820. if(isset($htmlOptions['for']))
  4821. {
  4822. $for=$htmlOptions['for'];
  4823. unset($htmlOptions['for']);
  4824. }
  4825. else
  4826. $for=self::getIdByName(self::resolveName($model,$attribute));
  4827. if(isset($htmlOptions['label']))
  4828. {
  4829. if(($label=$htmlOptions['label'])===false)
  4830. return '';
  4831. unset($htmlOptions['label']);
  4832. }
  4833. else
  4834. $label=$model->getAttributeLabel($attribute);
  4835. if($model->hasErrors($attribute))
  4836. self::addErrorCss($htmlOptions);
  4837. return self::label($label,$for,$htmlOptions);
  4838. }
  4839. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  4840. {
  4841. $realAttribute=$attribute;
  4842. self::resolveName($model,$attribute); // strip off square brackets if any
  4843. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  4844. return self::activeLabel($model,$realAttribute,$htmlOptions);
  4845. }
  4846. public static function activeTextField($model,$attribute,$htmlOptions=array())
  4847. {
  4848. self::resolveNameID($model,$attribute,$htmlOptions);
  4849. self::clientChange('change',$htmlOptions);
  4850. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  4851. }
  4852. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  4853. {
  4854. self::resolveNameID($model,$attribute,$htmlOptions);
  4855. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  4856. }
  4857. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  4858. {
  4859. self::resolveNameID($model,$attribute,$htmlOptions);
  4860. self::clientChange('change',$htmlOptions);
  4861. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  4862. }
  4863. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  4864. {
  4865. self::resolveNameID($model,$attribute,$htmlOptions);
  4866. self::clientChange('change',$htmlOptions);
  4867. if($model->hasErrors($attribute))
  4868. self::addErrorCss($htmlOptions);
  4869. $text=self::resolveValue($model,$attribute);
  4870. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  4871. }
  4872. public static function activeFileField($model,$attribute,$htmlOptions=array())
  4873. {
  4874. self::resolveNameID($model,$attribute,$htmlOptions);
  4875. // add a hidden field so that if a model only has a file field, we can
  4876. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  4877. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4878. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  4879. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  4880. }
  4881. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  4882. {
  4883. self::resolveNameID($model,$attribute,$htmlOptions);
  4884. if(!isset($htmlOptions['value']))
  4885. $htmlOptions['value']=1;
  4886. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  4887. $htmlOptions['checked']='checked';
  4888. self::clientChange('click',$htmlOptions);
  4889. if(array_key_exists('uncheckValue',$htmlOptions))
  4890. {
  4891. $uncheck=$htmlOptions['uncheckValue'];
  4892. unset($htmlOptions['uncheckValue']);
  4893. }
  4894. else
  4895. $uncheck='0';
  4896. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4897. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  4898. // add a hidden field so that if the radio button is not selected, it still submits a value
  4899. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  4900. }
  4901. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  4902. {
  4903. self::resolveNameID($model,$attribute,$htmlOptions);
  4904. if(!isset($htmlOptions['value']))
  4905. $htmlOptions['value']=1;
  4906. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  4907. $htmlOptions['checked']='checked';
  4908. self::clientChange('click',$htmlOptions);
  4909. if(array_key_exists('uncheckValue',$htmlOptions))
  4910. {
  4911. $uncheck=$htmlOptions['uncheckValue'];
  4912. unset($htmlOptions['uncheckValue']);
  4913. }
  4914. else
  4915. $uncheck='0';
  4916. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4917. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  4918. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  4919. }
  4920. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  4921. {
  4922. self::resolveNameID($model,$attribute,$htmlOptions);
  4923. $selection=self::resolveValue($model,$attribute);
  4924. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  4925. self::clientChange('change',$htmlOptions);
  4926. if($model->hasErrors($attribute))
  4927. self::addErrorCss($htmlOptions);
  4928. if(isset($htmlOptions['multiple']))
  4929. {
  4930. if(substr($htmlOptions['name'],-2)!=='[]')
  4931. $htmlOptions['name'].='[]';
  4932. }
  4933. return self::tag('select',$htmlOptions,$options);
  4934. }
  4935. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  4936. {
  4937. if(!isset($htmlOptions['size']))
  4938. $htmlOptions['size']=4;
  4939. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  4940. }
  4941. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  4942. {
  4943. self::resolveNameID($model,$attribute,$htmlOptions);
  4944. $selection=self::resolveValue($model,$attribute);
  4945. if($model->hasErrors($attribute))
  4946. self::addErrorCss($htmlOptions);
  4947. $name=$htmlOptions['name'];
  4948. unset($htmlOptions['name']);
  4949. if(array_key_exists('uncheckValue',$htmlOptions))
  4950. {
  4951. $uncheck=$htmlOptions['uncheckValue'];
  4952. unset($htmlOptions['uncheckValue']);
  4953. }
  4954. else
  4955. $uncheck='';
  4956. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4957. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  4958. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  4959. }
  4960. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  4961. {
  4962. self::resolveNameID($model,$attribute,$htmlOptions);
  4963. $selection=self::resolveValue($model,$attribute);
  4964. if($model->hasErrors($attribute))
  4965. self::addErrorCss($htmlOptions);
  4966. $name=$htmlOptions['name'];
  4967. unset($htmlOptions['name']);
  4968. if(array_key_exists('uncheckValue',$htmlOptions))
  4969. {
  4970. $uncheck=$htmlOptions['uncheckValue'];
  4971. unset($htmlOptions['uncheckValue']);
  4972. }
  4973. else
  4974. $uncheck='';
  4975. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  4976. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  4977. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  4978. }
  4979. public static function getActiveId($model,$attribute)
  4980. {
  4981. return self::activeId($model,$attribute);
  4982. }
  4983. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  4984. {
  4985. $content='';
  4986. if(!is_array($model))
  4987. $model=array($model);
  4988. if(isset($htmlOptions['firstError']))
  4989. {
  4990. $firstError=$htmlOptions['firstError'];
  4991. unset($htmlOptions['firstError']);
  4992. }
  4993. else
  4994. $firstError=false;
  4995. foreach($model as $m)
  4996. {
  4997. foreach($m->getErrors() as $errors)
  4998. {
  4999. foreach($errors as $error)
  5000. {
  5001. if($error!='')
  5002. $content.="<li>$error</li>\n";
  5003. if($firstError)
  5004. break;
  5005. }
  5006. }
  5007. }
  5008. if($content!=='')
  5009. {
  5010. if($header===null)
  5011. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5012. if(!isset($htmlOptions['class']))
  5013. $htmlOptions['class']=self::$errorSummaryCss;
  5014. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5015. }
  5016. else
  5017. return '';
  5018. }
  5019. public static function error($model,$attribute,$htmlOptions=array())
  5020. {
  5021. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5022. $error=$model->getError($attribute);
  5023. if($error!='')
  5024. {
  5025. if(!isset($htmlOptions['class']))
  5026. $htmlOptions['class']=self::$errorMessageCss;
  5027. return self::tag('div',$htmlOptions,$error);
  5028. }
  5029. else
  5030. return '';
  5031. }
  5032. public static function listData($models,$valueField,$textField,$groupField='')
  5033. {
  5034. $listData=array();
  5035. if($groupField==='')
  5036. {
  5037. foreach($models as $model)
  5038. {
  5039. $value=self::value($model,$valueField);
  5040. $text=self::value($model,$textField);
  5041. $listData[$value]=$text;
  5042. }
  5043. }
  5044. else
  5045. {
  5046. foreach($models as $model)
  5047. {
  5048. $group=self::value($model,$groupField);
  5049. $value=self::value($model,$valueField);
  5050. $text=self::value($model,$textField);
  5051. $listData[$group][$value]=$text;
  5052. }
  5053. }
  5054. return $listData;
  5055. }
  5056. public static function value($model,$attribute,$defaultValue=null)
  5057. {
  5058. foreach(explode('.',$attribute) as $name)
  5059. {
  5060. if(is_object($model))
  5061. $model=$model->$name;
  5062. else if(is_array($model) && isset($model[$name]))
  5063. $model=$model[$name];
  5064. else
  5065. return $defaultValue;
  5066. }
  5067. return $model;
  5068. }
  5069. public static function getIdByName($name)
  5070. {
  5071. return str_replace(array('[]', '][', '[', ']'), array('', '_', '_', ''), $name);
  5072. }
  5073. public static function activeId($model,$attribute)
  5074. {
  5075. return self::getIdByName(self::activeName($model,$attribute));
  5076. }
  5077. public static function activeName($model,$attribute)
  5078. {
  5079. $a=$attribute; // because the attribute name may be changed by resolveName
  5080. return self::resolveName($model,$a);
  5081. }
  5082. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5083. {
  5084. $htmlOptions['type']=$type;
  5085. if($type==='text' || $type==='password')
  5086. {
  5087. if(!isset($htmlOptions['maxlength']))
  5088. {
  5089. foreach($model->getValidators($attribute) as $validator)
  5090. {
  5091. if($validator instanceof CStringValidator && $validator->max!==null)
  5092. {
  5093. $htmlOptions['maxlength']=$validator->max;
  5094. break;
  5095. }
  5096. }
  5097. }
  5098. else if($htmlOptions['maxlength']===false)
  5099. unset($htmlOptions['maxlength']);
  5100. }
  5101. if($type==='file')
  5102. unset($htmlOptions['value']);
  5103. else if(!isset($htmlOptions['value']))
  5104. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5105. if($model->hasErrors($attribute))
  5106. self::addErrorCss($htmlOptions);
  5107. return self::tag('input',$htmlOptions);
  5108. }
  5109. public static function listOptions($selection,$listData,&$htmlOptions)
  5110. {
  5111. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5112. $content='';
  5113. if(isset($htmlOptions['prompt']))
  5114. {
  5115. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5116. unset($htmlOptions['prompt']);
  5117. }
  5118. if(isset($htmlOptions['empty']))
  5119. {
  5120. if(!is_array($htmlOptions['empty']))
  5121. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5122. foreach($htmlOptions['empty'] as $value=>$label)
  5123. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;', '>'=>'&gt;'))."</option>\n";
  5124. unset($htmlOptions['empty']);
  5125. }
  5126. if(isset($htmlOptions['options']))
  5127. {
  5128. $options=$htmlOptions['options'];
  5129. unset($htmlOptions['options']);
  5130. }
  5131. else
  5132. $options=array();
  5133. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  5134. if(is_array($selection))
  5135. {
  5136. foreach($selection as $i=>$item)
  5137. {
  5138. if(is_object($item))
  5139. $selection[$i]=$item->$key;
  5140. }
  5141. }
  5142. else if(is_object($selection))
  5143. $selection=$selection->$key;
  5144. foreach($listData as $key=>$value)
  5145. {
  5146. if(is_array($value))
  5147. {
  5148. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  5149. $dummy=array('options'=>$options);
  5150. if(isset($htmlOptions['encode']))
  5151. $dummy['encode']=$htmlOptions['encode'];
  5152. $content.=self::listOptions($selection,$value,$dummy);
  5153. $content.='</optgroup>'."\n";
  5154. }
  5155. else
  5156. {
  5157. $attributes=array('value'=>(string)$key, 'encode'=>!$raw);
  5158. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  5159. $attributes['selected']='selected';
  5160. if(isset($options[$key]))
  5161. $attributes=array_merge($attributes,$options[$key]);
  5162. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  5163. }
  5164. }
  5165. unset($htmlOptions['key']);
  5166. return $content;
  5167. }
  5168. protected static function clientChange($event,&$htmlOptions)
  5169. {
  5170. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  5171. return;
  5172. if(isset($htmlOptions['live']))
  5173. {
  5174. $live=$htmlOptions['live'];
  5175. unset($htmlOptions['live']);
  5176. }
  5177. else
  5178. $live=true;
  5179. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  5180. $return='return true';
  5181. else
  5182. $return='return false';
  5183. if(isset($htmlOptions['on'.$event]))
  5184. {
  5185. $handler=trim($htmlOptions['on'.$event],';').';';
  5186. unset($htmlOptions['on'.$event]);
  5187. }
  5188. else
  5189. $handler='';
  5190. if(isset($htmlOptions['id']))
  5191. $id=$htmlOptions['id'];
  5192. else
  5193. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  5194. $cs=Yii::app()->getClientScript();
  5195. $cs->registerCoreScript('jquery');
  5196. if(isset($htmlOptions['submit']))
  5197. {
  5198. $cs->registerCoreScript('yii');
  5199. $request=Yii::app()->getRequest();
  5200. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  5201. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  5202. if(isset($htmlOptions['params']))
  5203. $params=CJavaScript::encode($htmlOptions['params']);
  5204. else
  5205. $params='{}';
  5206. if($htmlOptions['submit']!=='')
  5207. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  5208. else
  5209. $url='';
  5210. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  5211. }
  5212. if(isset($htmlOptions['ajax']))
  5213. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  5214. if(isset($htmlOptions['confirm']))
  5215. {
  5216. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  5217. if($handler!=='')
  5218. $handler="if($confirm) {".$handler."} else return false;";
  5219. else
  5220. $handler="return $confirm;";
  5221. }
  5222. if($live)
  5223. $cs->registerScript('Yii.CHtml.#'.$id,"jQuery('body').undelegate('#$id','$event').delegate('#$id','$event',function(){{$handler}});");
  5224. else
  5225. $cs->registerScript('Yii.CHtml.#'.$id,"jQuery('#$id').unbind('$event').bind('$event', function(){{$handler}});");
  5226. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  5227. }
  5228. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  5229. {
  5230. if(!isset($htmlOptions['name']))
  5231. $htmlOptions['name']=self::resolveName($model,$attribute);
  5232. if(!isset($htmlOptions['id']))
  5233. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  5234. else if($htmlOptions['id']===false)
  5235. unset($htmlOptions['id']);
  5236. }
  5237. public static function resolveName($model,&$attribute)
  5238. {
  5239. if(($pos=strpos($attribute,'['))!==false)
  5240. {
  5241. if($pos!==0) // e.g. name[a][b]
  5242. return get_class($model).'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5243. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5244. {
  5245. $sub=substr($attribute,0,$pos+1);
  5246. $attribute=substr($attribute,$pos+1);
  5247. return get_class($model).$sub.'['.$attribute.']';
  5248. }
  5249. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5250. {
  5251. $name=get_class($model).'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5252. $attribute=$matches[1];
  5253. return $name;
  5254. }
  5255. }
  5256. return get_class($model).'['.$attribute.']';
  5257. }
  5258. public static function resolveValue($model,$attribute)
  5259. {
  5260. if(($pos=strpos($attribute,'['))!==false)
  5261. {
  5262. if($pos===0) // [a]name[b][c], should ignore [a]
  5263. {
  5264. if(preg_match('/\](\w+)/',$attribute,$matches))
  5265. $attribute=$matches[1];
  5266. if(($pos=strpos($attribute,'['))===false)
  5267. return $model->$attribute;
  5268. }
  5269. $name=substr($attribute,0,$pos);
  5270. $value=$model->$name;
  5271. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5272. {
  5273. if(is_array($value) && isset($value[$id]))
  5274. $value=$value[$id];
  5275. else
  5276. return null;
  5277. }
  5278. return $value;
  5279. }
  5280. else
  5281. return $model->$attribute;
  5282. }
  5283. protected static function addErrorCss(&$htmlOptions)
  5284. {
  5285. if(isset($htmlOptions['class']))
  5286. $htmlOptions['class'].=' '.self::$errorCss;
  5287. else
  5288. $htmlOptions['class']=self::$errorCss;
  5289. }
  5290. public static function renderAttributes($htmlOptions)
  5291. {
  5292. static $specialAttributes=array(
  5293. 'checked'=>1,
  5294. 'declare'=>1,
  5295. 'defer'=>1,
  5296. 'disabled'=>1,
  5297. 'ismap'=>1,
  5298. 'multiple'=>1,
  5299. 'nohref'=>1,
  5300. 'noresize'=>1,
  5301. 'readonly'=>1,
  5302. 'selected'=>1,
  5303. );
  5304. if($htmlOptions===array())
  5305. return '';
  5306. $html='';
  5307. if(isset($htmlOptions['encode']))
  5308. {
  5309. $raw=!$htmlOptions['encode'];
  5310. unset($htmlOptions['encode']);
  5311. }
  5312. else
  5313. $raw=false;
  5314. if($raw)
  5315. {
  5316. foreach($htmlOptions as $name=>$value)
  5317. {
  5318. if(isset($specialAttributes[$name]))
  5319. {
  5320. if($value)
  5321. $html .= ' ' . $name . '="' . $name . '"';
  5322. }
  5323. else if($value!==null)
  5324. $html .= ' ' . $name . '="' . $value . '"';
  5325. }
  5326. }
  5327. else
  5328. {
  5329. foreach($htmlOptions as $name=>$value)
  5330. {
  5331. if(isset($specialAttributes[$name]))
  5332. {
  5333. if($value)
  5334. $html .= ' ' . $name . '="' . $name . '"';
  5335. }
  5336. else if($value!==null)
  5337. $html .= ' ' . $name . '="' . self::encode($value) . '"';
  5338. }
  5339. }
  5340. return $html;
  5341. }
  5342. }
  5343. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  5344. {
  5345. public $enableSkin=false;
  5346. public $widgets=array();
  5347. public $skinnableWidgets;
  5348. public $skinPath;
  5349. private $_skins=array(); // class name, skin name, property name => value
  5350. public function init()
  5351. {
  5352. parent::init();
  5353. if($this->enableSkin && $this->skinPath===null)
  5354. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  5355. }
  5356. public function createWidget($owner,$className,$properties=array())
  5357. {
  5358. $className=Yii::import($className,true);
  5359. $widget=new $className($owner);
  5360. if(isset($this->widgets[$className]))
  5361. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  5362. if($this->enableSkin)
  5363. {
  5364. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  5365. {
  5366. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  5367. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  5368. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  5369. }
  5370. }
  5371. foreach($properties as $name=>$value)
  5372. $widget->$name=$value;
  5373. return $widget;
  5374. }
  5375. protected function getSkin($className,$skinName)
  5376. {
  5377. if(!isset($this->_skins[$className][$skinName]))
  5378. {
  5379. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  5380. if(is_file($skinFile))
  5381. $this->_skins[$className]=require($skinFile);
  5382. else
  5383. $this->_skins[$className]=array();
  5384. if(($theme=Yii::app()->getTheme())!==null)
  5385. {
  5386. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  5387. if(is_file($skinFile))
  5388. {
  5389. $skins=require($skinFile);
  5390. foreach($skins as $name=>$skin)
  5391. $this->_skins[$className][$name]=$skin;
  5392. }
  5393. }
  5394. if(!isset($this->_skins[$className][$skinName]))
  5395. $this->_skins[$className][$skinName]=array();
  5396. }
  5397. return $this->_skins[$className][$skinName];
  5398. }
  5399. }
  5400. class CWidget extends CBaseController
  5401. {
  5402. public $actionPrefix;
  5403. public $skin='default';
  5404. private static $_viewPaths;
  5405. private static $_counter=0;
  5406. private $_id;
  5407. private $_owner;
  5408. public static function actions()
  5409. {
  5410. return array();
  5411. }
  5412. public function __construct($owner=null)
  5413. {
  5414. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  5415. }
  5416. public function getOwner()
  5417. {
  5418. return $this->_owner;
  5419. }
  5420. public function getId($autoGenerate=true)
  5421. {
  5422. if($this->_id!==null)
  5423. return $this->_id;
  5424. else if($autoGenerate)
  5425. return $this->_id='yw'.self::$_counter++;
  5426. }
  5427. public function setId($value)
  5428. {
  5429. $this->_id=$value;
  5430. }
  5431. public function getController()
  5432. {
  5433. if($this->_owner instanceof CController)
  5434. return $this->_owner;
  5435. else
  5436. return Yii::app()->getController();
  5437. }
  5438. public function init()
  5439. {
  5440. }
  5441. public function run()
  5442. {
  5443. }
  5444. public function getViewPath($checkTheme=false)
  5445. {
  5446. $className=get_class($this);
  5447. if(isset(self::$_viewPaths[$className]))
  5448. return self::$_viewPaths[$className];
  5449. else
  5450. {
  5451. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  5452. {
  5453. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  5454. if(strpos($className,'\\')!==false) // namespaced class
  5455. $path.=str_replace('\\','_',ltrim($className,'\\'));
  5456. else
  5457. $path.=$className;
  5458. if(is_dir($path))
  5459. return self::$_viewPaths[$className]=$path;
  5460. }
  5461. $class=new ReflectionClass($className);
  5462. return self::$_viewPaths[$className]=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  5463. }
  5464. }
  5465. public function getViewFile($viewName)
  5466. {
  5467. if(($renderer=Yii::app()->getViewRenderer())!==null)
  5468. $extension=$renderer->fileExtension;
  5469. else
  5470. $extension='.php';
  5471. if(strpos($viewName,'.')) // a path alias
  5472. $viewFile=Yii::getPathOfAlias($viewName);
  5473. else
  5474. {
  5475. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  5476. if(is_file($viewFile.$extension))
  5477. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5478. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5479. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5480. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  5481. }
  5482. if(is_file($viewFile.$extension))
  5483. return Yii::app()->findLocalizedFile($viewFile.$extension);
  5484. else if($extension!=='.php' && is_file($viewFile.'.php'))
  5485. return Yii::app()->findLocalizedFile($viewFile.'.php');
  5486. else
  5487. return false;
  5488. }
  5489. public function render($view,$data=null,$return=false)
  5490. {
  5491. if(($viewFile=$this->getViewFile($view))!==false)
  5492. return $this->renderFile($viewFile,$data,$return);
  5493. else
  5494. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  5495. array('{widget}'=>get_class($this), '{view}'=>$view)));
  5496. }
  5497. }
  5498. class CClientScript extends CApplicationComponent
  5499. {
  5500. const POS_HEAD=0;
  5501. const POS_BEGIN=1;
  5502. const POS_END=2;
  5503. const POS_LOAD=3;
  5504. const POS_READY=4;
  5505. public $enableJavaScript=true;
  5506. public $scriptMap=array();
  5507. public $packages=array();
  5508. public $corePackages;
  5509. protected $cssFiles=array();
  5510. protected $scriptFiles=array();
  5511. protected $scripts=array();
  5512. protected $metaTags=array();
  5513. protected $linkTags=array();
  5514. protected $css=array();
  5515. protected $hasScripts=false;
  5516. protected $coreScripts=array();
  5517. public $coreScriptPosition=self::POS_HEAD;
  5518. private $_baseUrl;
  5519. public function reset()
  5520. {
  5521. $this->hasScripts=false;
  5522. $this->coreScripts=array();
  5523. $this->cssFiles=array();
  5524. $this->css=array();
  5525. $this->scriptFiles=array();
  5526. $this->scripts=array();
  5527. $this->metaTags=array();
  5528. $this->linkTags=array();
  5529. $this->recordCachingAction('clientScript','reset',array());
  5530. }
  5531. public function render(&$output)
  5532. {
  5533. if(!$this->hasScripts)
  5534. return;
  5535. $this->renderCoreScripts();
  5536. if(!empty($this->scriptMap))
  5537. $this->remapScripts();
  5538. $this->unifyScripts();
  5539. $this->renderHead($output);
  5540. if($this->enableJavaScript)
  5541. {
  5542. $this->renderBodyBegin($output);
  5543. $this->renderBodyEnd($output);
  5544. }
  5545. }
  5546. protected function unifyScripts()
  5547. {
  5548. if(!$this->enableJavaScript)
  5549. return;
  5550. $map=array();
  5551. if(isset($this->scriptFiles[self::POS_HEAD]))
  5552. $map=$this->scriptFiles[self::POS_HEAD];
  5553. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5554. {
  5555. foreach($this->scriptFiles[self::POS_BEGIN] as $key=>$scriptFile)
  5556. {
  5557. if(isset($map[$scriptFile]))
  5558. unset($this->scriptFiles[self::POS_BEGIN][$key]);
  5559. else
  5560. $map[$scriptFile]=true;
  5561. }
  5562. }
  5563. if(isset($this->scriptFiles[self::POS_END]))
  5564. {
  5565. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  5566. {
  5567. if(isset($map[$scriptFile]))
  5568. unset($this->scriptFiles[self::POS_END][$key]);
  5569. }
  5570. }
  5571. }
  5572. protected function remapScripts()
  5573. {
  5574. $cssFiles=array();
  5575. foreach($this->cssFiles as $url=>$media)
  5576. {
  5577. $name=basename($url);
  5578. if(isset($this->scriptMap[$name]))
  5579. {
  5580. if($this->scriptMap[$name]!==false)
  5581. $cssFiles[$this->scriptMap[$name]]=$media;
  5582. }
  5583. else if(isset($this->scriptMap['*.css']))
  5584. {
  5585. if($this->scriptMap['*.css']!==false)
  5586. $cssFiles[$this->scriptMap['*.css']]=$media;
  5587. }
  5588. else
  5589. $cssFiles[$url]=$media;
  5590. }
  5591. $this->cssFiles=$cssFiles;
  5592. $jsFiles=array();
  5593. foreach($this->scriptFiles as $position=>$scripts)
  5594. {
  5595. $jsFiles[$position]=array();
  5596. foreach($scripts as $key=>$script)
  5597. {
  5598. $name=basename($script);
  5599. if(isset($this->scriptMap[$name]))
  5600. {
  5601. if($this->scriptMap[$name]!==false)
  5602. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  5603. }
  5604. else if(isset($this->scriptMap['*.js']))
  5605. {
  5606. if($this->scriptMap['*.js']!==false)
  5607. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  5608. }
  5609. else
  5610. $jsFiles[$position][$key]=$script;
  5611. }
  5612. }
  5613. $this->scriptFiles=$jsFiles;
  5614. }
  5615. public function renderCoreScripts()
  5616. {
  5617. if($this->coreScripts===null)
  5618. return;
  5619. $cssFiles=array();
  5620. $jsFiles=array();
  5621. foreach($this->coreScripts as $name=>$package)
  5622. {
  5623. $baseUrl=$this->getPackageBaseUrl($name);
  5624. if(!empty($package['js']))
  5625. {
  5626. foreach($package['js'] as $js)
  5627. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  5628. }
  5629. if(!empty($package['css']))
  5630. {
  5631. foreach($package['css'] as $css)
  5632. $cssFiles[$baseUrl.'/'.$css]='';
  5633. }
  5634. }
  5635. // merge in place
  5636. if($cssFiles!==array())
  5637. {
  5638. foreach($this->cssFiles as $cssFile=>$media)
  5639. $cssFiles[$cssFile]=$media;
  5640. $this->cssFiles=$cssFiles;
  5641. }
  5642. if($jsFiles!==array())
  5643. {
  5644. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  5645. {
  5646. foreach($this->scriptFiles[$this->coreScriptPosition] as $url)
  5647. $jsFiles[$url]=$url;
  5648. }
  5649. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  5650. }
  5651. }
  5652. public function renderHead(&$output)
  5653. {
  5654. $html='';
  5655. foreach($this->metaTags as $meta)
  5656. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  5657. foreach($this->linkTags as $link)
  5658. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  5659. foreach($this->cssFiles as $url=>$media)
  5660. $html.=CHtml::cssFile($url,$media)."\n";
  5661. foreach($this->css as $css)
  5662. $html.=CHtml::css($css[0],$css[1])."\n";
  5663. if($this->enableJavaScript)
  5664. {
  5665. if(isset($this->scriptFiles[self::POS_HEAD]))
  5666. {
  5667. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFile)
  5668. $html.=CHtml::scriptFile($scriptFile)."\n";
  5669. }
  5670. if(isset($this->scripts[self::POS_HEAD]))
  5671. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_HEAD]))."\n";
  5672. }
  5673. if($html!=='')
  5674. {
  5675. $count=0;
  5676. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  5677. if($count)
  5678. $output=str_replace('<###head###>',$html,$output);
  5679. else
  5680. $output=$html.$output;
  5681. }
  5682. }
  5683. public function renderBodyBegin(&$output)
  5684. {
  5685. $html='';
  5686. if(isset($this->scriptFiles[self::POS_BEGIN]))
  5687. {
  5688. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile)
  5689. $html.=CHtml::scriptFile($scriptFile)."\n";
  5690. }
  5691. if(isset($this->scripts[self::POS_BEGIN]))
  5692. $html.=CHtml::script(implode("\n",$this->scripts[self::POS_BEGIN]))."\n";
  5693. if($html!=='')
  5694. {
  5695. $count=0;
  5696. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  5697. if($count)
  5698. $output=str_replace('<###begin###>',$html,$output);
  5699. else
  5700. $output=$html.$output;
  5701. }
  5702. }
  5703. public function renderBodyEnd(&$output)
  5704. {
  5705. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  5706. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  5707. return;
  5708. $fullPage=0;
  5709. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  5710. $html='';
  5711. if(isset($this->scriptFiles[self::POS_END]))
  5712. {
  5713. foreach($this->scriptFiles[self::POS_END] as $scriptFile)
  5714. $html.=CHtml::scriptFile($scriptFile)."\n";
  5715. }
  5716. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  5717. if(isset($this->scripts[self::POS_READY]))
  5718. {
  5719. if($fullPage)
  5720. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  5721. else
  5722. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  5723. }
  5724. if(isset($this->scripts[self::POS_LOAD]))
  5725. {
  5726. if($fullPage)
  5727. $scripts[]="jQuery(window).load(function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  5728. else
  5729. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  5730. }
  5731. if(!empty($scripts))
  5732. $html.=CHtml::script(implode("\n",$scripts))."\n";
  5733. if($fullPage)
  5734. $output=str_replace('<###end###>',$html,$output);
  5735. else
  5736. $output=$output.$html;
  5737. }
  5738. public function getCoreScriptUrl()
  5739. {
  5740. if($this->_baseUrl!==null)
  5741. return $this->_baseUrl;
  5742. else
  5743. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  5744. }
  5745. public function setCoreScriptUrl($value)
  5746. {
  5747. $this->_baseUrl=$value;
  5748. }
  5749. public function getPackageBaseUrl($name)
  5750. {
  5751. if(!isset($this->coreScripts[$name]))
  5752. return false;
  5753. $package=$this->coreScripts[$name];
  5754. if(isset($package['baseUrl']))
  5755. {
  5756. $baseUrl=$package['baseUrl'];
  5757. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  5758. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  5759. $baseUrl=rtrim($baseUrl,'/');
  5760. }
  5761. else if(isset($package['basePath']))
  5762. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  5763. else
  5764. $baseUrl=$this->getCoreScriptUrl();
  5765. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  5766. }
  5767. public function registerPackage($name)
  5768. {
  5769. return $this->registerCoreScript($name);
  5770. }
  5771. public function registerCoreScript($name)
  5772. {
  5773. if(isset($this->coreScripts[$name]))
  5774. return $this;
  5775. if(isset($this->packages[$name]))
  5776. $package=$this->packages[$name];
  5777. else
  5778. {
  5779. if($this->corePackages===null)
  5780. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  5781. if(isset($this->corePackages[$name]))
  5782. $package=$this->corePackages[$name];
  5783. }
  5784. if(isset($package))
  5785. {
  5786. if(!empty($package['depends']))
  5787. {
  5788. foreach($package['depends'] as $p)
  5789. $this->registerCoreScript($p);
  5790. }
  5791. $this->coreScripts[$name]=$package;
  5792. $this->hasScripts=true;
  5793. $params=func_get_args();
  5794. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  5795. }
  5796. return $this;
  5797. }
  5798. public function registerCssFile($url,$media='')
  5799. {
  5800. $this->hasScripts=true;
  5801. $this->cssFiles[$url]=$media;
  5802. $params=func_get_args();
  5803. $this->recordCachingAction('clientScript','registerCssFile',$params);
  5804. return $this;
  5805. }
  5806. public function registerCss($id,$css,$media='')
  5807. {
  5808. $this->hasScripts=true;
  5809. $this->css[$id]=array($css,$media);
  5810. $params=func_get_args();
  5811. $this->recordCachingAction('clientScript','registerCss',$params);
  5812. return $this;
  5813. }
  5814. public function registerScriptFile($url,$position=self::POS_HEAD)
  5815. {
  5816. $this->hasScripts=true;
  5817. $this->scriptFiles[$position][$url]=$url;
  5818. $params=func_get_args();
  5819. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  5820. return $this;
  5821. }
  5822. public function registerScript($id,$script,$position=self::POS_READY)
  5823. {
  5824. $this->hasScripts=true;
  5825. $this->scripts[$position][$id]=$script;
  5826. if($position===self::POS_READY || $position===self::POS_LOAD)
  5827. $this->registerCoreScript('jquery');
  5828. $params=func_get_args();
  5829. $this->recordCachingAction('clientScript','registerScript',$params);
  5830. return $this;
  5831. }
  5832. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array())
  5833. {
  5834. $this->hasScripts=true;
  5835. if($name!==null)
  5836. $options['name']=$name;
  5837. if($httpEquiv!==null)
  5838. $options['http-equiv']=$httpEquiv;
  5839. $options['content']=$content;
  5840. $this->metaTags[serialize($options)]=$options;
  5841. $params=func_get_args();
  5842. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  5843. return $this;
  5844. }
  5845. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  5846. {
  5847. $this->hasScripts=true;
  5848. if($relation!==null)
  5849. $options['rel']=$relation;
  5850. if($type!==null)
  5851. $options['type']=$type;
  5852. if($href!==null)
  5853. $options['href']=$href;
  5854. if($media!==null)
  5855. $options['media']=$media;
  5856. $this->linkTags[serialize($options)]=$options;
  5857. $params=func_get_args();
  5858. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  5859. return $this;
  5860. }
  5861. public function isCssFileRegistered($url)
  5862. {
  5863. return isset($this->cssFiles[$url]);
  5864. }
  5865. public function isCssRegistered($id)
  5866. {
  5867. return isset($this->css[$id]);
  5868. }
  5869. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  5870. {
  5871. return isset($this->scriptFiles[$position][$url]);
  5872. }
  5873. public function isScriptRegistered($id,$position=self::POS_READY)
  5874. {
  5875. return isset($this->scripts[$position][$id]);
  5876. }
  5877. protected function recordCachingAction($context,$method,$params)
  5878. {
  5879. if(($controller=Yii::app()->getController())!==null)
  5880. $controller->recordCachingAction($context,$method,$params);
  5881. }
  5882. }
  5883. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  5884. {
  5885. private $_d=array();
  5886. private $_c=0;
  5887. private $_r=false;
  5888. public function __construct($data=null,$readOnly=false)
  5889. {
  5890. if($data!==null)
  5891. $this->copyFrom($data);
  5892. $this->setReadOnly($readOnly);
  5893. }
  5894. public function getReadOnly()
  5895. {
  5896. return $this->_r;
  5897. }
  5898. protected function setReadOnly($value)
  5899. {
  5900. $this->_r=$value;
  5901. }
  5902. public function getIterator()
  5903. {
  5904. return new CListIterator($this->_d);
  5905. }
  5906. public function count()
  5907. {
  5908. return $this->getCount();
  5909. }
  5910. public function getCount()
  5911. {
  5912. return $this->_c;
  5913. }
  5914. public function itemAt($index)
  5915. {
  5916. if(isset($this->_d[$index]))
  5917. return $this->_d[$index];
  5918. else if($index>=0 && $index<$this->_c) // in case the value is null
  5919. return $this->_d[$index];
  5920. else
  5921. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  5922. array('{index}'=>$index)));
  5923. }
  5924. public function add($item)
  5925. {
  5926. $this->insertAt($this->_c,$item);
  5927. return $this->_c-1;
  5928. }
  5929. public function insertAt($index,$item)
  5930. {
  5931. if(!$this->_r)
  5932. {
  5933. if($index===$this->_c)
  5934. $this->_d[$this->_c++]=$item;
  5935. else if($index>=0 && $index<$this->_c)
  5936. {
  5937. array_splice($this->_d,$index,0,array($item));
  5938. $this->_c++;
  5939. }
  5940. else
  5941. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  5942. array('{index}'=>$index)));
  5943. }
  5944. else
  5945. throw new CException(Yii::t('yii','The list is read only.'));
  5946. }
  5947. public function remove($item)
  5948. {
  5949. if(($index=$this->indexOf($item))>=0)
  5950. {
  5951. $this->removeAt($index);
  5952. return $index;
  5953. }
  5954. else
  5955. return false;
  5956. }
  5957. public function removeAt($index)
  5958. {
  5959. if(!$this->_r)
  5960. {
  5961. if($index>=0 && $index<$this->_c)
  5962. {
  5963. $this->_c--;
  5964. if($index===$this->_c)
  5965. return array_pop($this->_d);
  5966. else
  5967. {
  5968. $item=$this->_d[$index];
  5969. array_splice($this->_d,$index,1);
  5970. return $item;
  5971. }
  5972. }
  5973. else
  5974. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  5975. array('{index}'=>$index)));
  5976. }
  5977. else
  5978. throw new CException(Yii::t('yii','The list is read only.'));
  5979. }
  5980. public function clear()
  5981. {
  5982. for($i=$this->_c-1;$i>=0;--$i)
  5983. $this->removeAt($i);
  5984. }
  5985. public function contains($item)
  5986. {
  5987. return $this->indexOf($item)>=0;
  5988. }
  5989. public function indexOf($item)
  5990. {
  5991. if(($index=array_search($item,$this->_d,true))!==false)
  5992. return $index;
  5993. else
  5994. return -1;
  5995. }
  5996. public function toArray()
  5997. {
  5998. return $this->_d;
  5999. }
  6000. public function copyFrom($data)
  6001. {
  6002. if(is_array($data) || ($data instanceof Traversable))
  6003. {
  6004. if($this->_c>0)
  6005. $this->clear();
  6006. if($data instanceof CList)
  6007. $data=$data->_d;
  6008. foreach($data as $item)
  6009. $this->add($item);
  6010. }
  6011. else if($data!==null)
  6012. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6013. }
  6014. public function mergeWith($data)
  6015. {
  6016. if(is_array($data) || ($data instanceof Traversable))
  6017. {
  6018. if($data instanceof CList)
  6019. $data=$data->_d;
  6020. foreach($data as $item)
  6021. $this->add($item);
  6022. }
  6023. else if($data!==null)
  6024. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6025. }
  6026. public function offsetExists($offset)
  6027. {
  6028. return ($offset>=0 && $offset<$this->_c);
  6029. }
  6030. public function offsetGet($offset)
  6031. {
  6032. return $this->itemAt($offset);
  6033. }
  6034. public function offsetSet($offset,$item)
  6035. {
  6036. if($offset===null || $offset===$this->_c)
  6037. $this->insertAt($this->_c,$item);
  6038. else
  6039. {
  6040. $this->removeAt($offset);
  6041. $this->insertAt($offset,$item);
  6042. }
  6043. }
  6044. public function offsetUnset($offset)
  6045. {
  6046. $this->removeAt($offset);
  6047. }
  6048. }
  6049. class CFilterChain extends CList
  6050. {
  6051. public $controller;
  6052. public $action;
  6053. public $filterIndex=0;
  6054. public function __construct($controller,$action)
  6055. {
  6056. $this->controller=$controller;
  6057. $this->action=$action;
  6058. }
  6059. public static function create($controller,$action,$filters)
  6060. {
  6061. $chain=new CFilterChain($controller,$action);
  6062. $actionID=$action->getId();
  6063. foreach($filters as $filter)
  6064. {
  6065. if(is_string($filter)) // filterName [+|- action1 action2]
  6066. {
  6067. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  6068. {
  6069. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  6070. if(($filter[$pos]==='+')===$matched)
  6071. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  6072. }
  6073. else
  6074. $filter=CInlineFilter::create($controller,$filter);
  6075. }
  6076. else if(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  6077. {
  6078. if(!isset($filter[0]))
  6079. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  6080. $filterClass=$filter[0];
  6081. unset($filter[0]);
  6082. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  6083. {
  6084. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  6085. if(($filterClass[$pos]==='+')===$matched)
  6086. $filterClass=trim(substr($filterClass,0,$pos));
  6087. else
  6088. continue;
  6089. }
  6090. $filter['class']=$filterClass;
  6091. $filter=Yii::createComponent($filter);
  6092. }
  6093. if(is_object($filter))
  6094. {
  6095. $filter->init();
  6096. $chain->add($filter);
  6097. }
  6098. }
  6099. return $chain;
  6100. }
  6101. public function insertAt($index,$item)
  6102. {
  6103. if($item instanceof IFilter)
  6104. parent::insertAt($index,$item);
  6105. else
  6106. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  6107. }
  6108. public function run()
  6109. {
  6110. if($this->offsetExists($this->filterIndex))
  6111. {
  6112. $filter=$this->itemAt($this->filterIndex++);
  6113. $filter->filter($this);
  6114. }
  6115. else
  6116. $this->controller->runAction($this->action);
  6117. }
  6118. }
  6119. class CFilter extends CComponent implements IFilter
  6120. {
  6121. public function filter($filterChain)
  6122. {
  6123. if($this->preFilter($filterChain))
  6124. {
  6125. $filterChain->run();
  6126. $this->postFilter($filterChain);
  6127. }
  6128. }
  6129. public function init()
  6130. {
  6131. }
  6132. protected function preFilter($filterChain)
  6133. {
  6134. return true;
  6135. }
  6136. protected function postFilter($filterChain)
  6137. {
  6138. }
  6139. }
  6140. class CInlineFilter extends CFilter
  6141. {
  6142. public $name;
  6143. public static function create($controller,$filterName)
  6144. {
  6145. if(method_exists($controller,'filter'.$filterName))
  6146. {
  6147. $filter=new CInlineFilter;
  6148. $filter->name=$filterName;
  6149. return $filter;
  6150. }
  6151. else
  6152. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  6153. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  6154. }
  6155. public function filter($filterChain)
  6156. {
  6157. $method='filter'.$this->name;
  6158. $filterChain->controller->$method($filterChain);
  6159. }
  6160. }
  6161. class CAccessControlFilter extends CFilter
  6162. {
  6163. public $message;
  6164. private $_rules=array();
  6165. public function getRules()
  6166. {
  6167. return $this->_rules;
  6168. }
  6169. public function setRules($rules)
  6170. {
  6171. foreach($rules as $rule)
  6172. {
  6173. if(is_array($rule) && isset($rule[0]))
  6174. {
  6175. $r=new CAccessRule;
  6176. $r->allow=$rule[0]==='allow';
  6177. foreach(array_slice($rule,1) as $name=>$value)
  6178. {
  6179. if($name==='expression' || $name==='roles' || $name==='message')
  6180. $r->$name=$value;
  6181. else
  6182. $r->$name=array_map('strtolower',$value);
  6183. }
  6184. $this->_rules[]=$r;
  6185. }
  6186. }
  6187. }
  6188. protected function preFilter($filterChain)
  6189. {
  6190. $app=Yii::app();
  6191. $request=$app->getRequest();
  6192. $user=$app->getUser();
  6193. $verb=$request->getRequestType();
  6194. $ip=$request->getUserHostAddress();
  6195. foreach($this->getRules() as $rule)
  6196. {
  6197. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  6198. break;
  6199. else if($allow<0) // denied
  6200. {
  6201. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  6202. return false;
  6203. }
  6204. }
  6205. return true;
  6206. }
  6207. protected function resolveErrorMessage($rule)
  6208. {
  6209. if($rule->message!==null)
  6210. return $rule->message;
  6211. else if($this->message!==null)
  6212. return $this->message;
  6213. else
  6214. return Yii::t('yii','You are not authorized to perform this action.');
  6215. }
  6216. protected function accessDenied($user,$message)
  6217. {
  6218. if($user->getIsGuest())
  6219. $user->loginRequired();
  6220. else
  6221. throw new CHttpException(403,$message);
  6222. }
  6223. }
  6224. class CAccessRule extends CComponent
  6225. {
  6226. public $allow;
  6227. public $actions;
  6228. public $controllers;
  6229. public $users;
  6230. public $roles;
  6231. public $ips;
  6232. public $verbs;
  6233. public $expression;
  6234. public $message;
  6235. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  6236. {
  6237. if($this->isActionMatched($action)
  6238. && $this->isUserMatched($user)
  6239. && $this->isRoleMatched($user)
  6240. && $this->isIpMatched($ip)
  6241. && $this->isVerbMatched($verb)
  6242. && $this->isControllerMatched($controller)
  6243. && $this->isExpressionMatched($user))
  6244. return $this->allow ? 1 : -1;
  6245. else
  6246. return 0;
  6247. }
  6248. protected function isActionMatched($action)
  6249. {
  6250. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  6251. }
  6252. protected function isControllerMatched($controller)
  6253. {
  6254. return empty($this->controllers) || in_array(strtolower($controller->getId()),$this->controllers);
  6255. }
  6256. protected function isUserMatched($user)
  6257. {
  6258. if(empty($this->users))
  6259. return true;
  6260. foreach($this->users as $u)
  6261. {
  6262. if($u==='*')
  6263. return true;
  6264. else if($u==='?' && $user->getIsGuest())
  6265. return true;
  6266. else if($u==='@' && !$user->getIsGuest())
  6267. return true;
  6268. else if(!strcasecmp($u,$user->getName()))
  6269. return true;
  6270. }
  6271. return false;
  6272. }
  6273. protected function isRoleMatched($user)
  6274. {
  6275. if(empty($this->roles))
  6276. return true;
  6277. foreach($this->roles as $role)
  6278. {
  6279. if($user->checkAccess($role))
  6280. return true;
  6281. }
  6282. return false;
  6283. }
  6284. protected function isIpMatched($ip)
  6285. {
  6286. if(empty($this->ips))
  6287. return true;
  6288. foreach($this->ips as $rule)
  6289. {
  6290. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  6291. return true;
  6292. }
  6293. return false;
  6294. }
  6295. protected function isVerbMatched($verb)
  6296. {
  6297. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  6298. }
  6299. protected function isExpressionMatched($user)
  6300. {
  6301. if($this->expression===null)
  6302. return true;
  6303. else
  6304. return $this->evaluateExpression($this->expression, array('user'=>$user));
  6305. }
  6306. }
  6307. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  6308. {
  6309. private $_errors=array(); // attribute name => array of errors
  6310. private $_validators; // validators
  6311. private $_scenario=''; // scenario
  6312. abstract public function attributeNames();
  6313. public function rules()
  6314. {
  6315. return array();
  6316. }
  6317. public function behaviors()
  6318. {
  6319. return array();
  6320. }
  6321. public function attributeLabels()
  6322. {
  6323. return array();
  6324. }
  6325. public function validate($attributes=null, $clearErrors=true)
  6326. {
  6327. if($clearErrors)
  6328. $this->clearErrors();
  6329. if($this->beforeValidate())
  6330. {
  6331. foreach($this->getValidators() as $validator)
  6332. $validator->validate($this,$attributes);
  6333. $this->afterValidate();
  6334. return !$this->hasErrors();
  6335. }
  6336. else
  6337. return false;
  6338. }
  6339. protected function afterConstruct()
  6340. {
  6341. if($this->hasEventHandler('onAfterConstruct'))
  6342. $this->onAfterConstruct(new CEvent($this));
  6343. }
  6344. protected function beforeValidate()
  6345. {
  6346. $event=new CModelEvent($this);
  6347. $this->onBeforeValidate($event);
  6348. return $event->isValid;
  6349. }
  6350. protected function afterValidate()
  6351. {
  6352. $this->onAfterValidate(new CEvent($this));
  6353. }
  6354. public function onAfterConstruct($event)
  6355. {
  6356. $this->raiseEvent('onAfterConstruct',$event);
  6357. }
  6358. public function onBeforeValidate($event)
  6359. {
  6360. $this->raiseEvent('onBeforeValidate',$event);
  6361. }
  6362. public function onAfterValidate($event)
  6363. {
  6364. $this->raiseEvent('onAfterValidate',$event);
  6365. }
  6366. public function getValidatorList()
  6367. {
  6368. if($this->_validators===null)
  6369. $this->_validators=$this->createValidators();
  6370. return $this->_validators;
  6371. }
  6372. public function getValidators($attribute=null)
  6373. {
  6374. if($this->_validators===null)
  6375. $this->_validators=$this->createValidators();
  6376. $validators=array();
  6377. $scenario=$this->getScenario();
  6378. foreach($this->_validators as $validator)
  6379. {
  6380. if($validator->applyTo($scenario))
  6381. {
  6382. if($attribute===null || in_array($attribute,$validator->attributes,true))
  6383. $validators[]=$validator;
  6384. }
  6385. }
  6386. return $validators;
  6387. }
  6388. public function createValidators()
  6389. {
  6390. $validators=new CList;
  6391. foreach($this->rules() as $rule)
  6392. {
  6393. if(isset($rule[0],$rule[1])) // attributes, validator name
  6394. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  6395. else
  6396. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  6397. array('{class}'=>get_class($this))));
  6398. }
  6399. return $validators;
  6400. }
  6401. public function isAttributeRequired($attribute)
  6402. {
  6403. foreach($this->getValidators($attribute) as $validator)
  6404. {
  6405. if($validator instanceof CRequiredValidator)
  6406. return true;
  6407. }
  6408. return false;
  6409. }
  6410. public function isAttributeSafe($attribute)
  6411. {
  6412. $attributes=$this->getSafeAttributeNames();
  6413. return in_array($attribute,$attributes);
  6414. }
  6415. public function getAttributeLabel($attribute)
  6416. {
  6417. $labels=$this->attributeLabels();
  6418. if(isset($labels[$attribute]))
  6419. return $labels[$attribute];
  6420. else
  6421. return $this->generateAttributeLabel($attribute);
  6422. }
  6423. public function hasErrors($attribute=null)
  6424. {
  6425. if($attribute===null)
  6426. return $this->_errors!==array();
  6427. else
  6428. return isset($this->_errors[$attribute]);
  6429. }
  6430. public function getErrors($attribute=null)
  6431. {
  6432. if($attribute===null)
  6433. return $this->_errors;
  6434. else
  6435. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  6436. }
  6437. public function getError($attribute)
  6438. {
  6439. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  6440. }
  6441. public function addError($attribute,$error)
  6442. {
  6443. $this->_errors[$attribute][]=$error;
  6444. }
  6445. public function addErrors($errors)
  6446. {
  6447. foreach($errors as $attribute=>$error)
  6448. {
  6449. if(is_array($error))
  6450. {
  6451. foreach($error as $e)
  6452. $this->_errors[$attribute][]=$e;
  6453. }
  6454. else
  6455. $this->_errors[$attribute][]=$error;
  6456. }
  6457. }
  6458. public function clearErrors($attribute=null)
  6459. {
  6460. if($attribute===null)
  6461. $this->_errors=array();
  6462. else
  6463. unset($this->_errors[$attribute]);
  6464. }
  6465. public function generateAttributeLabel($name)
  6466. {
  6467. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  6468. }
  6469. public function getAttributes($names=null)
  6470. {
  6471. $values=array();
  6472. foreach($this->attributeNames() as $name)
  6473. $values[$name]=$this->$name;
  6474. if(is_array($names))
  6475. {
  6476. $values2=array();
  6477. foreach($names as $name)
  6478. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  6479. return $values2;
  6480. }
  6481. else
  6482. return $values;
  6483. }
  6484. public function setAttributes($values,$safeOnly=true)
  6485. {
  6486. if(!is_array($values))
  6487. return;
  6488. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  6489. foreach($values as $name=>$value)
  6490. {
  6491. if(isset($attributes[$name]))
  6492. $this->$name=$value;
  6493. else if($safeOnly)
  6494. $this->onUnsafeAttribute($name,$value);
  6495. }
  6496. }
  6497. public function unsetAttributes($names=null)
  6498. {
  6499. if($names===null)
  6500. $names=$this->attributeNames();
  6501. foreach($names as $name)
  6502. $this->$name=null;
  6503. }
  6504. public function onUnsafeAttribute($name,$value)
  6505. {
  6506. if(YII_DEBUG)
  6507. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  6508. }
  6509. public function getScenario()
  6510. {
  6511. return $this->_scenario;
  6512. }
  6513. public function setScenario($value)
  6514. {
  6515. $this->_scenario=$value;
  6516. }
  6517. public function getSafeAttributeNames()
  6518. {
  6519. $attributes=array();
  6520. $unsafe=array();
  6521. foreach($this->getValidators() as $validator)
  6522. {
  6523. if(!$validator->safe)
  6524. {
  6525. foreach($validator->attributes as $name)
  6526. $unsafe[]=$name;
  6527. }
  6528. else
  6529. {
  6530. foreach($validator->attributes as $name)
  6531. $attributes[$name]=true;
  6532. }
  6533. }
  6534. foreach($unsafe as $name)
  6535. unset($attributes[$name]);
  6536. return array_keys($attributes);
  6537. }
  6538. public function getIterator()
  6539. {
  6540. $attributes=$this->getAttributes();
  6541. return new CMapIterator($attributes);
  6542. }
  6543. public function offsetExists($offset)
  6544. {
  6545. return property_exists($this,$offset);
  6546. }
  6547. public function offsetGet($offset)
  6548. {
  6549. return $this->$offset;
  6550. }
  6551. public function offsetSet($offset,$item)
  6552. {
  6553. $this->$offset=$item;
  6554. }
  6555. public function offsetUnset($offset)
  6556. {
  6557. unset($this->$offset);
  6558. }
  6559. }
  6560. abstract class CActiveRecord extends CModel
  6561. {
  6562. const BELONGS_TO='CBelongsToRelation';
  6563. const HAS_ONE='CHasOneRelation';
  6564. const HAS_MANY='CHasManyRelation';
  6565. const MANY_MANY='CManyManyRelation';
  6566. const STAT='CStatRelation';
  6567. public static $db;
  6568. private static $_models=array(); // class name => model
  6569. private $_md; // meta data
  6570. private $_new=false; // whether this instance is new or not
  6571. private $_attributes=array(); // attribute name => attribute value
  6572. private $_related=array(); // attribute name => related objects
  6573. private $_c; // query criteria (used by finder only)
  6574. private $_pk; // old primary key value
  6575. private $_alias='t'; // the table alias being used for query
  6576. public function __construct($scenario='insert')
  6577. {
  6578. if($scenario===null) // internally used by populateRecord() and model()
  6579. return;
  6580. $this->setScenario($scenario);
  6581. $this->setIsNewRecord(true);
  6582. $this->_attributes=$this->getMetaData()->attributeDefaults;
  6583. $this->init();
  6584. $this->attachBehaviors($this->behaviors());
  6585. $this->afterConstruct();
  6586. }
  6587. public function init()
  6588. {
  6589. }
  6590. public function cache($duration, $dependency=null, $queryCount=1)
  6591. {
  6592. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  6593. return $this;
  6594. }
  6595. public function __sleep()
  6596. {
  6597. $this->_md=null;
  6598. return array_keys((array)$this);
  6599. }
  6600. public function __get($name)
  6601. {
  6602. if(isset($this->_attributes[$name]))
  6603. return $this->_attributes[$name];
  6604. else if(isset($this->getMetaData()->columns[$name]))
  6605. return null;
  6606. else if(isset($this->_related[$name]))
  6607. return $this->_related[$name];
  6608. else if(isset($this->getMetaData()->relations[$name]))
  6609. return $this->getRelated($name);
  6610. else
  6611. return parent::__get($name);
  6612. }
  6613. public function __set($name,$value)
  6614. {
  6615. if($this->setAttribute($name,$value)===false)
  6616. {
  6617. if(isset($this->getMetaData()->relations[$name]))
  6618. $this->_related[$name]=$value;
  6619. else
  6620. parent::__set($name,$value);
  6621. }
  6622. }
  6623. public function __isset($name)
  6624. {
  6625. if(isset($this->_attributes[$name]))
  6626. return true;
  6627. else if(isset($this->getMetaData()->columns[$name]))
  6628. return false;
  6629. else if(isset($this->_related[$name]))
  6630. return true;
  6631. else if(isset($this->getMetaData()->relations[$name]))
  6632. return $this->getRelated($name)!==null;
  6633. else
  6634. return parent::__isset($name);
  6635. }
  6636. public function __unset($name)
  6637. {
  6638. if(isset($this->getMetaData()->columns[$name]))
  6639. unset($this->_attributes[$name]);
  6640. else if(isset($this->getMetaData()->relations[$name]))
  6641. unset($this->_related[$name]);
  6642. else
  6643. parent::__unset($name);
  6644. }
  6645. public function __call($name,$parameters)
  6646. {
  6647. if(isset($this->getMetaData()->relations[$name]))
  6648. {
  6649. if(empty($parameters))
  6650. return $this->getRelated($name,false);
  6651. else
  6652. return $this->getRelated($name,false,$parameters[0]);
  6653. }
  6654. $scopes=$this->scopes();
  6655. if(isset($scopes[$name]))
  6656. {
  6657. $this->getDbCriteria()->mergeWith($scopes[$name]);
  6658. return $this;
  6659. }
  6660. return parent::__call($name,$parameters);
  6661. }
  6662. public function getRelated($name,$refresh=false,$params=array())
  6663. {
  6664. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  6665. return $this->_related[$name];
  6666. $md=$this->getMetaData();
  6667. if(!isset($md->relations[$name]))
  6668. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  6669. array('{class}'=>get_class($this), '{name}'=>$name)));
  6670. $relation=$md->relations[$name];
  6671. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  6672. return $relation instanceof CHasOneRelation ? null : array();
  6673. if($params!==array()) // dynamic query
  6674. {
  6675. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6676. if($exists)
  6677. $save=$this->_related[$name];
  6678. $r=array($name=>$params);
  6679. }
  6680. else
  6681. $r=$name;
  6682. unset($this->_related[$name]);
  6683. $finder=new CActiveFinder($this,$r);
  6684. $finder->lazyFind($this);
  6685. if(!isset($this->_related[$name]))
  6686. {
  6687. if($relation instanceof CHasManyRelation)
  6688. $this->_related[$name]=array();
  6689. else if($relation instanceof CStatRelation)
  6690. $this->_related[$name]=$relation->defaultValue;
  6691. else
  6692. $this->_related[$name]=null;
  6693. }
  6694. if($params!==array())
  6695. {
  6696. $results=$this->_related[$name];
  6697. if($exists)
  6698. $this->_related[$name]=$save;
  6699. else
  6700. unset($this->_related[$name]);
  6701. return $results;
  6702. }
  6703. else
  6704. return $this->_related[$name];
  6705. }
  6706. public function hasRelated($name)
  6707. {
  6708. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  6709. }
  6710. public function getDbCriteria($createIfNull=true)
  6711. {
  6712. if($this->_c===null)
  6713. {
  6714. if(($c=$this->defaultScope())!==array() || $createIfNull)
  6715. $this->_c=new CDbCriteria($c);
  6716. }
  6717. return $this->_c;
  6718. }
  6719. public function setDbCriteria($criteria)
  6720. {
  6721. $this->_c=$criteria;
  6722. }
  6723. public function defaultScope()
  6724. {
  6725. return array();
  6726. }
  6727. public function resetScope()
  6728. {
  6729. $this->_c=new CDbCriteria();
  6730. return $this;
  6731. }
  6732. public static function model($className=__CLASS__)
  6733. {
  6734. if(isset(self::$_models[$className]))
  6735. return self::$_models[$className];
  6736. else
  6737. {
  6738. $model=self::$_models[$className]=new $className(null);
  6739. $model->_md=new CActiveRecordMetaData($model);
  6740. $model->attachBehaviors($model->behaviors());
  6741. return $model;
  6742. }
  6743. }
  6744. public function getMetaData()
  6745. {
  6746. if($this->_md!==null)
  6747. return $this->_md;
  6748. else
  6749. return $this->_md=self::model(get_class($this))->_md;
  6750. }
  6751. public function refreshMetaData()
  6752. {
  6753. $finder=self::model(get_class($this));
  6754. $finder->_md=new CActiveRecordMetaData($finder);
  6755. if($this!==$finder)
  6756. $this->_md=$finder->_md;
  6757. }
  6758. public function tableName()
  6759. {
  6760. return get_class($this);
  6761. }
  6762. public function primaryKey()
  6763. {
  6764. }
  6765. public function relations()
  6766. {
  6767. return array();
  6768. }
  6769. public function scopes()
  6770. {
  6771. return array();
  6772. }
  6773. public function attributeNames()
  6774. {
  6775. return array_keys($this->getMetaData()->columns);
  6776. }
  6777. public function getAttributeLabel($attribute)
  6778. {
  6779. $labels=$this->attributeLabels();
  6780. if(isset($labels[$attribute]))
  6781. return $labels[$attribute];
  6782. else if(strpos($attribute,'.')!==false)
  6783. {
  6784. $segs=explode('.',$attribute);
  6785. $name=array_pop($segs);
  6786. $model=$this;
  6787. foreach($segs as $seg)
  6788. {
  6789. $relations=$model->getMetaData()->relations;
  6790. if(isset($relations[$seg]))
  6791. $model=CActiveRecord::model($relations[$seg]->className);
  6792. else
  6793. break;
  6794. }
  6795. return $model->getAttributeLabel($name);
  6796. }
  6797. else
  6798. return $this->generateAttributeLabel($attribute);
  6799. }
  6800. public function getDbConnection()
  6801. {
  6802. if(self::$db!==null)
  6803. return self::$db;
  6804. else
  6805. {
  6806. self::$db=Yii::app()->getDb();
  6807. if(self::$db instanceof CDbConnection)
  6808. return self::$db;
  6809. else
  6810. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  6811. }
  6812. }
  6813. public function getActiveRelation($name)
  6814. {
  6815. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  6816. }
  6817. public function getTableSchema()
  6818. {
  6819. return $this->getMetaData()->tableSchema;
  6820. }
  6821. public function getCommandBuilder()
  6822. {
  6823. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  6824. }
  6825. public function hasAttribute($name)
  6826. {
  6827. return isset($this->getMetaData()->columns[$name]);
  6828. }
  6829. public function getAttribute($name)
  6830. {
  6831. if(property_exists($this,$name))
  6832. return $this->$name;
  6833. else if(isset($this->_attributes[$name]))
  6834. return $this->_attributes[$name];
  6835. }
  6836. public function setAttribute($name,$value)
  6837. {
  6838. if(property_exists($this,$name))
  6839. $this->$name=$value;
  6840. else if(isset($this->getMetaData()->columns[$name]))
  6841. $this->_attributes[$name]=$value;
  6842. else
  6843. return false;
  6844. return true;
  6845. }
  6846. public function addRelatedRecord($name,$record,$index)
  6847. {
  6848. if($index!==false)
  6849. {
  6850. if(!isset($this->_related[$name]))
  6851. $this->_related[$name]=array();
  6852. if($record instanceof CActiveRecord)
  6853. {
  6854. if($index===true)
  6855. $this->_related[$name][]=$record;
  6856. else
  6857. $this->_related[$name][$index]=$record;
  6858. }
  6859. }
  6860. else if(!isset($this->_related[$name]))
  6861. $this->_related[$name]=$record;
  6862. }
  6863. public function getAttributes($names=true)
  6864. {
  6865. $attributes=$this->_attributes;
  6866. foreach($this->getMetaData()->columns as $name=>$column)
  6867. {
  6868. if(property_exists($this,$name))
  6869. $attributes[$name]=$this->$name;
  6870. else if($names===true && !isset($attributes[$name]))
  6871. $attributes[$name]=null;
  6872. }
  6873. if(is_array($names))
  6874. {
  6875. $attrs=array();
  6876. foreach($names as $name)
  6877. {
  6878. if(property_exists($this,$name))
  6879. $attrs[$name]=$this->$name;
  6880. else
  6881. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  6882. }
  6883. return $attrs;
  6884. }
  6885. else
  6886. return $attributes;
  6887. }
  6888. public function save($runValidation=true,$attributes=null)
  6889. {
  6890. if(!$runValidation || $this->validate($attributes))
  6891. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  6892. else
  6893. return false;
  6894. }
  6895. public function getIsNewRecord()
  6896. {
  6897. return $this->_new;
  6898. }
  6899. public function setIsNewRecord($value)
  6900. {
  6901. $this->_new=$value;
  6902. }
  6903. public function onBeforeSave($event)
  6904. {
  6905. $this->raiseEvent('onBeforeSave',$event);
  6906. }
  6907. public function onAfterSave($event)
  6908. {
  6909. $this->raiseEvent('onAfterSave',$event);
  6910. }
  6911. public function onBeforeDelete($event)
  6912. {
  6913. $this->raiseEvent('onBeforeDelete',$event);
  6914. }
  6915. public function onAfterDelete($event)
  6916. {
  6917. $this->raiseEvent('onAfterDelete',$event);
  6918. }
  6919. public function onBeforeFind($event)
  6920. {
  6921. $this->raiseEvent('onBeforeFind',$event);
  6922. }
  6923. public function onAfterFind($event)
  6924. {
  6925. $this->raiseEvent('onAfterFind',$event);
  6926. }
  6927. protected function beforeSave()
  6928. {
  6929. if($this->hasEventHandler('onBeforeSave'))
  6930. {
  6931. $event=new CModelEvent($this);
  6932. $this->onBeforeSave($event);
  6933. return $event->isValid;
  6934. }
  6935. else
  6936. return true;
  6937. }
  6938. protected function afterSave()
  6939. {
  6940. if($this->hasEventHandler('onAfterSave'))
  6941. $this->onAfterSave(new CEvent($this));
  6942. }
  6943. protected function beforeDelete()
  6944. {
  6945. if($this->hasEventHandler('onBeforeDelete'))
  6946. {
  6947. $event=new CModelEvent($this);
  6948. $this->onBeforeDelete($event);
  6949. return $event->isValid;
  6950. }
  6951. else
  6952. return true;
  6953. }
  6954. protected function afterDelete()
  6955. {
  6956. if($this->hasEventHandler('onAfterDelete'))
  6957. $this->onAfterDelete(new CEvent($this));
  6958. }
  6959. protected function beforeFind()
  6960. {
  6961. if($this->hasEventHandler('onBeforeFind'))
  6962. {
  6963. $event=new CModelEvent($this);
  6964. // for backward compatibility
  6965. $event->criteria=func_num_args()>0 ? func_get_arg(0) : null;
  6966. $this->onBeforeFind($event);
  6967. }
  6968. }
  6969. protected function afterFind()
  6970. {
  6971. if($this->hasEventHandler('onAfterFind'))
  6972. $this->onAfterFind(new CEvent($this));
  6973. }
  6974. public function beforeFindInternal()
  6975. {
  6976. $this->beforeFind();
  6977. }
  6978. public function afterFindInternal()
  6979. {
  6980. $this->afterFind();
  6981. }
  6982. public function insert($attributes=null)
  6983. {
  6984. if(!$this->getIsNewRecord())
  6985. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  6986. if($this->beforeSave())
  6987. {
  6988. $builder=$this->getCommandBuilder();
  6989. $table=$this->getMetaData()->tableSchema;
  6990. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  6991. if($command->execute())
  6992. {
  6993. $primaryKey=$table->primaryKey;
  6994. if($table->sequenceName!==null)
  6995. {
  6996. if(is_string($primaryKey) && $this->$primaryKey===null)
  6997. $this->$primaryKey=$builder->getLastInsertID($table);
  6998. else if(is_array($primaryKey))
  6999. {
  7000. foreach($primaryKey as $pk)
  7001. {
  7002. if($this->$pk===null)
  7003. {
  7004. $this->$pk=$builder->getLastInsertID($table);
  7005. break;
  7006. }
  7007. }
  7008. }
  7009. }
  7010. $this->_pk=$this->getPrimaryKey();
  7011. $this->afterSave();
  7012. $this->setIsNewRecord(false);
  7013. $this->setScenario('update');
  7014. return true;
  7015. }
  7016. }
  7017. return false;
  7018. }
  7019. public function update($attributes=null)
  7020. {
  7021. if($this->getIsNewRecord())
  7022. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7023. if($this->beforeSave())
  7024. {
  7025. if($this->_pk===null)
  7026. $this->_pk=$this->getPrimaryKey();
  7027. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  7028. $this->_pk=$this->getPrimaryKey();
  7029. $this->afterSave();
  7030. return true;
  7031. }
  7032. else
  7033. return false;
  7034. }
  7035. public function saveAttributes($attributes)
  7036. {
  7037. if(!$this->getIsNewRecord())
  7038. {
  7039. $values=array();
  7040. foreach($attributes as $name=>$value)
  7041. {
  7042. if(is_integer($name))
  7043. $values[$value]=$this->$value;
  7044. else
  7045. $values[$name]=$this->$name=$value;
  7046. }
  7047. if($this->_pk===null)
  7048. $this->_pk=$this->getPrimaryKey();
  7049. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  7050. {
  7051. $this->_pk=$this->getPrimaryKey();
  7052. return true;
  7053. }
  7054. else
  7055. return false;
  7056. }
  7057. else
  7058. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7059. }
  7060. public function saveCounters($counters)
  7061. {
  7062. $builder=$this->getCommandBuilder();
  7063. $table=$this->getTableSchema();
  7064. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  7065. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7066. if($command->execute())
  7067. {
  7068. foreach($counters as $name=>$value)
  7069. $this->$name=$this->$name+$value;
  7070. return true;
  7071. }
  7072. else
  7073. return false;
  7074. }
  7075. public function delete()
  7076. {
  7077. if(!$this->getIsNewRecord())
  7078. {
  7079. if($this->beforeDelete())
  7080. {
  7081. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  7082. $this->afterDelete();
  7083. return $result;
  7084. }
  7085. else
  7086. return false;
  7087. }
  7088. else
  7089. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  7090. }
  7091. public function refresh()
  7092. {
  7093. if(!$this->getIsNewRecord() && ($record=$this->findByPk($this->getPrimaryKey()))!==null)
  7094. {
  7095. $this->_attributes=array();
  7096. $this->_related=array();
  7097. foreach($this->getMetaData()->columns as $name=>$column)
  7098. {
  7099. if(property_exists($this,$name))
  7100. $this->$name=$record->$name;
  7101. else
  7102. $this->_attributes[$name]=$record->$name;
  7103. }
  7104. return true;
  7105. }
  7106. else
  7107. return false;
  7108. }
  7109. public function equals($record)
  7110. {
  7111. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  7112. }
  7113. public function getPrimaryKey()
  7114. {
  7115. $table=$this->getMetaData()->tableSchema;
  7116. if(is_string($table->primaryKey))
  7117. return $this->{$table->primaryKey};
  7118. else if(is_array($table->primaryKey))
  7119. {
  7120. $values=array();
  7121. foreach($table->primaryKey as $name)
  7122. $values[$name]=$this->$name;
  7123. return $values;
  7124. }
  7125. else
  7126. return null;
  7127. }
  7128. public function setPrimaryKey($value)
  7129. {
  7130. $this->_pk=$this->getPrimaryKey();
  7131. $table=$this->getMetaData()->tableSchema;
  7132. if(is_string($table->primaryKey))
  7133. $this->{$table->primaryKey}=$value;
  7134. else if(is_array($table->primaryKey))
  7135. {
  7136. foreach($table->primaryKey as $name)
  7137. $this->$name=$value[$name];
  7138. }
  7139. }
  7140. public function getOldPrimaryKey()
  7141. {
  7142. return $this->_pk;
  7143. }
  7144. public function setOldPrimaryKey($value)
  7145. {
  7146. $this->_pk=$value;
  7147. }
  7148. protected function query($criteria,$all=false)
  7149. {
  7150. $this->beforeFind();
  7151. $this->applyScopes($criteria);
  7152. if(empty($criteria->with))
  7153. {
  7154. if(!$all)
  7155. $criteria->limit=1;
  7156. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  7157. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  7158. }
  7159. else
  7160. {
  7161. $finder=new CActiveFinder($this,$criteria->with);
  7162. return $finder->query($criteria,$all);
  7163. }
  7164. }
  7165. public function applyScopes(&$criteria)
  7166. {
  7167. if(!empty($criteria->scopes))
  7168. {
  7169. $scs=$this->scopes();
  7170. $c=$this->getDbCriteria();
  7171. foreach((array)$criteria->scopes as $k=>$v)
  7172. {
  7173. if(is_integer($k))
  7174. {
  7175. if(is_string($v))
  7176. {
  7177. if(isset($scs[$v]))
  7178. {
  7179. $c->mergeWith($scs[$v],true);
  7180. continue;
  7181. }
  7182. $scope=$v;
  7183. $params=array();
  7184. }
  7185. else if(is_array($v))
  7186. {
  7187. $scope=key($v);
  7188. $params=current($v);
  7189. }
  7190. }
  7191. else if(is_string($k))
  7192. {
  7193. $scope=$k;
  7194. $params=$v;
  7195. }
  7196. call_user_func_array(array($this,$scope),(array)$params);
  7197. }
  7198. }
  7199. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  7200. {
  7201. $c->mergeWith($criteria);
  7202. $criteria=$c;
  7203. $this->_c=null;
  7204. }
  7205. }
  7206. public function getTableAlias($quote=false, $checkScopes=true)
  7207. {
  7208. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  7209. $alias=$criteria->alias;
  7210. else
  7211. $alias=$this->_alias;
  7212. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  7213. }
  7214. public function setTableAlias($alias)
  7215. {
  7216. $this->_alias=$alias;
  7217. }
  7218. public function find($condition='',$params=array())
  7219. {
  7220. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7221. return $this->query($criteria);
  7222. }
  7223. public function findAll($condition='',$params=array())
  7224. {
  7225. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  7226. return $this->query($criteria,true);
  7227. }
  7228. public function findByPk($pk,$condition='',$params=array())
  7229. {
  7230. $prefix=$this->getTableAlias(true).'.';
  7231. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7232. return $this->query($criteria);
  7233. }
  7234. public function findAllByPk($pk,$condition='',$params=array())
  7235. {
  7236. $prefix=$this->getTableAlias(true).'.';
  7237. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  7238. return $this->query($criteria,true);
  7239. }
  7240. public function findByAttributes($attributes,$condition='',$params=array())
  7241. {
  7242. $prefix=$this->getTableAlias(true).'.';
  7243. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7244. return $this->query($criteria);
  7245. }
  7246. public function findAllByAttributes($attributes,$condition='',$params=array())
  7247. {
  7248. $prefix=$this->getTableAlias(true).'.';
  7249. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7250. return $this->query($criteria,true);
  7251. }
  7252. public function findBySql($sql,$params=array())
  7253. {
  7254. $this->beforeFind();
  7255. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7256. {
  7257. $this->_c=null;
  7258. $finder=new CActiveFinder($this,$criteria->with);
  7259. return $finder->findBySql($sql,$params);
  7260. }
  7261. else
  7262. {
  7263. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7264. return $this->populateRecord($command->queryRow());
  7265. }
  7266. }
  7267. public function findAllBySql($sql,$params=array())
  7268. {
  7269. $this->beforeFind();
  7270. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  7271. {
  7272. $this->_c=null;
  7273. $finder=new CActiveFinder($this,$criteria->with);
  7274. return $finder->findAllBySql($sql,$params);
  7275. }
  7276. else
  7277. {
  7278. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  7279. return $this->populateRecords($command->queryAll());
  7280. }
  7281. }
  7282. public function count($condition='',$params=array())
  7283. {
  7284. $builder=$this->getCommandBuilder();
  7285. $criteria=$builder->createCriteria($condition,$params);
  7286. $this->applyScopes($criteria);
  7287. if(empty($criteria->with))
  7288. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7289. else
  7290. {
  7291. $finder=new CActiveFinder($this,$criteria->with);
  7292. return $finder->count($criteria);
  7293. }
  7294. }
  7295. public function countByAttributes($attributes,$condition='',$params=array())
  7296. {
  7297. $prefix=$this->getTableAlias(true).'.';
  7298. $builder=$this->getCommandBuilder();
  7299. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  7300. $this->applyScopes($criteria);
  7301. if(empty($criteria->with))
  7302. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  7303. else
  7304. {
  7305. $finder=new CActiveFinder($this,$criteria->with);
  7306. return $finder->count($criteria);
  7307. }
  7308. }
  7309. public function countBySql($sql,$params=array())
  7310. {
  7311. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  7312. }
  7313. public function exists($condition='',$params=array())
  7314. {
  7315. $builder=$this->getCommandBuilder();
  7316. $criteria=$builder->createCriteria($condition,$params);
  7317. $table=$this->getTableSchema();
  7318. $criteria->select='1';
  7319. $criteria->limit=1;
  7320. $this->applyScopes($criteria);
  7321. if(empty($criteria->with))
  7322. return $builder->createFindCommand($table,$criteria)->queryRow()!==false;
  7323. else
  7324. {
  7325. $criteria->select='*';
  7326. $finder=new CActiveFinder($this,$criteria->with);
  7327. return $finder->count($criteria)>0;
  7328. }
  7329. }
  7330. public function with()
  7331. {
  7332. if(func_num_args()>0)
  7333. {
  7334. $with=func_get_args();
  7335. if(is_array($with[0])) // the parameter is given as an array
  7336. $with=$with[0];
  7337. if(!empty($with))
  7338. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  7339. }
  7340. return $this;
  7341. }
  7342. public function together()
  7343. {
  7344. $this->getDbCriteria()->together=true;
  7345. return $this;
  7346. }
  7347. public function updateByPk($pk,$attributes,$condition='',$params=array())
  7348. {
  7349. $builder=$this->getCommandBuilder();
  7350. $table=$this->getTableSchema();
  7351. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  7352. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  7353. return $command->execute();
  7354. }
  7355. public function updateAll($attributes,$condition='',$params=array())
  7356. {
  7357. $builder=$this->getCommandBuilder();
  7358. $criteria=$builder->createCriteria($condition,$params);
  7359. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  7360. return $command->execute();
  7361. }
  7362. public function updateCounters($counters,$condition='',$params=array())
  7363. {
  7364. $builder=$this->getCommandBuilder();
  7365. $criteria=$builder->createCriteria($condition,$params);
  7366. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7367. return $command->execute();
  7368. }
  7369. public function deleteByPk($pk,$condition='',$params=array())
  7370. {
  7371. $builder=$this->getCommandBuilder();
  7372. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  7373. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7374. return $command->execute();
  7375. }
  7376. public function deleteAll($condition='',$params=array())
  7377. {
  7378. $builder=$this->getCommandBuilder();
  7379. $criteria=$builder->createCriteria($condition,$params);
  7380. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  7381. return $command->execute();
  7382. }
  7383. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  7384. {
  7385. $builder=$this->getCommandBuilder();
  7386. $table=$this->getTableSchema();
  7387. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  7388. $command=$builder->createDeleteCommand($table,$criteria);
  7389. return $command->execute();
  7390. }
  7391. public function populateRecord($attributes,$callAfterFind=true)
  7392. {
  7393. if($attributes!==false)
  7394. {
  7395. $record=$this->instantiate($attributes);
  7396. $record->setScenario('update');
  7397. $record->init();
  7398. $md=$record->getMetaData();
  7399. foreach($attributes as $name=>$value)
  7400. {
  7401. if(property_exists($record,$name))
  7402. $record->$name=$value;
  7403. else if(isset($md->columns[$name]))
  7404. $record->_attributes[$name]=$value;
  7405. }
  7406. $record->_pk=$record->getPrimaryKey();
  7407. $record->attachBehaviors($record->behaviors());
  7408. if($callAfterFind)
  7409. $record->afterFind();
  7410. return $record;
  7411. }
  7412. else
  7413. return null;
  7414. }
  7415. public function populateRecords($data,$callAfterFind=true,$index=null)
  7416. {
  7417. $records=array();
  7418. foreach($data as $attributes)
  7419. {
  7420. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  7421. {
  7422. if($index===null)
  7423. $records[]=$record;
  7424. else
  7425. $records[$record->$index]=$record;
  7426. }
  7427. }
  7428. return $records;
  7429. }
  7430. protected function instantiate($attributes)
  7431. {
  7432. $class=get_class($this);
  7433. $model=new $class(null);
  7434. return $model;
  7435. }
  7436. public function offsetExists($offset)
  7437. {
  7438. return $this->__isset($offset);
  7439. }
  7440. }
  7441. class CBaseActiveRelation extends CComponent
  7442. {
  7443. public $name;
  7444. public $className;
  7445. public $foreignKey;
  7446. public $select='*';
  7447. public $condition='';
  7448. public $params=array();
  7449. public $group='';
  7450. public $join='';
  7451. public $having='';
  7452. public $order='';
  7453. public function __construct($name,$className,$foreignKey,$options=array())
  7454. {
  7455. $this->name=$name;
  7456. $this->className=$className;
  7457. $this->foreignKey=$foreignKey;
  7458. foreach($options as $name=>$value)
  7459. $this->$name=$value;
  7460. }
  7461. public function mergeWith($criteria,$fromScope=false)
  7462. {
  7463. if($criteria instanceof CDbCriteria)
  7464. $criteria=$criteria->toArray();
  7465. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  7466. {
  7467. if($this->select==='*')
  7468. $this->select=$criteria['select'];
  7469. else if($criteria['select']!=='*')
  7470. {
  7471. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  7472. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  7473. $this->select=array_merge($select1,array_diff($select2,$select1));
  7474. }
  7475. }
  7476. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  7477. {
  7478. if($this->condition==='')
  7479. $this->condition=$criteria['condition'];
  7480. else if($criteria['condition']!=='')
  7481. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  7482. }
  7483. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  7484. $this->params=array_merge($this->params,$criteria['params']);
  7485. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  7486. {
  7487. if($this->order==='')
  7488. $this->order=$criteria['order'];
  7489. else if($criteria['order']!=='')
  7490. $this->order=$criteria['order'].', '.$this->order;
  7491. }
  7492. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  7493. {
  7494. if($this->group==='')
  7495. $this->group=$criteria['group'];
  7496. else if($criteria['group']!=='')
  7497. $this->group.=', '.$criteria['group'];
  7498. }
  7499. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  7500. {
  7501. if($this->join==='')
  7502. $this->join=$criteria['join'];
  7503. else if($criteria['join']!=='')
  7504. $this->join.=' '.$criteria['join'];
  7505. }
  7506. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  7507. {
  7508. if($this->having==='')
  7509. $this->having=$criteria['having'];
  7510. else if($criteria['having']!=='')
  7511. $this->having="({$this->having}) AND ({$criteria['having']})";
  7512. }
  7513. }
  7514. }
  7515. class CStatRelation extends CBaseActiveRelation
  7516. {
  7517. public $select='COUNT(*)';
  7518. public $defaultValue=0;
  7519. public function mergeWith($criteria,$fromScope=false)
  7520. {
  7521. if($criteria instanceof CDbCriteria)
  7522. $criteria=$criteria->toArray();
  7523. parent::mergeWith($criteria,$fromScope);
  7524. if(isset($criteria['defaultValue']))
  7525. $this->defaultValue=$criteria['defaultValue'];
  7526. }
  7527. }
  7528. class CActiveRelation extends CBaseActiveRelation
  7529. {
  7530. public $joinType='LEFT OUTER JOIN';
  7531. public $on='';
  7532. public $alias;
  7533. public $with=array();
  7534. public $together;
  7535. public function mergeWith($criteria,$fromScope=false)
  7536. {
  7537. if($criteria instanceof CDbCriteria)
  7538. $criteria=$criteria->toArray();
  7539. if($fromScope)
  7540. {
  7541. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  7542. {
  7543. if($this->on==='')
  7544. $this->on=$criteria['condition'];
  7545. else if($criteria['condition']!=='')
  7546. $this->on="({$this->on}) AND ({$criteria['condition']})";
  7547. }
  7548. unset($criteria['condition']);
  7549. }
  7550. parent::mergeWith($criteria);
  7551. if(isset($criteria['joinType']))
  7552. $this->joinType=$criteria['joinType'];
  7553. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  7554. {
  7555. if($this->on==='')
  7556. $this->on=$criteria['on'];
  7557. else if($criteria['on']!=='')
  7558. $this->on="({$this->on}) AND ({$criteria['on']})";
  7559. }
  7560. if(isset($criteria['with']))
  7561. $this->with=$criteria['with'];
  7562. if(isset($criteria['alias']))
  7563. $this->alias=$criteria['alias'];
  7564. if(isset($criteria['together']))
  7565. $this->together=$criteria['together'];
  7566. }
  7567. }
  7568. class CBelongsToRelation extends CActiveRelation
  7569. {
  7570. }
  7571. class CHasOneRelation extends CActiveRelation
  7572. {
  7573. public $through;
  7574. }
  7575. class CHasManyRelation extends CActiveRelation
  7576. {
  7577. public $limit=-1;
  7578. public $offset=-1;
  7579. public $index;
  7580. public $through;
  7581. public function mergeWith($criteria,$fromScope=false)
  7582. {
  7583. if($criteria instanceof CDbCriteria)
  7584. $criteria=$criteria->toArray();
  7585. parent::mergeWith($criteria,$fromScope);
  7586. if(isset($criteria['limit']) && $criteria['limit']>0)
  7587. $this->limit=$criteria['limit'];
  7588. if(isset($criteria['offset']) && $criteria['offset']>=0)
  7589. $this->offset=$criteria['offset'];
  7590. if(isset($criteria['index']))
  7591. $this->index=$criteria['index'];
  7592. }
  7593. }
  7594. class CManyManyRelation extends CHasManyRelation
  7595. {
  7596. }
  7597. class CActiveRecordMetaData
  7598. {
  7599. public $tableSchema;
  7600. public $columns;
  7601. public $relations=array();
  7602. public $attributeDefaults=array();
  7603. private $_model;
  7604. public function __construct($model)
  7605. {
  7606. $this->_model=$model;
  7607. $tableName=$model->tableName();
  7608. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  7609. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  7610. array('{class}'=>get_class($model),'{table}'=>$tableName)));
  7611. if($table->primaryKey===null)
  7612. {
  7613. $table->primaryKey=$model->primaryKey();
  7614. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  7615. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  7616. else if(is_array($table->primaryKey))
  7617. {
  7618. foreach($table->primaryKey as $name)
  7619. {
  7620. if(isset($table->columns[$name]))
  7621. $table->columns[$name]->isPrimaryKey=true;
  7622. }
  7623. }
  7624. }
  7625. $this->tableSchema=$table;
  7626. $this->columns=$table->columns;
  7627. foreach($table->columns as $name=>$column)
  7628. {
  7629. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  7630. $this->attributeDefaults[$name]=$column->defaultValue;
  7631. }
  7632. foreach($model->relations() as $name=>$config)
  7633. {
  7634. $this->addRelation($name,$config);
  7635. }
  7636. }
  7637. public function addRelation($name,$config)
  7638. {
  7639. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  7640. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  7641. else
  7642. 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)));
  7643. }
  7644. public function hasRelation($name)
  7645. {
  7646. return isset($this->relations[$name]);
  7647. }
  7648. public function removeRelation($name)
  7649. {
  7650. unset($this->relations[$name]);
  7651. }
  7652. }
  7653. class CDbConnection extends CApplicationComponent
  7654. {
  7655. public $connectionString;
  7656. public $username='';
  7657. public $password='';
  7658. public $schemaCachingDuration=0;
  7659. public $schemaCachingExclude=array();
  7660. public $schemaCacheID='cache';
  7661. public $queryCachingDuration=0;
  7662. public $queryCachingDependency;
  7663. public $queryCachingCount=0;
  7664. public $queryCacheID='cache';
  7665. public $autoConnect=true;
  7666. public $charset;
  7667. public $emulatePrepare;
  7668. public $enableParamLogging=false;
  7669. public $enableProfiling=false;
  7670. public $tablePrefix;
  7671. public $initSQLs;
  7672. public $driverMap=array(
  7673. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  7674. 'mysqli'=>'CMysqlSchema', // MySQL
  7675. 'mysql'=>'CMysqlSchema', // MySQL
  7676. 'sqlite'=>'CSqliteSchema', // sqlite 3
  7677. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  7678. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  7679. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  7680. 'sqlsrv'=>'CMssqlSchema', // Mssql
  7681. 'oci'=>'COciSchema', // Oracle driver
  7682. );
  7683. public $pdoClass = 'PDO';
  7684. private $_attributes=array();
  7685. private $_active=false;
  7686. private $_pdo;
  7687. private $_transaction;
  7688. private $_schema;
  7689. public function __construct($dsn='',$username='',$password='')
  7690. {
  7691. $this->connectionString=$dsn;
  7692. $this->username=$username;
  7693. $this->password=$password;
  7694. }
  7695. public function __sleep()
  7696. {
  7697. $this->close();
  7698. return array_keys(get_object_vars($this));
  7699. }
  7700. public static function getAvailableDrivers()
  7701. {
  7702. return PDO::getAvailableDrivers();
  7703. }
  7704. public function init()
  7705. {
  7706. parent::init();
  7707. if($this->autoConnect)
  7708. $this->setActive(true);
  7709. }
  7710. public function getActive()
  7711. {
  7712. return $this->_active;
  7713. }
  7714. public function setActive($value)
  7715. {
  7716. if($value!=$this->_active)
  7717. {
  7718. if($value)
  7719. $this->open();
  7720. else
  7721. $this->close();
  7722. }
  7723. }
  7724. public function cache($duration, $dependency=null, $queryCount=1)
  7725. {
  7726. $this->queryCachingDuration=$duration;
  7727. $this->queryCachingDependency=$dependency;
  7728. $this->queryCachingCount=$queryCount;
  7729. return $this;
  7730. }
  7731. protected function open()
  7732. {
  7733. if($this->_pdo===null)
  7734. {
  7735. if(empty($this->connectionString))
  7736. throw new CDbException(Yii::t('yii','CDbConnection.connectionString cannot be empty.'));
  7737. try
  7738. {
  7739. $this->_pdo=$this->createPdoInstance();
  7740. $this->initConnection($this->_pdo);
  7741. $this->_active=true;
  7742. }
  7743. catch(PDOException $e)
  7744. {
  7745. if(YII_DEBUG)
  7746. {
  7747. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection: {error}',
  7748. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$e->errorInfo);
  7749. }
  7750. else
  7751. {
  7752. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  7753. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'),(int)$e->getCode(),$e->errorInfo);
  7754. }
  7755. }
  7756. }
  7757. }
  7758. protected function close()
  7759. {
  7760. $this->_pdo=null;
  7761. $this->_active=false;
  7762. $this->_schema=null;
  7763. }
  7764. protected function createPdoInstance()
  7765. {
  7766. $pdoClass=$this->pdoClass;
  7767. if(($pos=strpos($this->connectionString,':'))!==false)
  7768. {
  7769. $driver=strtolower(substr($this->connectionString,0,$pos));
  7770. if($driver==='mssql' || $driver==='dblib' || $driver==='sqlsrv')
  7771. $pdoClass='CMssqlPdoAdapter';
  7772. }
  7773. return new $pdoClass($this->connectionString,$this->username,
  7774. $this->password,$this->_attributes);
  7775. }
  7776. protected function initConnection($pdo)
  7777. {
  7778. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  7779. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  7780. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  7781. if($this->charset!==null)
  7782. {
  7783. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  7784. if(in_array($driver,array('pgsql','mysql','mysqli')))
  7785. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  7786. }
  7787. if($this->initSQLs!==null)
  7788. {
  7789. foreach($this->initSQLs as $sql)
  7790. $pdo->exec($sql);
  7791. }
  7792. }
  7793. public function getPdoInstance()
  7794. {
  7795. return $this->_pdo;
  7796. }
  7797. public function createCommand($query=null)
  7798. {
  7799. $this->setActive(true);
  7800. return new CDbCommand($this,$query);
  7801. }
  7802. public function getCurrentTransaction()
  7803. {
  7804. if($this->_transaction!==null)
  7805. {
  7806. if($this->_transaction->getActive())
  7807. return $this->_transaction;
  7808. }
  7809. return null;
  7810. }
  7811. public function beginTransaction()
  7812. {
  7813. $this->setActive(true);
  7814. $this->_pdo->beginTransaction();
  7815. return $this->_transaction=new CDbTransaction($this);
  7816. }
  7817. public function getSchema()
  7818. {
  7819. if($this->_schema!==null)
  7820. return $this->_schema;
  7821. else
  7822. {
  7823. $driver=$this->getDriverName();
  7824. if(isset($this->driverMap[$driver]))
  7825. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  7826. else
  7827. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  7828. array('{driver}'=>$driver)));
  7829. }
  7830. }
  7831. public function getCommandBuilder()
  7832. {
  7833. return $this->getSchema()->getCommandBuilder();
  7834. }
  7835. public function getLastInsertID($sequenceName='')
  7836. {
  7837. $this->setActive(true);
  7838. return $this->_pdo->lastInsertId($sequenceName);
  7839. }
  7840. public function quoteValue($str)
  7841. {
  7842. if(is_int($str) || is_float($str))
  7843. return $str;
  7844. $this->setActive(true);
  7845. if(($value=$this->_pdo->quote($str))!==false)
  7846. return $value;
  7847. else // the driver doesn't support quote (e.g. oci)
  7848. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  7849. }
  7850. public function quoteTableName($name)
  7851. {
  7852. return $this->getSchema()->quoteTableName($name);
  7853. }
  7854. public function quoteColumnName($name)
  7855. {
  7856. return $this->getSchema()->quoteColumnName($name);
  7857. }
  7858. public function getPdoType($type)
  7859. {
  7860. static $map=array
  7861. (
  7862. 'boolean'=>PDO::PARAM_BOOL,
  7863. 'integer'=>PDO::PARAM_INT,
  7864. 'string'=>PDO::PARAM_STR,
  7865. 'NULL'=>PDO::PARAM_NULL,
  7866. );
  7867. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  7868. }
  7869. public function getColumnCase()
  7870. {
  7871. return $this->getAttribute(PDO::ATTR_CASE);
  7872. }
  7873. public function setColumnCase($value)
  7874. {
  7875. $this->setAttribute(PDO::ATTR_CASE,$value);
  7876. }
  7877. public function getNullConversion()
  7878. {
  7879. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  7880. }
  7881. public function setNullConversion($value)
  7882. {
  7883. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  7884. }
  7885. public function getAutoCommit()
  7886. {
  7887. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  7888. }
  7889. public function setAutoCommit($value)
  7890. {
  7891. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  7892. }
  7893. public function getPersistent()
  7894. {
  7895. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  7896. }
  7897. public function setPersistent($value)
  7898. {
  7899. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  7900. }
  7901. public function getDriverName()
  7902. {
  7903. if(($pos=strpos($this->connectionString, ':'))!==false)
  7904. return strtolower(substr($this->connectionString, 0, $pos));
  7905. // return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  7906. }
  7907. public function getClientVersion()
  7908. {
  7909. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  7910. }
  7911. public function getConnectionStatus()
  7912. {
  7913. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  7914. }
  7915. public function getPrefetch()
  7916. {
  7917. return $this->getAttribute(PDO::ATTR_PREFETCH);
  7918. }
  7919. public function getServerInfo()
  7920. {
  7921. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  7922. }
  7923. public function getServerVersion()
  7924. {
  7925. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  7926. }
  7927. public function getTimeout()
  7928. {
  7929. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  7930. }
  7931. public function getAttribute($name)
  7932. {
  7933. $this->setActive(true);
  7934. return $this->_pdo->getAttribute($name);
  7935. }
  7936. public function setAttribute($name,$value)
  7937. {
  7938. if($this->_pdo instanceof PDO)
  7939. $this->_pdo->setAttribute($name,$value);
  7940. else
  7941. $this->_attributes[$name]=$value;
  7942. }
  7943. public function getAttributes()
  7944. {
  7945. return $this->_attributes;
  7946. }
  7947. public function setAttributes($values)
  7948. {
  7949. foreach($values as $name=>$value)
  7950. $this->_attributes[$name]=$value;
  7951. }
  7952. public function getStats()
  7953. {
  7954. $logger=Yii::getLogger();
  7955. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  7956. $count=count($timings);
  7957. $time=array_sum($timings);
  7958. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  7959. $count+=count($timings);
  7960. $time+=array_sum($timings);
  7961. return array($count,$time);
  7962. }
  7963. }
  7964. abstract class CDbSchema extends CComponent
  7965. {
  7966. public $columnTypes=array();
  7967. private $_tableNames=array();
  7968. private $_tables=array();
  7969. private $_connection;
  7970. private $_builder;
  7971. private $_cacheExclude=array();
  7972. abstract protected function loadTable($name);
  7973. public function __construct($conn)
  7974. {
  7975. $this->_connection=$conn;
  7976. foreach($conn->schemaCachingExclude as $name)
  7977. $this->_cacheExclude[$name]=true;
  7978. }
  7979. public function getDbConnection()
  7980. {
  7981. return $this->_connection;
  7982. }
  7983. public function getTable($name)
  7984. {
  7985. if(isset($this->_tables[$name]))
  7986. return $this->_tables[$name];
  7987. else
  7988. {
  7989. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  7990. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  7991. else
  7992. $realName=$name;
  7993. // temporarily disable query caching
  7994. if($this->_connection->queryCachingDuration>0)
  7995. {
  7996. $qcDuration=$this->_connection->queryCachingDuration;
  7997. $this->_connection->queryCachingDuration=0;
  7998. }
  7999. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8000. {
  8001. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8002. if(($table=$cache->get($key))===false)
  8003. {
  8004. $table=$this->loadTable($realName);
  8005. if($table!==null)
  8006. $cache->set($key,$table,$duration);
  8007. }
  8008. $this->_tables[$name]=$table;
  8009. }
  8010. else
  8011. $this->_tables[$name]=$table=$this->loadTable($realName);
  8012. if(isset($qcDuration)) // re-enable query caching
  8013. $this->_connection->queryCachingDuration=$qcDuration;
  8014. return $table;
  8015. }
  8016. }
  8017. public function getTables($schema='')
  8018. {
  8019. $tables=array();
  8020. foreach($this->getTableNames($schema) as $name)
  8021. {
  8022. if(($table=$this->getTable($name))!==null)
  8023. $tables[$name]=$table;
  8024. }
  8025. return $tables;
  8026. }
  8027. public function getTableNames($schema='')
  8028. {
  8029. if(!isset($this->_tableNames[$schema]))
  8030. $this->_tableNames[$schema]=$this->findTableNames($schema);
  8031. return $this->_tableNames[$schema];
  8032. }
  8033. public function getCommandBuilder()
  8034. {
  8035. if($this->_builder!==null)
  8036. return $this->_builder;
  8037. else
  8038. return $this->_builder=$this->createCommandBuilder();
  8039. }
  8040. public function refresh()
  8041. {
  8042. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8043. {
  8044. foreach(array_keys($this->_tables) as $name)
  8045. {
  8046. if(!isset($this->_cacheExclude[$name]))
  8047. {
  8048. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8049. $cache->delete($key);
  8050. }
  8051. }
  8052. }
  8053. $this->_tables=array();
  8054. $this->_tableNames=array();
  8055. $this->_builder=null;
  8056. }
  8057. public function quoteTableName($name)
  8058. {
  8059. if(strpos($name,'.')===false)
  8060. return $this->quoteSimpleTableName($name);
  8061. $parts=explode('.',$name);
  8062. foreach($parts as $i=>$part)
  8063. $parts[$i]=$this->quoteSimpleTableName($part);
  8064. return implode('.',$parts);
  8065. }
  8066. public function quoteSimpleTableName($name)
  8067. {
  8068. return "'".$name."'";
  8069. }
  8070. public function quoteColumnName($name)
  8071. {
  8072. if(($pos=strrpos($name,'.'))!==false)
  8073. {
  8074. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  8075. $name=substr($name,$pos+1);
  8076. }
  8077. else
  8078. $prefix='';
  8079. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  8080. }
  8081. public function quoteSimpleColumnName($name)
  8082. {
  8083. return '"'.$name.'"';
  8084. }
  8085. public function compareTableNames($name1,$name2)
  8086. {
  8087. $name1=str_replace(array('"','`',"'"),'',$name1);
  8088. $name2=str_replace(array('"','`',"'"),'',$name2);
  8089. if(($pos=strrpos($name1,'.'))!==false)
  8090. $name1=substr($name1,$pos+1);
  8091. if(($pos=strrpos($name2,'.'))!==false)
  8092. $name2=substr($name2,$pos+1);
  8093. if($this->_connection->tablePrefix!==null)
  8094. {
  8095. if(strpos($name1,'{')!==false)
  8096. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  8097. if(strpos($name2,'{')!==false)
  8098. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  8099. }
  8100. return $name1===$name2;
  8101. }
  8102. public function resetSequence($table,$value=null)
  8103. {
  8104. }
  8105. public function checkIntegrity($check=true,$schema='')
  8106. {
  8107. }
  8108. protected function createCommandBuilder()
  8109. {
  8110. return new CDbCommandBuilder($this);
  8111. }
  8112. protected function findTableNames($schema='')
  8113. {
  8114. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  8115. array('{class}'=>get_class($this))));
  8116. }
  8117. public function getColumnType($type)
  8118. {
  8119. if(isset($this->columnTypes[$type]))
  8120. return $this->columnTypes[$type];
  8121. else if(($pos=strpos($type,' '))!==false)
  8122. {
  8123. $t=substr($type,0,$pos);
  8124. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  8125. }
  8126. else
  8127. return $type;
  8128. }
  8129. public function createTable($table, $columns, $options=null)
  8130. {
  8131. $cols=array();
  8132. foreach($columns as $name=>$type)
  8133. {
  8134. if(is_string($name))
  8135. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  8136. else
  8137. $cols[]="\t".$type;
  8138. }
  8139. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  8140. return $options===null ? $sql : $sql.' '.$options;
  8141. }
  8142. public function renameTable($table, $newName)
  8143. {
  8144. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  8145. }
  8146. public function dropTable($table)
  8147. {
  8148. return "DROP TABLE ".$this->quoteTableName($table);
  8149. }
  8150. public function truncateTable($table)
  8151. {
  8152. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  8153. }
  8154. public function addColumn($table, $column, $type)
  8155. {
  8156. $type=$this->getColumnType($type);
  8157. $sql='ALTER TABLE ' . $this->quoteTableName($table)
  8158. . ' ADD ' . $this->quoteColumnName($column) . ' '
  8159. . $this->getColumnType($type);
  8160. return $sql;
  8161. }
  8162. public function dropColumn($table, $column)
  8163. {
  8164. return "ALTER TABLE ".$this->quoteTableName($table)
  8165. ." DROP COLUMN ".$this->quoteColumnName($column);
  8166. }
  8167. public function renameColumn($table, $name, $newName)
  8168. {
  8169. return "ALTER TABLE ".$this->quoteTableName($table)
  8170. . " RENAME COLUMN ".$this->quoteColumnName($name)
  8171. . " TO ".$this->quoteColumnName($newName);
  8172. }
  8173. public function alterColumn($table, $column, $type)
  8174. {
  8175. $type=$this->getColumnType($type);
  8176. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  8177. . $this->quoteColumnName($column) . ' '
  8178. . $this->quoteColumnName($column) . ' '
  8179. . $this->getColumnType($type);
  8180. }
  8181. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8182. {
  8183. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  8184. foreach($columns as $i=>$col)
  8185. $columns[$i]=$this->quoteColumnName($col);
  8186. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  8187. foreach($refColumns as $i=>$col)
  8188. $refColumns[$i]=$this->quoteColumnName($col);
  8189. $sql='ALTER TABLE '.$this->quoteTableName($table)
  8190. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  8191. .' FOREIGN KEY ('.implode(', ', $columns).')'
  8192. .' REFERENCES '.$this->quoteTableName($refTable)
  8193. .' ('.implode(', ', $refColumns).')';
  8194. if($delete!==null)
  8195. $sql.=' ON DELETE '.$delete;
  8196. if($update!==null)
  8197. $sql.=' ON UPDATE '.$update;
  8198. return $sql;
  8199. }
  8200. public function dropForeignKey($name, $table)
  8201. {
  8202. return 'ALTER TABLE '.$this->quoteTableName($table)
  8203. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  8204. }
  8205. public function createIndex($name, $table, $column, $unique=false)
  8206. {
  8207. $cols=array();
  8208. $columns=preg_split('/\s*,\s*/',$column,-1,PREG_SPLIT_NO_EMPTY);
  8209. foreach($columns as $col)
  8210. {
  8211. if(strpos($col,'(')!==false)
  8212. $cols[]=$col;
  8213. else
  8214. $cols[]=$this->quoteColumnName($col);
  8215. }
  8216. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  8217. . $this->quoteTableName($name).' ON '
  8218. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  8219. }
  8220. public function dropIndex($name, $table)
  8221. {
  8222. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  8223. }
  8224. }
  8225. class CSqliteSchema extends CDbSchema
  8226. {
  8227. public $columnTypes=array(
  8228. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  8229. 'string' => 'varchar(255)',
  8230. 'text' => 'text',
  8231. 'integer' => 'integer',
  8232. 'float' => 'float',
  8233. 'decimal' => 'decimal',
  8234. 'datetime' => 'datetime',
  8235. 'timestamp' => 'timestamp',
  8236. 'time' => 'time',
  8237. 'date' => 'date',
  8238. 'binary' => 'blob',
  8239. 'boolean' => 'tinyint(1)',
  8240. 'money' => 'decimal(19,4)',
  8241. );
  8242. public function resetSequence($table,$value=null)
  8243. {
  8244. if($table->sequenceName!==null)
  8245. {
  8246. if($value===null)
  8247. $value=$this->getDbConnection()->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")->queryScalar();
  8248. else
  8249. $value=(int)$value-1;
  8250. try
  8251. {
  8252. // it's possible sqlite_sequence does not exist
  8253. $this->getDbConnection()->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")->execute();
  8254. }
  8255. catch(Exception $e)
  8256. {
  8257. }
  8258. }
  8259. }
  8260. public function checkIntegrity($check=true,$schema='')
  8261. {
  8262. // SQLite doesn't enforce integrity
  8263. return;
  8264. }
  8265. protected function findTableNames($schema='')
  8266. {
  8267. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  8268. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  8269. }
  8270. protected function createCommandBuilder()
  8271. {
  8272. return new CSqliteCommandBuilder($this);
  8273. }
  8274. protected function loadTable($name)
  8275. {
  8276. $table=new CDbTableSchema;
  8277. $table->name=$name;
  8278. $table->rawName=$this->quoteTableName($name);
  8279. if($this->findColumns($table))
  8280. {
  8281. $this->findConstraints($table);
  8282. return $table;
  8283. }
  8284. else
  8285. return null;
  8286. }
  8287. protected function findColumns($table)
  8288. {
  8289. $sql="PRAGMA table_info({$table->rawName})";
  8290. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  8291. if(empty($columns))
  8292. return false;
  8293. foreach($columns as $column)
  8294. {
  8295. $c=$this->createColumn($column);
  8296. $table->columns[$c->name]=$c;
  8297. if($c->isPrimaryKey)
  8298. {
  8299. if($table->primaryKey===null)
  8300. $table->primaryKey=$c->name;
  8301. else if(is_string($table->primaryKey))
  8302. $table->primaryKey=array($table->primaryKey,$c->name);
  8303. else
  8304. $table->primaryKey[]=$c->name;
  8305. }
  8306. }
  8307. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  8308. {
  8309. $table->sequenceName='';
  8310. $table->columns[$table->primaryKey]->autoIncrement=true;
  8311. }
  8312. return true;
  8313. }
  8314. protected function findConstraints($table)
  8315. {
  8316. $foreignKeys=array();
  8317. $sql="PRAGMA foreign_key_list({$table->rawName})";
  8318. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  8319. foreach($keys as $key)
  8320. {
  8321. $column=$table->columns[$key['from']];
  8322. $column->isForeignKey=true;
  8323. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  8324. }
  8325. $table->foreignKeys=$foreignKeys;
  8326. }
  8327. protected function createColumn($column)
  8328. {
  8329. $c=new CSqliteColumnSchema;
  8330. $c->name=$column['name'];
  8331. $c->rawName=$this->quoteColumnName($c->name);
  8332. $c->allowNull=!$column['notnull'];
  8333. $c->isPrimaryKey=$column['pk']!=0;
  8334. $c->isForeignKey=false;
  8335. $c->init(strtolower($column['type']),$column['dflt_value']);
  8336. return $c;
  8337. }
  8338. public function truncateTable($table)
  8339. {
  8340. return "DELETE FROM ".$this->quoteTableName($table);
  8341. }
  8342. public function dropColumn($table, $column)
  8343. {
  8344. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  8345. }
  8346. public function renameColumn($table, $name, $newName)
  8347. {
  8348. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  8349. }
  8350. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8351. {
  8352. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  8353. }
  8354. public function dropForeignKey($name, $table)
  8355. {
  8356. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  8357. }
  8358. public function alterColumn($table, $column, $type)
  8359. {
  8360. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  8361. }
  8362. public function dropIndex($name, $table)
  8363. {
  8364. return 'DROP INDEX '.$this->quoteTableName($name);
  8365. }
  8366. }
  8367. class CDbTableSchema extends CComponent
  8368. {
  8369. public $name;
  8370. public $rawName;
  8371. public $primaryKey;
  8372. public $sequenceName;
  8373. public $foreignKeys=array();
  8374. public $columns=array();
  8375. public function getColumn($name)
  8376. {
  8377. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  8378. }
  8379. public function getColumnNames()
  8380. {
  8381. return array_keys($this->columns);
  8382. }
  8383. }
  8384. class CDbCommand extends CComponent
  8385. {
  8386. public $params=array();
  8387. private $_connection;
  8388. private $_text;
  8389. private $_statement;
  8390. private $_paramLog=array();
  8391. private $_query;
  8392. private $_fetchMode = array(PDO::FETCH_ASSOC);
  8393. public function __construct(CDbConnection $connection,$query=null)
  8394. {
  8395. $this->_connection=$connection;
  8396. if(is_array($query))
  8397. {
  8398. foreach($query as $name=>$value)
  8399. $this->$name=$value;
  8400. }
  8401. else
  8402. $this->setText($query);
  8403. }
  8404. public function __sleep()
  8405. {
  8406. $this->_statement=null;
  8407. return array_keys(get_object_vars($this));
  8408. }
  8409. public function setFetchMode($mode)
  8410. {
  8411. $params=func_get_args();
  8412. $this->_fetchMode = $params;
  8413. return $this;
  8414. }
  8415. public function reset()
  8416. {
  8417. $this->_text=null;
  8418. $this->_query=null;
  8419. $this->_statement=null;
  8420. $this->_paramLog=array();
  8421. $this->params=array();
  8422. return $this;
  8423. }
  8424. public function getText()
  8425. {
  8426. if($this->_text=='' && !empty($this->_query))
  8427. $this->setText($this->buildQuery($this->_query));
  8428. return $this->_text;
  8429. }
  8430. public function setText($value)
  8431. {
  8432. if($this->_connection->tablePrefix!==null && $value!='')
  8433. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  8434. else
  8435. $this->_text=$value;
  8436. $this->cancel();
  8437. return $this;
  8438. }
  8439. public function getConnection()
  8440. {
  8441. return $this->_connection;
  8442. }
  8443. public function getPdoStatement()
  8444. {
  8445. return $this->_statement;
  8446. }
  8447. public function prepare()
  8448. {
  8449. if($this->_statement==null)
  8450. {
  8451. try
  8452. {
  8453. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  8454. $this->_paramLog=array();
  8455. }
  8456. catch(Exception $e)
  8457. {
  8458. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8459. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8460. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  8461. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  8462. }
  8463. }
  8464. }
  8465. public function cancel()
  8466. {
  8467. $this->_statement=null;
  8468. }
  8469. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  8470. {
  8471. $this->prepare();
  8472. if($dataType===null)
  8473. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  8474. else if($length===null)
  8475. $this->_statement->bindParam($name,$value,$dataType);
  8476. else if($driverOptions===null)
  8477. $this->_statement->bindParam($name,$value,$dataType,$length);
  8478. else
  8479. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  8480. $this->_paramLog[$name]=&$value;
  8481. return $this;
  8482. }
  8483. public function bindValue($name, $value, $dataType=null)
  8484. {
  8485. $this->prepare();
  8486. if($dataType===null)
  8487. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8488. else
  8489. $this->_statement->bindValue($name,$value,$dataType);
  8490. $this->_paramLog[$name]=$value;
  8491. return $this;
  8492. }
  8493. public function bindValues($values)
  8494. {
  8495. $this->prepare();
  8496. foreach($values as $name=>$value)
  8497. {
  8498. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  8499. $this->_paramLog[$name]=$value;
  8500. }
  8501. return $this;
  8502. }
  8503. public function execute($params=array())
  8504. {
  8505. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8506. {
  8507. $p=array();
  8508. foreach($pars as $name=>$value)
  8509. $p[$name]=$name.'='.var_export($value,true);
  8510. $par='. Bound with ' .implode(', ',$p);
  8511. }
  8512. else
  8513. $par='';
  8514. try
  8515. {
  8516. if($this->_connection->enableProfiling)
  8517. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8518. $this->prepare();
  8519. if($params===array())
  8520. $this->_statement->execute();
  8521. else
  8522. $this->_statement->execute($params);
  8523. $n=$this->_statement->rowCount();
  8524. if($this->_connection->enableProfiling)
  8525. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8526. return $n;
  8527. }
  8528. catch(Exception $e)
  8529. {
  8530. if($this->_connection->enableProfiling)
  8531. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  8532. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8533. $message = $e->getMessage();
  8534. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  8535. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8536. if(YII_DEBUG)
  8537. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  8538. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8539. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8540. }
  8541. }
  8542. public function query($params=array())
  8543. {
  8544. return $this->queryInternal('',0,$params);
  8545. }
  8546. public function queryAll($fetchAssociative=true,$params=array())
  8547. {
  8548. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8549. }
  8550. public function queryRow($fetchAssociative=true,$params=array())
  8551. {
  8552. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  8553. }
  8554. public function queryScalar($params=array())
  8555. {
  8556. $result=$this->queryInternal('fetchColumn',0,$params);
  8557. if(is_resource($result) && get_resource_type($result)==='stream')
  8558. return stream_get_contents($result);
  8559. else
  8560. return $result;
  8561. }
  8562. public function queryColumn($params=array())
  8563. {
  8564. return $this->queryInternal('fetchAll',PDO::FETCH_COLUMN,$params);
  8565. }
  8566. private function queryInternal($method,$mode,$params=array())
  8567. {
  8568. $params=array_merge($this->params,$params);
  8569. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  8570. {
  8571. $p=array();
  8572. foreach($pars as $name=>$value)
  8573. $p[$name]=$name.'='.var_export($value,true);
  8574. $par='. Bound with '.implode(', ',$p);
  8575. }
  8576. else
  8577. $par='';
  8578. if($this->_connection->queryCachingCount>0 && $method!==''
  8579. && $this->_connection->queryCachingDuration>0
  8580. && $this->_connection->queryCacheID!==false
  8581. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  8582. {
  8583. $this->_connection->queryCachingCount--;
  8584. $cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
  8585. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  8586. if(($result=$cache->get($cacheKey))!==false)
  8587. {
  8588. return $result;
  8589. }
  8590. }
  8591. try
  8592. {
  8593. if($this->_connection->enableProfiling)
  8594. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8595. $this->prepare();
  8596. if($params===array())
  8597. $this->_statement->execute();
  8598. else
  8599. $this->_statement->execute($params);
  8600. if($method==='')
  8601. $result=new CDbDataReader($this);
  8602. else
  8603. {
  8604. $mode=(array)$mode;
  8605. $result=call_user_func_array(array($this->_statement, $method), $mode);
  8606. $this->_statement->closeCursor();
  8607. }
  8608. if($this->_connection->enableProfiling)
  8609. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8610. if(isset($cache,$cacheKey))
  8611. $cache->set($cacheKey, $result, $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  8612. return $result;
  8613. }
  8614. catch(Exception $e)
  8615. {
  8616. if($this->_connection->enableProfiling)
  8617. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  8618. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  8619. $message = $e->getMessage();
  8620. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  8621. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  8622. if(YII_DEBUG)
  8623. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  8624. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  8625. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  8626. }
  8627. }
  8628. public function buildQuery($query)
  8629. {
  8630. $sql=isset($query['distinct']) && $query['distinct'] ? 'SELECT DISTINCT' : 'SELECT';
  8631. $sql.=' '.(isset($query['select']) ? $query['select'] : '*');
  8632. if(isset($query['from']))
  8633. $sql.="\nFROM ".$query['from'];
  8634. else
  8635. throw new CDbException(Yii::t('yii','The DB query must contain the "from" portion.'));
  8636. if(isset($query['join']))
  8637. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  8638. if(isset($query['where']))
  8639. $sql.="\nWHERE ".$query['where'];
  8640. if(isset($query['group']))
  8641. $sql.="\nGROUP BY ".$query['group'];
  8642. if(isset($query['having']))
  8643. $sql.="\nHAVING ".$query['having'];
  8644. if(isset($query['order']))
  8645. $sql.="\nORDER BY ".$query['order'];
  8646. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  8647. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  8648. if($limit>=0 || $offset>0)
  8649. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  8650. if(isset($query['union']))
  8651. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  8652. return $sql;
  8653. }
  8654. public function select($columns='*', $option='')
  8655. {
  8656. if(is_string($columns) && strpos($columns,'(')!==false)
  8657. $this->_query['select']=$columns;
  8658. else
  8659. {
  8660. if(!is_array($columns))
  8661. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8662. foreach($columns as $i=>$column)
  8663. {
  8664. if(is_object($column))
  8665. $columns[$i]=(string)$column;
  8666. else if(strpos($column,'(')===false)
  8667. {
  8668. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  8669. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  8670. else
  8671. $columns[$i]=$this->_connection->quoteColumnName($column);
  8672. }
  8673. }
  8674. $this->_query['select']=implode(', ',$columns);
  8675. }
  8676. if($option!='')
  8677. $this->_query['select']=$option.' '.$this->_query['select'];
  8678. return $this;
  8679. }
  8680. public function getSelect()
  8681. {
  8682. return isset($this->_query['select']) ? $this->_query['select'] : '';
  8683. }
  8684. public function setSelect($value)
  8685. {
  8686. $this->select($value);
  8687. }
  8688. public function selectDistinct($columns='*')
  8689. {
  8690. $this->_query['distinct']=true;
  8691. return $this->select($columns);
  8692. }
  8693. public function getDistinct()
  8694. {
  8695. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  8696. }
  8697. public function setDistinct($value)
  8698. {
  8699. $this->_query['distinct']=$value;
  8700. }
  8701. public function from($tables)
  8702. {
  8703. if(is_string($tables) && strpos($tables,'(')!==false)
  8704. $this->_query['from']=$tables;
  8705. else
  8706. {
  8707. if(!is_array($tables))
  8708. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  8709. foreach($tables as $i=>$table)
  8710. {
  8711. if(strpos($table,'(')===false)
  8712. {
  8713. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  8714. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  8715. else
  8716. $tables[$i]=$this->_connection->quoteTableName($table);
  8717. }
  8718. }
  8719. $this->_query['from']=implode(', ',$tables);
  8720. }
  8721. return $this;
  8722. }
  8723. public function getFrom()
  8724. {
  8725. return isset($this->_query['from']) ? $this->_query['from'] : '';
  8726. }
  8727. public function setFrom($value)
  8728. {
  8729. $this->from($value);
  8730. }
  8731. public function where($conditions, $params=array())
  8732. {
  8733. $this->_query['where']=$this->processConditions($conditions);
  8734. foreach($params as $name=>$value)
  8735. $this->params[$name]=$value;
  8736. return $this;
  8737. }
  8738. public function getWhere()
  8739. {
  8740. return isset($this->_query['where']) ? $this->_query['where'] : '';
  8741. }
  8742. public function setWhere($value)
  8743. {
  8744. $this->where($value);
  8745. }
  8746. public function join($table, $conditions, $params=array())
  8747. {
  8748. return $this->joinInternal('join', $table, $conditions, $params);
  8749. }
  8750. public function getJoin()
  8751. {
  8752. return isset($this->_query['join']) ? $this->_query['join'] : '';
  8753. }
  8754. public function setJoin($value)
  8755. {
  8756. $this->_query['join']=$value;
  8757. }
  8758. public function leftJoin($table, $conditions, $params=array())
  8759. {
  8760. return $this->joinInternal('left join', $table, $conditions, $params);
  8761. }
  8762. public function rightJoin($table, $conditions, $params=array())
  8763. {
  8764. return $this->joinInternal('right join', $table, $conditions, $params);
  8765. }
  8766. public function crossJoin($table)
  8767. {
  8768. return $this->joinInternal('cross join', $table);
  8769. }
  8770. public function naturalJoin($table)
  8771. {
  8772. return $this->joinInternal('natural join', $table);
  8773. }
  8774. public function group($columns)
  8775. {
  8776. if(is_string($columns) && strpos($columns,'(')!==false)
  8777. $this->_query['group']=$columns;
  8778. else
  8779. {
  8780. if(!is_array($columns))
  8781. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8782. foreach($columns as $i=>$column)
  8783. {
  8784. if(is_object($column))
  8785. $columns[$i]=(string)$column;
  8786. else if(strpos($column,'(')===false)
  8787. $columns[$i]=$this->_connection->quoteColumnName($column);
  8788. }
  8789. $this->_query['group']=implode(', ',$columns);
  8790. }
  8791. return $this;
  8792. }
  8793. public function getGroup()
  8794. {
  8795. return isset($this->_query['group']) ? $this->_query['group'] : '';
  8796. }
  8797. public function setGroup($value)
  8798. {
  8799. $this->group($value);
  8800. }
  8801. public function having($conditions, $params=array())
  8802. {
  8803. $this->_query['having']=$this->processConditions($conditions);
  8804. foreach($params as $name=>$value)
  8805. $this->params[$name]=$value;
  8806. return $this;
  8807. }
  8808. public function getHaving()
  8809. {
  8810. return isset($this->_query['having']) ? $this->_query['having'] : '';
  8811. }
  8812. public function setHaving($value)
  8813. {
  8814. $this->having($value);
  8815. }
  8816. public function order($columns)
  8817. {
  8818. if(is_string($columns) && strpos($columns,'(')!==false)
  8819. $this->_query['order']=$columns;
  8820. else
  8821. {
  8822. if(!is_array($columns))
  8823. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  8824. foreach($columns as $i=>$column)
  8825. {
  8826. if(is_object($column))
  8827. $columns[$i]=(string)$column;
  8828. else if(strpos($column,'(')===false)
  8829. {
  8830. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  8831. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  8832. else
  8833. $columns[$i]=$this->_connection->quoteColumnName($column);
  8834. }
  8835. }
  8836. $this->_query['order']=implode(', ',$columns);
  8837. }
  8838. return $this;
  8839. }
  8840. public function getOrder()
  8841. {
  8842. return isset($this->_query['order']) ? $this->_query['order'] : '';
  8843. }
  8844. public function setOrder($value)
  8845. {
  8846. $this->order($value);
  8847. }
  8848. public function limit($limit, $offset=null)
  8849. {
  8850. $this->_query['limit']=(int)$limit;
  8851. if($offset!==null)
  8852. $this->offset($offset);
  8853. return $this;
  8854. }
  8855. public function getLimit()
  8856. {
  8857. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  8858. }
  8859. public function setLimit($value)
  8860. {
  8861. $this->limit($value);
  8862. }
  8863. public function offset($offset)
  8864. {
  8865. $this->_query['offset']=(int)$offset;
  8866. return $this;
  8867. }
  8868. public function getOffset()
  8869. {
  8870. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  8871. }
  8872. public function setOffset($value)
  8873. {
  8874. $this->offset($value);
  8875. }
  8876. public function union($sql)
  8877. {
  8878. if(isset($this->_query['union']) && is_string($this->_query['union']))
  8879. $this->_query['union']=array($this->_query['union']);
  8880. $this->_query['union'][]=$sql;
  8881. return $this;
  8882. }
  8883. public function getUnion()
  8884. {
  8885. return isset($this->_query['union']) ? $this->_query['union'] : '';
  8886. }
  8887. public function setUnion($value)
  8888. {
  8889. $this->_query['union']=$value;
  8890. }
  8891. public function insert($table, $columns)
  8892. {
  8893. $params=array();
  8894. $names=array();
  8895. $placeholders=array();
  8896. foreach($columns as $name=>$value)
  8897. {
  8898. $names[]=$this->_connection->quoteColumnName($name);
  8899. if($value instanceof CDbExpression)
  8900. {
  8901. $placeholders[] = $value->expression;
  8902. foreach($value->params as $n => $v)
  8903. $params[$n] = $v;
  8904. }
  8905. else
  8906. {
  8907. $placeholders[] = ':' . $name;
  8908. $params[':' . $name] = $value;
  8909. }
  8910. }
  8911. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  8912. . ' (' . implode(', ',$names) . ') VALUES ('
  8913. . implode(', ', $placeholders) . ')';
  8914. return $this->setText($sql)->execute($params);
  8915. }
  8916. public function update($table, $columns, $conditions='', $params=array())
  8917. {
  8918. $lines=array();
  8919. foreach($columns as $name=>$value)
  8920. {
  8921. if($value instanceof CDbExpression)
  8922. {
  8923. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  8924. foreach($value->params as $n => $v)
  8925. $params[$n] = $v;
  8926. }
  8927. else
  8928. {
  8929. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  8930. $params[':' . $name]=$value;
  8931. }
  8932. }
  8933. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  8934. if(($where=$this->processConditions($conditions))!='')
  8935. $sql.=' WHERE '.$where;
  8936. return $this->setText($sql)->execute($params);
  8937. }
  8938. public function delete($table, $conditions='', $params=array())
  8939. {
  8940. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  8941. if(($where=$this->processConditions($conditions))!='')
  8942. $sql.=' WHERE '.$where;
  8943. return $this->setText($sql)->execute($params);
  8944. }
  8945. public function createTable($table, $columns, $options=null)
  8946. {
  8947. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  8948. }
  8949. public function renameTable($table, $newName)
  8950. {
  8951. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  8952. }
  8953. public function dropTable($table)
  8954. {
  8955. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  8956. }
  8957. public function truncateTable($table)
  8958. {
  8959. $schema=$this->getConnection()->getSchema();
  8960. $n=$this->setText($schema->truncateTable($table))->execute();
  8961. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  8962. $schema->resetSequence($schema->getTable($table));
  8963. return $n;
  8964. }
  8965. public function addColumn($table, $column, $type)
  8966. {
  8967. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  8968. }
  8969. public function dropColumn($table, $column)
  8970. {
  8971. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  8972. }
  8973. public function renameColumn($table, $name, $newName)
  8974. {
  8975. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  8976. }
  8977. public function alterColumn($table, $column, $type)
  8978. {
  8979. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  8980. }
  8981. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  8982. {
  8983. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  8984. }
  8985. public function dropForeignKey($name, $table)
  8986. {
  8987. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  8988. }
  8989. public function createIndex($name, $table, $column, $unique=false)
  8990. {
  8991. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $column, $unique))->execute();
  8992. }
  8993. public function dropIndex($name, $table)
  8994. {
  8995. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  8996. }
  8997. private function processConditions($conditions)
  8998. {
  8999. if(!is_array($conditions))
  9000. return $conditions;
  9001. else if($conditions===array())
  9002. return '';
  9003. $n=count($conditions);
  9004. $operator=strtoupper($conditions[0]);
  9005. if($operator==='OR' || $operator==='AND')
  9006. {
  9007. $parts=array();
  9008. for($i=1;$i<$n;++$i)
  9009. {
  9010. $condition=$this->processConditions($conditions[$i]);
  9011. if($condition!=='')
  9012. $parts[]='('.$condition.')';
  9013. }
  9014. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  9015. }
  9016. if(!isset($conditions[1],$conditions[2]))
  9017. return '';
  9018. $column=$conditions[1];
  9019. if(strpos($column,'(')===false)
  9020. $column=$this->_connection->quoteColumnName($column);
  9021. $values=$conditions[2];
  9022. if(!is_array($values))
  9023. $values=array($values);
  9024. if($operator==='IN' || $operator==='NOT IN')
  9025. {
  9026. if($values===array())
  9027. return $operator==='IN' ? '0=1' : '';
  9028. foreach($values as $i=>$value)
  9029. {
  9030. if(is_string($value))
  9031. $values[$i]=$this->_connection->quoteValue($value);
  9032. else
  9033. $values[$i]=(string)$value;
  9034. }
  9035. return $column.' '.$operator.' ('.implode(', ',$values).')';
  9036. }
  9037. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  9038. {
  9039. if($values===array())
  9040. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  9041. if($operator==='LIKE' || $operator==='NOT LIKE')
  9042. $andor=' AND ';
  9043. else
  9044. {
  9045. $andor=' OR ';
  9046. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  9047. }
  9048. $expressions=array();
  9049. foreach($values as $value)
  9050. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  9051. return implode($andor,$expressions);
  9052. }
  9053. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  9054. }
  9055. private function joinInternal($type, $table, $conditions='', $params=array())
  9056. {
  9057. if(strpos($table,'(')===false)
  9058. {
  9059. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9060. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9061. else
  9062. $table=$this->_connection->quoteTableName($table);
  9063. }
  9064. $conditions=$this->processConditions($conditions);
  9065. if($conditions!='')
  9066. $conditions=' ON '.$conditions;
  9067. if(isset($this->_query['join']) && is_string($this->_query['join']))
  9068. $this->_query['join']=array($this->_query['join']);
  9069. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  9070. foreach($params as $name=>$value)
  9071. $this->params[$name]=$value;
  9072. return $this;
  9073. }
  9074. }
  9075. class CDbColumnSchema extends CComponent
  9076. {
  9077. public $name;
  9078. public $rawName;
  9079. public $allowNull;
  9080. public $dbType;
  9081. public $type;
  9082. public $defaultValue;
  9083. public $size;
  9084. public $precision;
  9085. public $scale;
  9086. public $isPrimaryKey;
  9087. public $isForeignKey;
  9088. public $autoIncrement=false;
  9089. public function init($dbType, $defaultValue)
  9090. {
  9091. $this->dbType=$dbType;
  9092. $this->extractType($dbType);
  9093. $this->extractLimit($dbType);
  9094. if($defaultValue!==null)
  9095. $this->extractDefault($defaultValue);
  9096. }
  9097. protected function extractType($dbType)
  9098. {
  9099. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  9100. $this->type='integer';
  9101. else if(stripos($dbType,'bool')!==false)
  9102. $this->type='boolean';
  9103. else if(preg_match('/(real|floa|doub)/i',$dbType))
  9104. $this->type='double';
  9105. else
  9106. $this->type='string';
  9107. }
  9108. protected function extractLimit($dbType)
  9109. {
  9110. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  9111. {
  9112. $values=explode(',',$matches[1]);
  9113. $this->size=$this->precision=(int)$values[0];
  9114. if(isset($values[1]))
  9115. $this->scale=(int)$values[1];
  9116. }
  9117. }
  9118. protected function extractDefault($defaultValue)
  9119. {
  9120. $this->defaultValue=$this->typecast($defaultValue);
  9121. }
  9122. public function typecast($value)
  9123. {
  9124. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  9125. return $value;
  9126. if($value==='')
  9127. return $this->type==='string' ? '' : null;
  9128. switch($this->type)
  9129. {
  9130. case 'string': return (string)$value;
  9131. case 'integer': return (integer)$value;
  9132. case 'boolean': return (boolean)$value;
  9133. case 'double':
  9134. default: return $value;
  9135. }
  9136. }
  9137. }
  9138. class CSqliteColumnSchema extends CDbColumnSchema
  9139. {
  9140. protected function extractDefault($defaultValue)
  9141. {
  9142. if($this->type==='string') // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  9143. $this->defaultValue=trim($defaultValue,"'\"");
  9144. else
  9145. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  9146. }
  9147. }
  9148. abstract class CValidator extends CComponent
  9149. {
  9150. public static $builtInValidators=array(
  9151. 'required'=>'CRequiredValidator',
  9152. 'filter'=>'CFilterValidator',
  9153. 'match'=>'CRegularExpressionValidator',
  9154. 'email'=>'CEmailValidator',
  9155. 'url'=>'CUrlValidator',
  9156. 'unique'=>'CUniqueValidator',
  9157. 'compare'=>'CCompareValidator',
  9158. 'length'=>'CStringValidator',
  9159. 'in'=>'CRangeValidator',
  9160. 'numerical'=>'CNumberValidator',
  9161. 'captcha'=>'CCaptchaValidator',
  9162. 'type'=>'CTypeValidator',
  9163. 'file'=>'CFileValidator',
  9164. 'default'=>'CDefaultValueValidator',
  9165. 'exist'=>'CExistValidator',
  9166. 'boolean'=>'CBooleanValidator',
  9167. 'safe'=>'CSafeValidator',
  9168. 'unsafe'=>'CUnsafeValidator',
  9169. 'date'=>'CDateValidator',
  9170. );
  9171. public $attributes;
  9172. public $message;
  9173. public $skipOnError=false;
  9174. public $on;
  9175. public $safe=true;
  9176. public $enableClientValidation=true;
  9177. abstract protected function validateAttribute($object,$attribute);
  9178. public static function createValidator($name,$object,$attributes,$params=array())
  9179. {
  9180. if(is_string($attributes))
  9181. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  9182. if(isset($params['on']))
  9183. {
  9184. if(is_array($params['on']))
  9185. $on=$params['on'];
  9186. else
  9187. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  9188. }
  9189. else
  9190. $on=array();
  9191. if(method_exists($object,$name))
  9192. {
  9193. $validator=new CInlineValidator;
  9194. $validator->attributes=$attributes;
  9195. $validator->method=$name;
  9196. $validator->params=$params;
  9197. if(isset($params['skipOnError']))
  9198. $validator->skipOnError=$params['skipOnError'];
  9199. }
  9200. else
  9201. {
  9202. $params['attributes']=$attributes;
  9203. if(isset(self::$builtInValidators[$name]))
  9204. $className=Yii::import(self::$builtInValidators[$name],true);
  9205. else
  9206. $className=Yii::import($name,true);
  9207. $validator=new $className;
  9208. foreach($params as $name=>$value)
  9209. $validator->$name=$value;
  9210. }
  9211. $validator->on=empty($on) ? array() : array_combine($on,$on);
  9212. return $validator;
  9213. }
  9214. public function validate($object,$attributes=null)
  9215. {
  9216. if(is_array($attributes))
  9217. $attributes=array_intersect($this->attributes,$attributes);
  9218. else
  9219. $attributes=$this->attributes;
  9220. foreach($attributes as $attribute)
  9221. {
  9222. if(!$this->skipOnError || !$object->hasErrors($attribute))
  9223. $this->validateAttribute($object,$attribute);
  9224. }
  9225. }
  9226. public function clientValidateAttribute($object,$attribute)
  9227. {
  9228. }
  9229. public function applyTo($scenario)
  9230. {
  9231. return empty($this->on) || isset($this->on[$scenario]);
  9232. }
  9233. protected function addError($object,$attribute,$message,$params=array())
  9234. {
  9235. $params['{attribute}']=$object->getAttributeLabel($attribute);
  9236. $object->addError($attribute,strtr($message,$params));
  9237. }
  9238. protected function isEmpty($value,$trim=false)
  9239. {
  9240. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  9241. }
  9242. }
  9243. class CStringValidator extends CValidator
  9244. {
  9245. public $max;
  9246. public $min;
  9247. public $is;
  9248. public $tooShort;
  9249. public $tooLong;
  9250. public $allowEmpty=true;
  9251. public $encoding;
  9252. protected function validateAttribute($object,$attribute)
  9253. {
  9254. $value=$object->$attribute;
  9255. if($this->allowEmpty && $this->isEmpty($value))
  9256. return;
  9257. if(function_exists('mb_strlen') && $this->encoding!==false)
  9258. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  9259. else
  9260. $length=strlen($value);
  9261. if($this->min!==null && $length<$this->min)
  9262. {
  9263. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9264. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9265. }
  9266. if($this->max!==null && $length>$this->max)
  9267. {
  9268. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9269. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9270. }
  9271. if($this->is!==null && $length!==$this->is)
  9272. {
  9273. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9274. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  9275. }
  9276. }
  9277. public function clientValidateAttribute($object,$attribute)
  9278. {
  9279. $label=$object->getAttributeLabel($attribute);
  9280. if(($message=$this->message)===null)
  9281. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  9282. $message=strtr($message, array(
  9283. '{attribute}'=>$label,
  9284. '{length}'=>$this->is,
  9285. ));
  9286. if(($tooShort=$this->tooShort)===null)
  9287. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  9288. $tooShort=strtr($tooShort, array(
  9289. '{attribute}'=>$label,
  9290. '{min}'=>$this->min,
  9291. ));
  9292. if(($tooLong=$this->tooLong)===null)
  9293. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  9294. $tooLong=strtr($tooLong, array(
  9295. '{attribute}'=>$label,
  9296. '{max}'=>$this->max,
  9297. ));
  9298. $js='';
  9299. if($this->min!==null)
  9300. {
  9301. $js.="
  9302. if(value.length<{$this->min}) {
  9303. messages.push(".CJSON::encode($tooShort).");
  9304. }
  9305. ";
  9306. }
  9307. if($this->max!==null)
  9308. {
  9309. $js.="
  9310. if(value.length>{$this->max}) {
  9311. messages.push(".CJSON::encode($tooLong).");
  9312. }
  9313. ";
  9314. }
  9315. if($this->is!==null)
  9316. {
  9317. $js.="
  9318. if(value.length!={$this->is}) {
  9319. messages.push(".CJSON::encode($message).");
  9320. }
  9321. ";
  9322. }
  9323. if($this->allowEmpty)
  9324. {
  9325. $js="
  9326. if($.trim(value)!='') {
  9327. $js
  9328. }
  9329. ";
  9330. }
  9331. return $js;
  9332. }
  9333. }
  9334. class CRequiredValidator extends CValidator
  9335. {
  9336. public $requiredValue;
  9337. public $strict=false;
  9338. protected function validateAttribute($object,$attribute)
  9339. {
  9340. $value=$object->$attribute;
  9341. if($this->requiredValue!==null)
  9342. {
  9343. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  9344. {
  9345. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  9346. array('{value}'=>$this->requiredValue));
  9347. $this->addError($object,$attribute,$message);
  9348. }
  9349. }
  9350. else if($this->isEmpty($value,true))
  9351. {
  9352. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  9353. $this->addError($object,$attribute,$message);
  9354. }
  9355. }
  9356. public function clientValidateAttribute($object,$attribute)
  9357. {
  9358. $message=$this->message;
  9359. if($this->requiredValue!==null)
  9360. {
  9361. if($message===null)
  9362. $message=Yii::t('yii','{attribute} must be {value}.');
  9363. $message=strtr($message, array(
  9364. '{value}'=>$this->requiredValue,
  9365. '{attribute}'=>$object->getAttributeLabel($attribute),
  9366. ));
  9367. return "
  9368. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  9369. messages.push(".CJSON::encode($message).");
  9370. }
  9371. ";
  9372. }
  9373. else
  9374. {
  9375. if($message===null)
  9376. $message=Yii::t('yii','{attribute} cannot be blank.');
  9377. $message=strtr($message, array(
  9378. '{attribute}'=>$object->getAttributeLabel($attribute),
  9379. ));
  9380. return "
  9381. if($.trim(value)=='') {
  9382. messages.push(".CJSON::encode($message).");
  9383. }
  9384. ";
  9385. }
  9386. }
  9387. }
  9388. class CNumberValidator extends CValidator
  9389. {
  9390. public $integerOnly=false;
  9391. public $allowEmpty=true;
  9392. public $max;
  9393. public $min;
  9394. public $tooBig;
  9395. public $tooSmall;
  9396. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  9397. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  9398. protected function validateAttribute($object,$attribute)
  9399. {
  9400. $value=$object->$attribute;
  9401. if($this->allowEmpty && $this->isEmpty($value))
  9402. return;
  9403. if($this->integerOnly)
  9404. {
  9405. if(!preg_match($this->integerPattern,"$value"))
  9406. {
  9407. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  9408. $this->addError($object,$attribute,$message);
  9409. }
  9410. }
  9411. else
  9412. {
  9413. if(!preg_match($this->numberPattern,"$value"))
  9414. {
  9415. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  9416. $this->addError($object,$attribute,$message);
  9417. }
  9418. }
  9419. if($this->min!==null && $value<$this->min)
  9420. {
  9421. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9422. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  9423. }
  9424. if($this->max!==null && $value>$this->max)
  9425. {
  9426. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9427. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  9428. }
  9429. }
  9430. public function clientValidateAttribute($object,$attribute)
  9431. {
  9432. $label=$object->getAttributeLabel($attribute);
  9433. if(($message=$this->message)===null)
  9434. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  9435. $message=strtr($message, array(
  9436. '{attribute}'=>$label,
  9437. ));
  9438. if(($tooBig=$this->tooBig)===null)
  9439. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  9440. $tooBig=strtr($tooBig, array(
  9441. '{attribute}'=>$label,
  9442. '{max}'=>$this->max,
  9443. ));
  9444. if(($tooSmall=$this->tooSmall)===null)
  9445. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  9446. $tooSmall=strtr($tooSmall, array(
  9447. '{attribute}'=>$label,
  9448. '{min}'=>$this->min,
  9449. ));
  9450. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  9451. $js="
  9452. if(!value.match($pattern)) {
  9453. messages.push(".CJSON::encode($message).");
  9454. }
  9455. ";
  9456. if($this->min!==null)
  9457. {
  9458. $js.="
  9459. if(value<{$this->min}) {
  9460. messages.push(".CJSON::encode($tooSmall).");
  9461. }
  9462. ";
  9463. }
  9464. if($this->max!==null)
  9465. {
  9466. $js.="
  9467. if(value>{$this->max}) {
  9468. messages.push(".CJSON::encode($tooBig).");
  9469. }
  9470. ";
  9471. }
  9472. if($this->allowEmpty)
  9473. {
  9474. $js="
  9475. if($.trim(value)!='') {
  9476. $js
  9477. }
  9478. ";
  9479. }
  9480. return $js;
  9481. }
  9482. }
  9483. class CListIterator implements Iterator
  9484. {
  9485. private $_d;
  9486. private $_i;
  9487. private $_c;
  9488. public function __construct(&$data)
  9489. {
  9490. $this->_d=&$data;
  9491. $this->_i=0;
  9492. $this->_c=count($this->_d);
  9493. }
  9494. public function rewind()
  9495. {
  9496. $this->_i=0;
  9497. }
  9498. public function key()
  9499. {
  9500. return $this->_i;
  9501. }
  9502. public function current()
  9503. {
  9504. return $this->_d[$this->_i];
  9505. }
  9506. public function next()
  9507. {
  9508. $this->_i++;
  9509. }
  9510. public function valid()
  9511. {
  9512. return $this->_i<$this->_c;
  9513. }
  9514. }
  9515. interface IApplicationComponent
  9516. {
  9517. public function init();
  9518. public function getIsInitialized();
  9519. }
  9520. interface ICache
  9521. {
  9522. public function get($id);
  9523. public function mget($ids);
  9524. public function set($id,$value,$expire=0,$dependency=null);
  9525. public function add($id,$value,$expire=0,$dependency=null);
  9526. public function delete($id);
  9527. public function flush();
  9528. }
  9529. interface ICacheDependency
  9530. {
  9531. public function evaluateDependency();
  9532. public function getHasChanged();
  9533. }
  9534. interface IStatePersister
  9535. {
  9536. public function load();
  9537. public function save($state);
  9538. }
  9539. interface IFilter
  9540. {
  9541. public function filter($filterChain);
  9542. }
  9543. interface IAction
  9544. {
  9545. public function getId();
  9546. public function getController();
  9547. }
  9548. interface IWebServiceProvider
  9549. {
  9550. public function beforeWebMethod($service);
  9551. public function afterWebMethod($service);
  9552. }
  9553. interface IViewRenderer
  9554. {
  9555. public function renderFile($context,$file,$data,$return);
  9556. }
  9557. interface IUserIdentity
  9558. {
  9559. public function authenticate();
  9560. public function getIsAuthenticated();
  9561. public function getId();
  9562. public function getName();
  9563. public function getPersistentStates();
  9564. }
  9565. interface IWebUser
  9566. {
  9567. public function getId();
  9568. public function getName();
  9569. public function getIsGuest();
  9570. public function checkAccess($operation,$params=array());
  9571. }
  9572. interface IAuthManager
  9573. {
  9574. public function checkAccess($itemName,$userId,$params=array());
  9575. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  9576. public function removeAuthItem($name);
  9577. public function getAuthItems($type=null,$userId=null);
  9578. public function getAuthItem($name);
  9579. public function saveAuthItem($item,$oldName=null);
  9580. public function addItemChild($itemName,$childName);
  9581. public function removeItemChild($itemName,$childName);
  9582. public function hasItemChild($itemName,$childName);
  9583. public function getItemChildren($itemName);
  9584. public function assign($itemName,$userId,$bizRule=null,$data=null);
  9585. public function revoke($itemName,$userId);
  9586. public function isAssigned($itemName,$userId);
  9587. public function getAuthAssignment($itemName,$userId);
  9588. public function getAuthAssignments($userId);
  9589. public function saveAuthAssignment($assignment);
  9590. public function clearAll();
  9591. public function clearAuthAssignments();
  9592. public function save();
  9593. public function executeBizRule($bizRule,$params,$data);
  9594. }
  9595. interface IBehavior
  9596. {
  9597. public function attach($component);
  9598. public function detach($component);
  9599. public function getEnabled();
  9600. public function setEnabled($value);
  9601. }
  9602. interface IWidgetFactory
  9603. {
  9604. public function createWidget($owner,$className,$properties=array());
  9605. }
  9606. interface IDataProvider
  9607. {
  9608. public function getId();
  9609. public function getItemCount($refresh=false);
  9610. public function getTotalItemCount($refresh=false);
  9611. public function getData($refresh=false);
  9612. public function getKeys($refresh=false);
  9613. public function getSort();
  9614. public function getPagination();
  9615. }
  9616. ?>