CApplication.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. <?php
  2. /**
  3. * CApplication class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CApplication is the base class for all application classes.
  12. *
  13. * An application serves as the global context that the user request
  14. * is being processed. It manages a set of application components that
  15. * provide specific functionalities to the whole application.
  16. *
  17. * The core application components provided by CApplication are the following:
  18. * <ul>
  19. * <li>{@link getErrorHandler errorHandler}: handles PHP errors and
  20. * uncaught exceptions. This application component is dynamically loaded when needed.</li>
  21. * <li>{@link getSecurityManager securityManager}: provides security-related
  22. * services, such as hashing, encryption. This application component is dynamically
  23. * loaded when needed.</li>
  24. * <li>{@link getStatePersister statePersister}: provides global state
  25. * persistence method. This application component is dynamically loaded when needed.</li>
  26. * <li>{@link getCache cache}: provides caching feature. This application component is
  27. * disabled by default.</li>
  28. * <li>{@link getMessages messages}: provides the message source for translating
  29. * application messages. This application component is dynamically loaded when needed.</li>
  30. * <li>{@link getCoreMessages coreMessages}: provides the message source for translating
  31. * Yii framework messages. This application component is dynamically loaded when needed.</li>
  32. * <li>{@link getUrlManager urlManager}: provides URL construction as well as parsing functionality.
  33. * This application component is dynamically loaded when needed.</li>
  34. * <li>{@link getRequest request}: represents the current HTTP request by encapsulating
  35. * the $_SERVER variable and managing cookies sent from and sent to the user.
  36. * This application component is dynamically loaded when needed.</li>
  37. * <li>{@link getFormat format}: provides a set of commonly used data formatting methods.
  38. * This application component is dynamically loaded when needed.</li>
  39. * </ul>
  40. *
  41. * CApplication will undergo the following lifecycles when processing a user request:
  42. * <ol>
  43. * <li>load application configuration;</li>
  44. * <li>set up error handling;</li>
  45. * <li>load static application components;</li>
  46. * <li>{@link onBeginRequest}: preprocess the user request;</li>
  47. * <li>{@link processRequest}: process the user request;</li>
  48. * <li>{@link onEndRequest}: postprocess the user request;</li>
  49. * </ol>
  50. *
  51. * Starting from lifecycle 3, if a PHP error or an uncaught exception occurs,
  52. * the application will switch to its error handling logic and jump to step 6 afterwards.
  53. *
  54. * @property string $id The unique identifier for the application.
  55. * @property string $basePath The root directory of the application. Defaults to 'protected'.
  56. * @property string $runtimePath The directory that stores runtime files. Defaults to 'protected/runtime'.
  57. * @property string $extensionPath The directory that contains all extensions. Defaults to the 'extensions' directory under 'protected'.
  58. * @property string $language The language that the user is using and the application should be targeted to.
  59. * Defaults to the {@link sourceLanguage source language}.
  60. * @property string $timeZone The time zone used by this application.
  61. * @property CLocale $locale The locale instance.
  62. * @property string $localeDataPath The directory that contains the locale data. It defaults to 'framework/i18n/data'.
  63. * @property CNumberFormatter $numberFormatter The locale-dependent number formatter.
  64. * The current {@link getLocale application locale} will be used.
  65. * @property CDateFormatter $dateFormatter The locale-dependent date formatter.
  66. * The current {@link getLocale application locale} will be used.
  67. * @property CDbConnection $db The database connection.
  68. * @property CErrorHandler $errorHandler The error handler application component.
  69. * @property CSecurityManager $securityManager The security manager application component.
  70. * @property CStatePersister $statePersister The state persister application component.
  71. * @property CCache $cache The cache application component. Null if the component is not enabled.
  72. * @property CPhpMessageSource $coreMessages The core message translations.
  73. * @property CMessageSource $messages The application message translations.
  74. * @property CHttpRequest $request The request component.
  75. * @property CUrlManager $urlManager The URL manager component.
  76. * @property CController $controller The currently active controller. Null is returned in this base class.
  77. * @property string $baseUrl The relative URL for the application.
  78. * @property string $homeUrl The homepage URL.
  79. *
  80. * @author Qiang Xue <qiang.xue@gmail.com>
  81. * @package system.base
  82. * @since 1.0
  83. */
  84. abstract class CApplication extends CModule
  85. {
  86. /**
  87. * @var string the application name. Defaults to 'My Application'.
  88. */
  89. public $name='My Application';
  90. /**
  91. * @var string the charset currently used for the application. Defaults to 'UTF-8'.
  92. */
  93. public $charset='UTF-8';
  94. /**
  95. * @var string the language that the application is written in. This mainly refers to
  96. * the language that the messages and view files are in. Defaults to 'en_us' (US English).
  97. */
  98. public $sourceLanguage='en_us';
  99. /**
  100. * @var string the class used to get locale data. Defaults to 'CLocale'.
  101. */
  102. public $localeClass='CLocale';
  103. private $_id;
  104. private $_basePath;
  105. private $_runtimePath;
  106. private $_extensionPath;
  107. private $_globalState;
  108. private $_stateChanged;
  109. private $_ended=false;
  110. private $_language;
  111. private $_homeUrl;
  112. /**
  113. * Processes the request.
  114. * This is the place where the actual request processing work is done.
  115. * Derived classes should override this method.
  116. */
  117. abstract public function processRequest();
  118. /**
  119. * Constructor.
  120. * @param mixed $config application configuration.
  121. * If a string, it is treated as the path of the file that contains the configuration;
  122. * If an array, it is the actual configuration information.
  123. * Please make sure you specify the {@link getBasePath basePath} property in the configuration,
  124. * which should point to the directory containing all application logic, template and data.
  125. * If not, the directory will be defaulted to 'protected'.
  126. */
  127. public function __construct($config=null)
  128. {
  129. Yii::setApplication($this);
  130. // set basePath at early as possible to avoid trouble
  131. if(is_string($config))
  132. $config=require($config);
  133. if(isset($config['basePath']))
  134. {
  135. $this->setBasePath($config['basePath']);
  136. unset($config['basePath']);
  137. }
  138. else
  139. $this->setBasePath('protected');
  140. Yii::setPathOfAlias('application',$this->getBasePath());
  141. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  142. if(isset($config['extensionPath']))
  143. {
  144. $this->setExtensionPath($config['extensionPath']);
  145. unset($config['extensionPath']);
  146. }
  147. else
  148. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  149. if(isset($config['aliases']))
  150. {
  151. $this->setAliases($config['aliases']);
  152. unset($config['aliases']);
  153. }
  154. $this->preinit();
  155. $this->initSystemHandlers();
  156. $this->registerCoreComponents();
  157. $this->configure($config);
  158. $this->attachBehaviors($this->behaviors);
  159. $this->preloadComponents();
  160. $this->init();
  161. }
  162. /**
  163. * Runs the application.
  164. * This method loads static application components. Derived classes usually overrides this
  165. * method to do more application-specific tasks.
  166. * Remember to call the parent implementation so that static application components are loaded.
  167. */
  168. public function run()
  169. {
  170. if($this->hasEventHandler('onBeginRequest'))
  171. $this->onBeginRequest(new CEvent($this));
  172. register_shutdown_function(array($this,'end'),0,false);
  173. $this->processRequest();
  174. if($this->hasEventHandler('onEndRequest'))
  175. $this->onEndRequest(new CEvent($this));
  176. }
  177. /**
  178. * Terminates the application.
  179. * This method replaces PHP's exit() function by calling
  180. * {@link onEndRequest} before exiting.
  181. * @param integer $status exit status (value 0 means normal exit while other values mean abnormal exit).
  182. * @param boolean $exit whether to exit the current request. This parameter has been available since version 1.1.5.
  183. * It defaults to true, meaning the PHP's exit() function will be called at the end of this method.
  184. */
  185. public function end($status=0,$exit=true)
  186. {
  187. if($this->hasEventHandler('onEndRequest'))
  188. $this->onEndRequest(new CEvent($this));
  189. if($exit)
  190. exit($status);
  191. }
  192. /**
  193. * Raised right BEFORE the application processes the request.
  194. * @param CEvent $event the event parameter
  195. */
  196. public function onBeginRequest($event)
  197. {
  198. $this->raiseEvent('onBeginRequest',$event);
  199. }
  200. /**
  201. * Raised right AFTER the application processes the request.
  202. * @param CEvent $event the event parameter
  203. */
  204. public function onEndRequest($event)
  205. {
  206. if(!$this->_ended)
  207. {
  208. $this->_ended=true;
  209. $this->raiseEvent('onEndRequest',$event);
  210. }
  211. }
  212. /**
  213. * Returns the unique identifier for the application.
  214. * @return string the unique identifier for the application.
  215. */
  216. public function getId()
  217. {
  218. if($this->_id!==null)
  219. return $this->_id;
  220. else
  221. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  222. }
  223. /**
  224. * Sets the unique identifier for the application.
  225. * @param string $id the unique identifier for the application.
  226. */
  227. public function setId($id)
  228. {
  229. $this->_id=$id;
  230. }
  231. /**
  232. * Returns the root path of the application.
  233. * @return string the root directory of the application. Defaults to 'protected'.
  234. */
  235. public function getBasePath()
  236. {
  237. return $this->_basePath;
  238. }
  239. /**
  240. * Sets the root directory of the application.
  241. * This method can only be invoked at the begin of the constructor.
  242. * @param string $path the root directory of the application.
  243. * @throws CException if the directory does not exist.
  244. */
  245. public function setBasePath($path)
  246. {
  247. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  248. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  249. array('{path}'=>$path)));
  250. }
  251. /**
  252. * Returns the directory that stores runtime files.
  253. * @return string the directory that stores runtime files. Defaults to 'protected/runtime'.
  254. */
  255. public function getRuntimePath()
  256. {
  257. if($this->_runtimePath!==null)
  258. return $this->_runtimePath;
  259. else
  260. {
  261. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  262. return $this->_runtimePath;
  263. }
  264. }
  265. /**
  266. * Sets the directory that stores runtime files.
  267. * @param string $path the directory that stores runtime files.
  268. * @throws CException if the directory does not exist or is not writable
  269. */
  270. public function setRuntimePath($path)
  271. {
  272. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  273. 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.',
  274. array('{path}'=>$path)));
  275. $this->_runtimePath=$runtimePath;
  276. }
  277. /**
  278. * Returns the root directory that holds all third-party extensions.
  279. * @return string the directory that contains all extensions. Defaults to the 'extensions' directory under 'protected'.
  280. */
  281. public function getExtensionPath()
  282. {
  283. return Yii::getPathOfAlias('ext');
  284. }
  285. /**
  286. * Sets the root directory that holds all third-party extensions.
  287. * @param string $path the directory that contains all third-party extensions.
  288. * @throws CException if the directory does not exist
  289. */
  290. public function setExtensionPath($path)
  291. {
  292. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  293. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  294. array('{path}'=>$path)));
  295. Yii::setPathOfAlias('ext',$extensionPath);
  296. }
  297. /**
  298. * Returns the language that the user is using and the application should be targeted to.
  299. * @return string the language that the user is using and the application should be targeted to.
  300. * Defaults to the {@link sourceLanguage source language}.
  301. */
  302. public function getLanguage()
  303. {
  304. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  305. }
  306. /**
  307. * Specifies which language the application is targeted to.
  308. *
  309. * This is the language that the application displays to end users.
  310. * If set null, it uses the {@link sourceLanguage source language}.
  311. *
  312. * Unless your application needs to support multiple languages, you should always
  313. * set this language to null to maximize the application's performance.
  314. * @param string $language the user language (e.g. 'en_US', 'zh_CN').
  315. * If it is null, the {@link sourceLanguage} will be used.
  316. */
  317. public function setLanguage($language)
  318. {
  319. $this->_language=$language;
  320. }
  321. /**
  322. * Returns the time zone used by this application.
  323. * This is a simple wrapper of PHP function date_default_timezone_get().
  324. * @return string the time zone used by this application.
  325. * @see http://php.net/manual/en/function.date-default-timezone-get.php
  326. */
  327. public function getTimeZone()
  328. {
  329. return date_default_timezone_get();
  330. }
  331. /**
  332. * Sets the time zone used by this application.
  333. * This is a simple wrapper of PHP function date_default_timezone_set().
  334. * @param string $value the time zone used by this application.
  335. * @see http://php.net/manual/en/function.date-default-timezone-set.php
  336. */
  337. public function setTimeZone($value)
  338. {
  339. date_default_timezone_set($value);
  340. }
  341. /**
  342. * Returns the localized version of a specified file.
  343. *
  344. * The searching is based on the specified language code. In particular,
  345. * a file with the same name will be looked for under the subdirectory
  346. * named as the locale ID. For example, given the file "path/to/view.php"
  347. * and locale ID "zh_cn", the localized file will be looked for as
  348. * "path/to/zh_cn/view.php". If the file is not found, the original file
  349. * will be returned.
  350. *
  351. * For consistency, it is recommended that the locale ID is given
  352. * in lower case and in the format of LanguageID_RegionID (e.g. "en_us").
  353. *
  354. * @param string $srcFile the original file
  355. * @param string $srcLanguage the language that the original file is in. If null, the application {@link sourceLanguage source language} is used.
  356. * @param string $language the desired language that the file should be localized to. If null, the {@link getLanguage application language} will be used.
  357. * @return string the matching localized file. The original file is returned if no localized version is found
  358. * or if source language is the same as the desired language.
  359. */
  360. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  361. {
  362. if($srcLanguage===null)
  363. $srcLanguage=$this->sourceLanguage;
  364. if($language===null)
  365. $language=$this->getLanguage();
  366. if($language===$srcLanguage)
  367. return $srcFile;
  368. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  369. return is_file($desiredFile) ? $desiredFile : $srcFile;
  370. }
  371. /**
  372. * Returns the locale instance.
  373. * @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used.
  374. * @return an instance of CLocale
  375. */
  376. public function getLocale($localeID=null)
  377. {
  378. return call_user_func_array(array($this->localeClass, 'getInstance'),array($localeID===null?$this->getLanguage():$localeID));
  379. }
  380. /**
  381. * Returns the directory that contains the locale data.
  382. * @return string the directory that contains the locale data. It defaults to 'framework/i18n/data'.
  383. * @since 1.1.0
  384. */
  385. public function getLocaleDataPath()
  386. {
  387. $vars=get_class_vars($this->localeClass);
  388. if(empty($vars['dataPath']))
  389. return Yii::getPathOfAlias('system.i18n.data');
  390. return $vars['dataPath'];
  391. }
  392. /**
  393. * Sets the directory that contains the locale data.
  394. * @param string $value the directory that contains the locale data.
  395. * @since 1.1.0
  396. */
  397. public function setLocaleDataPath($value)
  398. {
  399. $property=new ReflectionProperty($this->localeClass,'dataPath');
  400. $property->setValue($value);
  401. }
  402. /**
  403. * @return CNumberFormatter the locale-dependent number formatter.
  404. * The current {@link getLocale application locale} will be used.
  405. */
  406. public function getNumberFormatter()
  407. {
  408. return $this->getLocale()->getNumberFormatter();
  409. }
  410. /**
  411. * Returns the locale-dependent date formatter.
  412. * @return CDateFormatter the locale-dependent date formatter.
  413. * The current {@link getLocale application locale} will be used.
  414. */
  415. public function getDateFormatter()
  416. {
  417. return $this->getLocale()->getDateFormatter();
  418. }
  419. /**
  420. * Returns the database connection component.
  421. * @return CDbConnection the database connection
  422. */
  423. public function getDb()
  424. {
  425. return $this->getComponent('db');
  426. }
  427. /**
  428. * Returns the error handler component.
  429. * @return CErrorHandler the error handler application component.
  430. */
  431. public function getErrorHandler()
  432. {
  433. return $this->getComponent('errorHandler');
  434. }
  435. /**
  436. * Returns the security manager component.
  437. * @return CSecurityManager the security manager application component.
  438. */
  439. public function getSecurityManager()
  440. {
  441. return $this->getComponent('securityManager');
  442. }
  443. /**
  444. * Returns the state persister component.
  445. * @return CStatePersister the state persister application component.
  446. */
  447. public function getStatePersister()
  448. {
  449. return $this->getComponent('statePersister');
  450. }
  451. /**
  452. * Returns the cache component.
  453. * @return CCache the cache application component. Null if the component is not enabled.
  454. */
  455. public function getCache()
  456. {
  457. return $this->getComponent('cache');
  458. }
  459. /**
  460. * Returns the core message translations component.
  461. * @return CPhpMessageSource the core message translations
  462. */
  463. public function getCoreMessages()
  464. {
  465. return $this->getComponent('coreMessages');
  466. }
  467. /**
  468. * Returns the application message translations component.
  469. * @return CMessageSource the application message translations
  470. */
  471. public function getMessages()
  472. {
  473. return $this->getComponent('messages');
  474. }
  475. /**
  476. * Returns the request component.
  477. * @return CHttpRequest the request component
  478. */
  479. public function getRequest()
  480. {
  481. return $this->getComponent('request');
  482. }
  483. /**
  484. * Returns the URL manager component.
  485. * @return CUrlManager the URL manager component
  486. */
  487. public function getUrlManager()
  488. {
  489. return $this->getComponent('urlManager');
  490. }
  491. /**
  492. * @return CController the currently active controller. Null is returned in this base class.
  493. * @since 1.1.8
  494. */
  495. public function getController()
  496. {
  497. return null;
  498. }
  499. /**
  500. * Creates a relative URL based on the given controller and action information.
  501. * @param string $route the URL route. This should be in the format of 'ControllerID/ActionID'.
  502. * @param array $params additional GET parameters (name=>value). Both the name and value will be URL-encoded.
  503. * @param string $ampersand the token separating name-value pairs in the URL.
  504. * @return string the constructed URL
  505. */
  506. public function createUrl($route,$params=array(),$ampersand='&')
  507. {
  508. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  509. }
  510. /**
  511. * Creates an absolute URL based on the given controller and action information.
  512. * @param string $route the URL route. This should be in the format of 'ControllerID/ActionID'.
  513. * @param array $params additional GET parameters (name=>value). Both the name and value will be URL-encoded.
  514. * @param string $schema schema to use (e.g. http, https). If empty, the schema used for the current request will be used.
  515. * @param string $ampersand the token separating name-value pairs in the URL.
  516. * @return string the constructed URL
  517. */
  518. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  519. {
  520. $url=$this->createUrl($route,$params,$ampersand);
  521. if(strpos($url,'http')===0)
  522. return $url;
  523. else
  524. return $this->getRequest()->getHostInfo($schema).$url;
  525. }
  526. /**
  527. * Returns the relative URL for the application.
  528. * This is a shortcut method to {@link CHttpRequest::getBaseUrl()}.
  529. * @param boolean $absolute whether to return an absolute URL. Defaults to false, meaning returning a relative one.
  530. * @return string the relative URL for the application
  531. * @see CHttpRequest::getBaseUrl()
  532. */
  533. public function getBaseUrl($absolute=false)
  534. {
  535. return $this->getRequest()->getBaseUrl($absolute);
  536. }
  537. /**
  538. * @return string the homepage URL
  539. */
  540. public function getHomeUrl()
  541. {
  542. if($this->_homeUrl===null)
  543. {
  544. if($this->getUrlManager()->showScriptName)
  545. return $this->getRequest()->getScriptUrl();
  546. else
  547. return $this->getRequest()->getBaseUrl().'/';
  548. }
  549. else
  550. return $this->_homeUrl;
  551. }
  552. /**
  553. * @param string $value the homepage URL
  554. */
  555. public function setHomeUrl($value)
  556. {
  557. $this->_homeUrl=$value;
  558. }
  559. /**
  560. * Returns a global value.
  561. *
  562. * A global value is one that is persistent across users sessions and requests.
  563. * @param string $key the name of the value to be returned
  564. * @param mixed $defaultValue the default value. If the named global value is not found, this will be returned instead.
  565. * @return mixed the named global value
  566. * @see setGlobalState
  567. */
  568. public function getGlobalState($key,$defaultValue=null)
  569. {
  570. if($this->_globalState===null)
  571. $this->loadGlobalState();
  572. if(isset($this->_globalState[$key]))
  573. return $this->_globalState[$key];
  574. else
  575. return $defaultValue;
  576. }
  577. /**
  578. * Sets a global value.
  579. *
  580. * A global value is one that is persistent across users sessions and requests.
  581. * Make sure that the value is serializable and unserializable.
  582. * @param string $key the name of the value to be saved
  583. * @param mixed $value the global value to be saved. It must be serializable.
  584. * @param mixed $defaultValue the default value. If the named global value is the same as this value, it will be cleared from the current storage.
  585. * @see getGlobalState
  586. */
  587. public function setGlobalState($key,$value,$defaultValue=null)
  588. {
  589. if($this->_globalState===null)
  590. $this->loadGlobalState();
  591. $changed=$this->_stateChanged;
  592. if($value===$defaultValue)
  593. {
  594. if(isset($this->_globalState[$key]))
  595. {
  596. unset($this->_globalState[$key]);
  597. $this->_stateChanged=true;
  598. }
  599. }
  600. elseif(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  601. {
  602. $this->_globalState[$key]=$value;
  603. $this->_stateChanged=true;
  604. }
  605. if($this->_stateChanged!==$changed)
  606. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  607. }
  608. /**
  609. * Clears a global value.
  610. *
  611. * The value cleared will no longer be available in this request and the following requests.
  612. * @param string $key the name of the value to be cleared
  613. */
  614. public function clearGlobalState($key)
  615. {
  616. $this->setGlobalState($key,true,true);
  617. }
  618. /**
  619. * Loads the global state data from persistent storage.
  620. * @see getStatePersister
  621. * @throws CException if the state persister is not available
  622. */
  623. public function loadGlobalState()
  624. {
  625. $persister=$this->getStatePersister();
  626. if(($this->_globalState=$persister->load())===null)
  627. $this->_globalState=array();
  628. $this->_stateChanged=false;
  629. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  630. }
  631. /**
  632. * Saves the global state data into persistent storage.
  633. * @see getStatePersister
  634. * @throws CException if the state persister is not available
  635. */
  636. public function saveGlobalState()
  637. {
  638. if($this->_stateChanged)
  639. {
  640. $this->_stateChanged=false;
  641. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  642. $this->getStatePersister()->save($this->_globalState);
  643. }
  644. }
  645. /**
  646. * Handles uncaught PHP exceptions.
  647. *
  648. * This method is implemented as a PHP exception handler. It requires
  649. * that constant YII_ENABLE_EXCEPTION_HANDLER be defined true.
  650. *
  651. * This method will first raise an {@link onException} event.
  652. * If the exception is not handled by any event handler, it will call
  653. * {@link getErrorHandler errorHandler} to process the exception.
  654. *
  655. * The application will be terminated by this method.
  656. *
  657. * @param Exception $exception exception that is not caught
  658. */
  659. public function handleException($exception)
  660. {
  661. // disable error capturing to avoid recursive errors
  662. restore_error_handler();
  663. restore_exception_handler();
  664. $category='exception.'.get_class($exception);
  665. if($exception instanceof CHttpException)
  666. $category.='.'.$exception->statusCode;
  667. // php <5.2 doesn't support string conversion auto-magically
  668. $message=$exception->__toString();
  669. if(isset($_SERVER['REQUEST_URI']))
  670. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  671. if(isset($_SERVER['HTTP_REFERER']))
  672. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  673. $message.="\n---";
  674. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  675. try
  676. {
  677. $event=new CExceptionEvent($this,$exception);
  678. $this->onException($event);
  679. if(!$event->handled)
  680. {
  681. // try an error handler
  682. if(($handler=$this->getErrorHandler())!==null)
  683. $handler->handle($event);
  684. else
  685. $this->displayException($exception);
  686. }
  687. }
  688. catch(Exception $e)
  689. {
  690. $this->displayException($e);
  691. }
  692. try
  693. {
  694. $this->end(1);
  695. }
  696. catch(Exception $e)
  697. {
  698. // use the most primitive way to log error
  699. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  700. $msg .= $e->getTraceAsString()."\n";
  701. $msg .= "Previous exception:\n";
  702. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  703. $msg .= $exception->getTraceAsString()."\n";
  704. $msg .= '$_SERVER='.var_export($_SERVER,true);
  705. error_log($msg);
  706. exit(1);
  707. }
  708. }
  709. /**
  710. * Handles PHP execution errors such as warnings, notices.
  711. *
  712. * This method is implemented as a PHP error handler. It requires
  713. * that constant YII_ENABLE_ERROR_HANDLER be defined true.
  714. *
  715. * This method will first raise an {@link onError} event.
  716. * If the error is not handled by any event handler, it will call
  717. * {@link getErrorHandler errorHandler} to process the error.
  718. *
  719. * The application will be terminated by this method.
  720. *
  721. * @param integer $code the level of the error raised
  722. * @param string $message the error message
  723. * @param string $file the filename that the error was raised in
  724. * @param integer $line the line number the error was raised at
  725. */
  726. public function handleError($code,$message,$file,$line)
  727. {
  728. if($code & error_reporting())
  729. {
  730. // disable error capturing to avoid recursive errors
  731. restore_error_handler();
  732. restore_exception_handler();
  733. $log="$message ($file:$line)\nStack trace:\n";
  734. $trace=debug_backtrace();
  735. // skip the first 3 stacks as they do not tell the error position
  736. if(count($trace)>3)
  737. $trace=array_slice($trace,3);
  738. foreach($trace as $i=>$t)
  739. {
  740. if(!isset($t['file']))
  741. $t['file']='unknown';
  742. if(!isset($t['line']))
  743. $t['line']=0;
  744. if(!isset($t['function']))
  745. $t['function']='unknown';
  746. $log.="#$i {$t['file']}({$t['line']}): ";
  747. if(isset($t['object']) && is_object($t['object']))
  748. $log.=get_class($t['object']).'->';
  749. $log.="{$t['function']}()\n";
  750. }
  751. if(isset($_SERVER['REQUEST_URI']))
  752. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  753. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  754. try
  755. {
  756. Yii::import('CErrorEvent',true);
  757. $event=new CErrorEvent($this,$code,$message,$file,$line);
  758. $this->onError($event);
  759. if(!$event->handled)
  760. {
  761. // try an error handler
  762. if(($handler=$this->getErrorHandler())!==null)
  763. $handler->handle($event);
  764. else
  765. $this->displayError($code,$message,$file,$line);
  766. }
  767. }
  768. catch(Exception $e)
  769. {
  770. $this->displayException($e);
  771. }
  772. try
  773. {
  774. $this->end(1);
  775. }
  776. catch(Exception $e)
  777. {
  778. // use the most primitive way to log error
  779. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  780. $msg .= $e->getTraceAsString()."\n";
  781. $msg .= "Previous error:\n";
  782. $msg .= $log."\n";
  783. $msg .= '$_SERVER='.var_export($_SERVER,true);
  784. error_log($msg);
  785. exit(1);
  786. }
  787. }
  788. }
  789. /**
  790. * Raised when an uncaught PHP exception occurs.
  791. *
  792. * An event handler can set the {@link CExceptionEvent::handled handled}
  793. * property of the event parameter to be true to indicate no further error
  794. * handling is needed. Otherwise, the {@link getErrorHandler errorHandler}
  795. * application component will continue processing the error.
  796. *
  797. * @param CExceptionEvent $event event parameter
  798. */
  799. public function onException($event)
  800. {
  801. $this->raiseEvent('onException',$event);
  802. }
  803. /**
  804. * Raised when a PHP execution error occurs.
  805. *
  806. * An event handler can set the {@link CErrorEvent::handled handled}
  807. * property of the event parameter to be true to indicate no further error
  808. * handling is needed. Otherwise, the {@link getErrorHandler errorHandler}
  809. * application component will continue processing the error.
  810. *
  811. * @param CErrorEvent $event event parameter
  812. */
  813. public function onError($event)
  814. {
  815. $this->raiseEvent('onError',$event);
  816. }
  817. /**
  818. * Displays the captured PHP error.
  819. * This method displays the error in HTML when there is
  820. * no active error handler.
  821. * @param integer $code error code
  822. * @param string $message error message
  823. * @param string $file error file
  824. * @param string $line error line
  825. */
  826. public function displayError($code,$message,$file,$line)
  827. {
  828. if(YII_DEBUG)
  829. {
  830. echo "<h1>PHP Error [$code]</h1>\n";
  831. echo "<p>$message ($file:$line)</p>\n";
  832. echo '<pre>';
  833. $trace=debug_backtrace();
  834. // skip the first 3 stacks as they do not tell the error position
  835. if(count($trace)>3)
  836. $trace=array_slice($trace,3);
  837. foreach($trace as $i=>$t)
  838. {
  839. if(!isset($t['file']))
  840. $t['file']='unknown';
  841. if(!isset($t['line']))
  842. $t['line']=0;
  843. if(!isset($t['function']))
  844. $t['function']='unknown';
  845. echo "#$i {$t['file']}({$t['line']}): ";
  846. if(isset($t['object']) && is_object($t['object']))
  847. echo get_class($t['object']).'->';
  848. echo "{$t['function']}()\n";
  849. }
  850. echo '</pre>';
  851. }
  852. else
  853. {
  854. echo "<h1>PHP Error [$code]</h1>\n";
  855. echo "<p>$message</p>\n";
  856. }
  857. }
  858. /**
  859. * Displays the uncaught PHP exception.
  860. * This method displays the exception in HTML when there is
  861. * no active error handler.
  862. * @param Exception $exception the uncaught exception
  863. */
  864. public function displayException($exception)
  865. {
  866. if(YII_DEBUG)
  867. {
  868. echo '<h1>'.get_class($exception)."</h1>\n";
  869. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  870. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  871. }
  872. else
  873. {
  874. echo '<h1>'.get_class($exception)."</h1>\n";
  875. echo '<p>'.$exception->getMessage().'</p>';
  876. }
  877. }
  878. /**
  879. * Initializes the error handlers.
  880. */
  881. protected function initSystemHandlers()
  882. {
  883. if(YII_ENABLE_EXCEPTION_HANDLER)
  884. set_exception_handler(array($this,'handleException'));
  885. if(YII_ENABLE_ERROR_HANDLER)
  886. set_error_handler(array($this,'handleError'),error_reporting());
  887. }
  888. /**
  889. * Registers the core application components.
  890. * @see setComponents
  891. */
  892. protected function registerCoreComponents()
  893. {
  894. $components=array(
  895. 'coreMessages'=>array(
  896. 'class'=>'CPhpMessageSource',
  897. 'language'=>'en_us',
  898. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  899. ),
  900. 'db'=>array(
  901. 'class'=>'CDbConnection',
  902. ),
  903. 'messages'=>array(
  904. 'class'=>'CPhpMessageSource',
  905. ),
  906. 'errorHandler'=>array(
  907. 'class'=>'CErrorHandler',
  908. ),
  909. 'securityManager'=>array(
  910. 'class'=>'CSecurityManager',
  911. ),
  912. 'statePersister'=>array(
  913. 'class'=>'CStatePersister',
  914. ),
  915. 'urlManager'=>array(
  916. 'class'=>'CUrlManager',
  917. ),
  918. 'request'=>array(
  919. 'class'=>'CHttpRequest',
  920. ),
  921. 'format'=>array(
  922. 'class'=>'CFormatter',
  923. ),
  924. );
  925. $this->setComponents($components);
  926. }
  927. }