Application.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. use Yii;
  9. use yii\helpers\Console;
  10. use yii\web\HttpException;
  11. /**
  12. * Application is the base class for all application classes.
  13. *
  14. * @property \yii\rbac\Manager $authManager The auth manager for this application. This property is read-only.
  15. * @property string $basePath The root directory of the application.
  16. * @property \yii\caching\Cache $cache The cache application component. Null if the component is not enabled.
  17. * This property is read-only.
  18. * @property \yii\db\Connection $db The database connection. This property is read-only.
  19. * @property ErrorHandler $errorHandler The error handler application component. This property is read-only.
  20. * @property \yii\base\Formatter $formatter The formatter application component. This property is read-only.
  21. * @property \yii\i18n\I18N $i18n The internationalization component. This property is read-only.
  22. * @property \yii\log\Logger $log The log component. This property is read-only.
  23. * @property \yii\mail\MailerInterface $mail The mailer interface. This property is read-only.
  24. * @property \yii\web\Request|\yii\console\Request $request The request component. This property is read-only.
  25. * @property string $runtimePath The directory that stores runtime files. Defaults to the "runtime"
  26. * subdirectory under [[basePath]].
  27. * @property string $timeZone The time zone used by this application.
  28. * @property string $uniqueId The unique ID of the module. This property is read-only.
  29. * @property \yii\web\UrlManager $urlManager The URL manager for this application. This property is read-only.
  30. * @property string $vendorPath The directory that stores vendor files. Defaults to "vendor" directory under
  31. * [[basePath]].
  32. * @property View|\yii\web\View $view The view object that is used to render various view files. This property
  33. * is read-only.
  34. *
  35. * @author Qiang Xue <[email protected]>
  36. * @since 2.0
  37. */
  38. abstract class Application extends Module
  39. {
  40. /**
  41. * @event Event an event raised before the application starts to handle a request.
  42. */
  43. const EVENT_BEFORE_REQUEST = 'beforeRequest';
  44. /**
  45. * @event Event an event raised after the application successfully handles a request (before the response is sent out).
  46. */
  47. const EVENT_AFTER_REQUEST = 'afterRequest';
  48. /**
  49. * @event ActionEvent an event raised before executing a controller action.
  50. * You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
  51. */
  52. const EVENT_BEFORE_ACTION = 'beforeAction';
  53. /**
  54. * @event ActionEvent an event raised after executing a controller action.
  55. */
  56. const EVENT_AFTER_ACTION = 'afterAction';
  57. /**
  58. * @var string the namespace that controller classes are in. If not set,
  59. * it will use the "app\controllers" namespace.
  60. */
  61. public $controllerNamespace = 'app\\controllers';
  62. /**
  63. * @var string the application name.
  64. */
  65. public $name = 'My Application';
  66. /**
  67. * @var string the version of this application.
  68. */
  69. public $version = '1.0';
  70. /**
  71. * @var string the charset currently used for the application.
  72. */
  73. public $charset = 'UTF-8';
  74. /**
  75. * @var string the language that is meant to be used for end users.
  76. * @see sourceLanguage
  77. */
  78. public $language = 'en-US';
  79. /**
  80. * @var string the language that the application is written in. This mainly refers to
  81. * the language that the messages and view files are written in.
  82. * @see language
  83. */
  84. public $sourceLanguage = 'en-US';
  85. /**
  86. * @var Controller the currently active controller instance
  87. */
  88. public $controller;
  89. /**
  90. * @var string|boolean the layout that should be applied for views in this application. Defaults to 'main'.
  91. * If this is false, layout will be disabled.
  92. */
  93. public $layout = 'main';
  94. /**
  95. * @var integer the size of the reserved memory. A portion of memory is pre-allocated so that
  96. * when an out-of-memory issue occurs, the error handler is able to handle the error with
  97. * the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
  98. * Defaults to 256KB.
  99. */
  100. public $memoryReserveSize = 262144;
  101. /**
  102. * @var string the requested route
  103. */
  104. public $requestedRoute;
  105. /**
  106. * @var Action the requested Action. If null, it means the request cannot be resolved into an action.
  107. */
  108. public $requestedAction;
  109. /**
  110. * @var array the parameters supplied to the requested action.
  111. */
  112. public $requestedParams;
  113. /**
  114. * @var array list of installed Yii extensions. Each array element represents a single extension
  115. * with the following structure:
  116. *
  117. * ~~~
  118. * [
  119. * 'name' => 'extension name',
  120. * 'version' => 'version number',
  121. * 'bootstrap' => 'BootstrapClassName',
  122. * ]
  123. * ~~~
  124. */
  125. public $extensions = [];
  126. /**
  127. * @var \Exception the exception that is being handled currently. When this is not null,
  128. * it means the application is handling some exception and extra care should be taken.
  129. */
  130. public $exception;
  131. /**
  132. * @var string Used to reserve memory for fatal error handler.
  133. */
  134. private $_memoryReserve;
  135. /**
  136. * Constructor.
  137. * @param array $config name-value pairs that will be used to initialize the object properties.
  138. * Note that the configuration must contain both [[id]] and [[basePath]].
  139. * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
  140. */
  141. public function __construct($config = [])
  142. {
  143. Yii::$app = $this;
  144. $this->preInit($config);
  145. $this->registerErrorHandlers();
  146. $this->registerCoreComponents();
  147. Component::__construct($config);
  148. }
  149. /**
  150. * Pre-initializes the application.
  151. * This method is called at the beginning of the application constructor.
  152. * It initializes several important application properties.
  153. * If you override this method, please make sure you call the parent implementation.
  154. * @param array $config the application configuration
  155. * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
  156. */
  157. public function preInit(&$config)
  158. {
  159. if (!isset($config['id'])) {
  160. throw new InvalidConfigException('The "id" configuration is required.');
  161. }
  162. if (isset($config['basePath'])) {
  163. $this->setBasePath($config['basePath']);
  164. unset($config['basePath']);
  165. } else {
  166. throw new InvalidConfigException('The "basePath" configuration is required.');
  167. }
  168. if (isset($config['vendorPath'])) {
  169. $this->setVendorPath($config['vendorPath']);
  170. unset($config['vendorPath']);
  171. } else {
  172. // set "@vendor"
  173. $this->getVendorPath();
  174. }
  175. if (isset($config['runtimePath'])) {
  176. $this->setRuntimePath($config['runtimePath']);
  177. unset($config['runtimePath']);
  178. } else {
  179. // set "@runtime"
  180. $this->getRuntimePath();
  181. }
  182. if (isset($config['timeZone'])) {
  183. $this->setTimeZone($config['timeZone']);
  184. unset($config['timeZone']);
  185. } elseif (!ini_get('date.timezone')) {
  186. $this->setTimeZone('UTC');
  187. }
  188. }
  189. /**
  190. * @inheritdoc
  191. */
  192. public function init()
  193. {
  194. $this->initExtensions($this->extensions);
  195. parent::init();
  196. }
  197. /**
  198. * Initializes the extensions.
  199. * @param array $extensions the extensions to be initialized. Please refer to [[extensions]]
  200. * for the structure of the extension array.
  201. */
  202. protected function initExtensions($extensions)
  203. {
  204. foreach ($extensions as $extension) {
  205. if (!empty($extension['alias'])) {
  206. foreach ($extension['alias'] as $name => $path) {
  207. Yii::setAlias($name, $path);
  208. }
  209. }
  210. if (isset($extension['bootstrap'])) {
  211. /** @var Extension $class */
  212. $class = $extension['bootstrap'];
  213. $class::init();
  214. }
  215. }
  216. }
  217. /**
  218. * Loads components that are declared in [[preload]].
  219. * @throws InvalidConfigException if a component or module to be preloaded is unknown
  220. */
  221. public function preloadComponents()
  222. {
  223. $this->getComponent('log');
  224. parent::preloadComponents();
  225. }
  226. /**
  227. * Registers error handlers.
  228. */
  229. public function registerErrorHandlers()
  230. {
  231. if (YII_ENABLE_ERROR_HANDLER) {
  232. ini_set('display_errors', 0);
  233. set_exception_handler([$this, 'handleException']);
  234. set_error_handler([$this, 'handleError'], error_reporting());
  235. if ($this->memoryReserveSize > 0) {
  236. $this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
  237. }
  238. register_shutdown_function([$this, 'handleFatalError']);
  239. }
  240. }
  241. /**
  242. * Returns an ID that uniquely identifies this module among all modules within the current application.
  243. * Since this is an application instance, it will always return an empty string.
  244. * @return string the unique ID of the module.
  245. */
  246. public function getUniqueId()
  247. {
  248. return '';
  249. }
  250. /**
  251. * Sets the root directory of the application and the @app alias.
  252. * This method can only be invoked at the beginning of the constructor.
  253. * @param string $path the root directory of the application.
  254. * @property string the root directory of the application.
  255. * @throws InvalidParamException if the directory does not exist.
  256. */
  257. public function setBasePath($path)
  258. {
  259. parent::setBasePath($path);
  260. Yii::setAlias('@app', $this->getBasePath());
  261. }
  262. /**
  263. * Runs the application.
  264. * This is the main entrance of an application.
  265. * @return integer the exit status (0 means normal, non-zero values mean abnormal)
  266. */
  267. public function run()
  268. {
  269. $this->trigger(self::EVENT_BEFORE_REQUEST);
  270. $response = $this->handleRequest($this->getRequest());
  271. $this->trigger(self::EVENT_AFTER_REQUEST);
  272. $response->send();
  273. return $response->exitStatus;
  274. }
  275. /**
  276. * Handles the specified request.
  277. *
  278. * This method should return an instance of [[Response]] or its child class
  279. * which represents the handling result of the request.
  280. *
  281. * @param Request $request the request to be handled
  282. * @return Response the resulting response
  283. */
  284. abstract public function handleRequest($request);
  285. private $_runtimePath;
  286. /**
  287. * Returns the directory that stores runtime files.
  288. * @return string the directory that stores runtime files.
  289. * Defaults to the "runtime" subdirectory under [[basePath]].
  290. */
  291. public function getRuntimePath()
  292. {
  293. if ($this->_runtimePath === null) {
  294. $this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
  295. }
  296. return $this->_runtimePath;
  297. }
  298. /**
  299. * Sets the directory that stores runtime files.
  300. * @param string $path the directory that stores runtime files.
  301. */
  302. public function setRuntimePath($path)
  303. {
  304. $this->_runtimePath = Yii::getAlias($path);
  305. Yii::setAlias('@runtime', $this->_runtimePath);
  306. }
  307. private $_vendorPath;
  308. /**
  309. * Returns the directory that stores vendor files.
  310. * @return string the directory that stores vendor files.
  311. * Defaults to "vendor" directory under [[basePath]].
  312. */
  313. public function getVendorPath()
  314. {
  315. if ($this->_vendorPath === null) {
  316. $this->setVendorPath($this->getBasePath() . DIRECTORY_SEPARATOR . 'vendor');
  317. }
  318. return $this->_vendorPath;
  319. }
  320. /**
  321. * Sets the directory that stores vendor files.
  322. * @param string $path the directory that stores vendor files.
  323. */
  324. public function setVendorPath($path)
  325. {
  326. $this->_vendorPath = Yii::getAlias($path);
  327. Yii::setAlias('@vendor', $this->_vendorPath);
  328. }
  329. /**
  330. * Returns the time zone used by this application.
  331. * This is a simple wrapper of PHP function date_default_timezone_get().
  332. * If time zone is not configured in php.ini or application config,
  333. * it will be set to UTC by default.
  334. * @return string the time zone used by this application.
  335. * @see http://php.net/manual/en/function.date-default-timezone-get.php
  336. */
  337. public function getTimeZone()
  338. {
  339. return date_default_timezone_get();
  340. }
  341. /**
  342. * Sets the time zone used by this application.
  343. * This is a simple wrapper of PHP function date_default_timezone_set().
  344. * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available timezones.
  345. * @param string $value the time zone used by this application.
  346. * @see http://php.net/manual/en/function.date-default-timezone-set.php
  347. */
  348. public function setTimeZone($value)
  349. {
  350. date_default_timezone_set($value);
  351. }
  352. /**
  353. * Returns the database connection component.
  354. * @return \yii\db\Connection the database connection
  355. */
  356. public function getDb()
  357. {
  358. return $this->getComponent('db');
  359. }
  360. /**
  361. * Returns the log component.
  362. * @return \yii\log\Logger the log component
  363. */
  364. public function getLog()
  365. {
  366. return $this->getComponent('log');
  367. }
  368. /**
  369. * Returns the error handler component.
  370. * @return ErrorHandler the error handler application component.
  371. */
  372. public function getErrorHandler()
  373. {
  374. return $this->getComponent('errorHandler');
  375. }
  376. /**
  377. * Returns the cache component.
  378. * @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
  379. */
  380. public function getCache()
  381. {
  382. return $this->getComponent('cache');
  383. }
  384. /**
  385. * Returns the formatter component.
  386. * @return \yii\base\Formatter the formatter application component.
  387. */
  388. public function getFormatter()
  389. {
  390. return $this->getComponent('formatter');
  391. }
  392. /**
  393. * Returns the request component.
  394. * @return \yii\web\Request|\yii\console\Request the request component
  395. */
  396. public function getRequest()
  397. {
  398. return $this->getComponent('request');
  399. }
  400. /**
  401. * Returns the view object.
  402. * @return View|\yii\web\View the view object that is used to render various view files.
  403. */
  404. public function getView()
  405. {
  406. return $this->getComponent('view');
  407. }
  408. /**
  409. * Returns the URL manager for this application.
  410. * @return \yii\web\UrlManager the URL manager for this application.
  411. */
  412. public function getUrlManager()
  413. {
  414. return $this->getComponent('urlManager');
  415. }
  416. /**
  417. * Returns the internationalization (i18n) component
  418. * @return \yii\i18n\I18N the internationalization component
  419. */
  420. public function getI18n()
  421. {
  422. return $this->getComponent('i18n');
  423. }
  424. /**
  425. * Returns the mailer component.
  426. * @return \yii\mail\MailerInterface the mailer interface
  427. */
  428. public function getMail()
  429. {
  430. return $this->getComponent('mail');
  431. }
  432. /**
  433. * Returns the auth manager for this application.
  434. * @return \yii\rbac\Manager the auth manager for this application.
  435. */
  436. public function getAuthManager()
  437. {
  438. return $this->getComponent('authManager');
  439. }
  440. /**
  441. * Registers the core application components.
  442. * @see setComponents
  443. */
  444. public function registerCoreComponents()
  445. {
  446. $this->setComponents([
  447. 'log' => ['class' => 'yii\log\Logger'],
  448. 'errorHandler' => ['class' => 'yii\base\ErrorHandler'],
  449. 'formatter' => ['class' => 'yii\base\Formatter'],
  450. 'i18n' => ['class' => 'yii\i18n\I18N'],
  451. 'mail' => ['class' => 'yii\swiftmailer\Mailer'],
  452. 'urlManager' => ['class' => 'yii\web\UrlManager'],
  453. 'view' => ['class' => 'yii\web\View'],
  454. ]);
  455. }
  456. /**
  457. * Handles uncaught PHP exceptions.
  458. *
  459. * This method is implemented as a PHP exception handler.
  460. *
  461. * @param \Exception $exception the exception that is not caught
  462. */
  463. public function handleException($exception)
  464. {
  465. $this->exception = $exception;
  466. // disable error capturing to avoid recursive errors while handling exceptions
  467. restore_error_handler();
  468. restore_exception_handler();
  469. try {
  470. $this->logException($exception);
  471. if (($handler = $this->getErrorHandler()) !== null) {
  472. $handler->handle($exception);
  473. } else {
  474. echo $this->renderException($exception);
  475. }
  476. } catch (\Exception $e) {
  477. // exception could be thrown in ErrorHandler::handle()
  478. $msg = (string)$e;
  479. $msg .= "\nPrevious exception:\n";
  480. $msg .= (string)$exception;
  481. if (YII_DEBUG) {
  482. if (PHP_SAPI === 'cli') {
  483. echo $msg . "\n";
  484. } else {
  485. echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, $this->charset) . '</pre>';
  486. }
  487. }
  488. $msg .= "\n\$_SERVER = " . var_export($_SERVER, true);
  489. error_log($msg);
  490. exit(1);
  491. }
  492. }
  493. /**
  494. * Handles PHP execution errors such as warnings, notices.
  495. *
  496. * This method is used as a PHP error handler. It will simply raise an `ErrorException`.
  497. *
  498. * @param integer $code the level of the error raised
  499. * @param string $message the error message
  500. * @param string $file the filename that the error was raised in
  501. * @param integer $line the line number the error was raised at
  502. *
  503. * @throws ErrorException
  504. */
  505. public function handleError($code, $message, $file, $line)
  506. {
  507. if (error_reporting() !== 0) {
  508. // load ErrorException manually here because autoloading them will not work
  509. // when error occurs while autoloading a class
  510. if (!class_exists('\\yii\\base\\Exception', false)) {
  511. require_once(__DIR__ . '/Exception.php');
  512. }
  513. if (!class_exists('\\yii\\base\\ErrorException', false)) {
  514. require_once(__DIR__ . '/ErrorException.php');
  515. }
  516. $exception = new ErrorException($message, $code, $code, $file, $line);
  517. // in case error appeared in __toString method we can't throw any exception
  518. $trace = debug_backtrace(false);
  519. array_shift($trace);
  520. foreach ($trace as $frame) {
  521. if ($frame['function'] == '__toString') {
  522. $this->handleException($exception);
  523. exit(1);
  524. }
  525. }
  526. throw $exception;
  527. }
  528. }
  529. /**
  530. * Handles fatal PHP errors
  531. */
  532. public function handleFatalError()
  533. {
  534. unset($this->_memoryReserve);
  535. // load ErrorException manually here because autoloading them will not work
  536. // when error occurs while autoloading a class
  537. if (!class_exists('\\yii\\base\\Exception', false)) {
  538. require_once(__DIR__ . '/Exception.php');
  539. }
  540. if (!class_exists('\\yii\\base\\ErrorException', false)) {
  541. require_once(__DIR__ . '/ErrorException.php');
  542. }
  543. $error = error_get_last();
  544. if (ErrorException::isFatalError($error)) {
  545. $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
  546. $this->exception = $exception;
  547. // use error_log because it's too late to use Yii log
  548. error_log($exception);
  549. if (($handler = $this->getErrorHandler()) !== null) {
  550. $handler->handle($exception);
  551. } else {
  552. echo $this->renderException($exception);
  553. }
  554. exit(1);
  555. }
  556. }
  557. /**
  558. * Renders an exception without using rich format.
  559. * @param \Exception $exception the exception to be rendered.
  560. * @return string the rendering result
  561. */
  562. public function renderException($exception)
  563. {
  564. if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
  565. $message = $exception->getName() . ': ' . $exception->getMessage();
  566. if (Yii::$app->controller instanceof \yii\console\Controller) {
  567. $message = Yii::$app->controller->ansiFormat($message, Console::FG_RED);
  568. }
  569. } else {
  570. $message = YII_DEBUG ? (string)$exception : 'Error: ' . $exception->getMessage();
  571. }
  572. if (PHP_SAPI === 'cli') {
  573. return $message . "\n";
  574. } else {
  575. return '<pre>' . htmlspecialchars($message, ENT_QUOTES, $this->charset) . '</pre>';
  576. }
  577. }
  578. /**
  579. * Logs the given exception
  580. * @param \Exception $exception the exception to be logged
  581. */
  582. protected function logException($exception)
  583. {
  584. $category = get_class($exception);
  585. if ($exception instanceof HttpException) {
  586. $category = 'yii\\web\\HttpException:' . $exception->statusCode;
  587. } elseif ($exception instanceof \ErrorException) {
  588. $category .= ':' . $exception->getSeverity();
  589. }
  590. Yii::error((string)$exception, $category);
  591. }
  592. }