Application.php 14.6 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

8 9
namespace yii\base;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\helpers\FileHelper;
.  
Qiang Xue committed
12

w  
Qiang Xue committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/**
 * Application is the base class for all application classes.
 *
 * An application serves as the global context that the user request
 * is being processed. It manages a set of application components that
 * provide specific functionalities to the whole application.
 *
 * The core application components provided by Application are the following:
 * <ul>
 * <li>{@link getErrorHandler errorHandler}: handles PHP errors and
 *   uncaught exceptions. This application component is dynamically loaded when needed.</li>
 * <li>{@link getSecurityManager securityManager}: provides security-related
 *   services, such as hashing, encryption. This application component is dynamically
 *   loaded when needed.</li>
 * <li>{@link getStatePersister statePersister}: provides global state
 *   persistence method. This application component is dynamically loaded when needed.</li>
 * <li>{@link getCache cache}: provides caching feature. This application component is
 *   disabled by default.</li>
 * </ul>
 *
Qiang Xue committed
33
 * Application will undergo the following life cycles when processing a user request:
w  
Qiang Xue committed
34 35 36 37
 * <ol>
 * <li>load application configuration;</li>
 * <li>set up class autoloader and error handling;</li>
 * <li>load static application components;</li>
38
 * <li>{@link beforeRequest}: preprocess the user request; `beforeRequest` event raised.</li>
w  
Qiang Xue committed
39
 * <li>{@link processRequest}: process the user request;</li>
40
 * <li>{@link afterRequest}: postprocess the user request; `afterRequest` event raised.</li>
w  
Qiang Xue committed
41 42 43 44 45
 * </ol>
 *
 * Starting from lifecycle 3, if a PHP error or an uncaught exception occurs,
 * the application will switch to its error handling logic and jump to step 6 afterwards.
 *
w  
Qiang Xue committed
46 47
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
w  
Qiang Xue committed
48
 */
Qiang Xue committed
49
class Application extends Module
w  
Qiang Xue committed
50
{
Qiang Xue committed
51 52
	const EVENT_BEFORE_REQUEST = 'beforeRequest';
	const EVENT_AFTER_REQUEST = 'afterRequest';
w  
Qiang Xue committed
53
	/**
Qiang Xue committed
54
	 * @var string the application name.
w  
Qiang Xue committed
55 56
	 */
	public $name = 'My Application';
Qiang Xue committed
57
	/**
Qiang Xue committed
58
	 * @var string the version of this application.
Qiang Xue committed
59 60
	 */
	public $version = '1.0';
w  
Qiang Xue committed
61
	/**
Qiang Xue committed
62
	 * @var string the charset currently used for the application.
w  
Qiang Xue committed
63 64
	 */
	public $charset = 'UTF-8';
Qiang Xue committed
65 66 67 68 69
	/**
	 * @var string the language that is meant to be used for end users.
	 * @see sourceLanguage
	 */
	public $language = 'en_US';
w  
Qiang Xue committed
70 71
	/**
	 * @var string the language that the application is written in. This mainly refers to
Qiang Xue committed
72
	 * the language that the messages and view files are written in.
.  
Qiang Xue committed
73
	 * @see language
w  
Qiang Xue committed
74
	 */
Qiang Xue committed
75
	public $sourceLanguage = 'en_US';
Qiang Xue committed
76
	/**
Qiang Xue committed
77
	 * @var array IDs of the components that need to be loaded when the application starts.
Qiang Xue committed
78
	 */
Qiang Xue committed
79
	public $preload = array();
Qiang Xue committed
80
	/**
81
	 * @var \yii\web\Controller|\yii\console\Controller the currently active controller instance
Qiang Xue committed
82 83
	 */
	public $controller;
Qiang Xue committed
84 85 86 87 88
	/**
	 * @var mixed the layout that should be applied for views in this application. Defaults to 'main'.
	 * If this is false, layout will be disabled.
	 */
	public $layout = 'main';
w  
Qiang Xue committed
89

Qiang Xue committed
90
	// todo
Qiang Xue committed
91 92
	public $localeDataPath = '@yii/i18n/data';

w  
Qiang Xue committed
93 94 95
	private $_runtimePath;
	private $_ended = false;

96 97 98 99 100 101
	/**
	 * @var string Used to reserve memory for fatal error handler. This memory
	 * reserve can be removed if it's OK to write to PHP log only in this particular case.
	 */
	private $_memoryReserve;

w  
Qiang Xue committed
102 103
	/**
	 * Constructor.
Qiang Xue committed
104
	 * @param string $id the ID of this application. The ID should uniquely identify the application from others.
Qiang Xue committed
105 106
	 * @param string $basePath the base path of this application. This should point to
	 * the directory containing all application logic, template and data.
Qiang Xue committed
107
	 * @param array $config name-value pairs that will be used to initialize the object properties
w  
Qiang Xue committed
108
	 */
Qiang Xue committed
109
	public function __construct($id, $basePath, $config = array())
w  
Qiang Xue committed
110
	{
Qiang Xue committed
111
		Yii::$app = $this;
Qiang Xue committed
112
		$this->id = $id;
.  
Qiang Xue committed
113
		$this->setBasePath($basePath);
Qiang Xue committed
114 115

		if (YII_ENABLE_ERROR_HANDLER) {
116
			ini_set('display_errors', 0);
Qiang Xue committed
117 118 119 120
			set_exception_handler(array($this, 'handleException'));
			set_error_handler(array($this, 'handleError'), error_reporting());
		}

Qiang Xue committed
121
		$this->registerDefaultAliases();
w  
Qiang Xue committed
122
		$this->registerCoreComponents();
Qiang Xue committed
123

Qiang Xue committed
124
		Component::__construct($config);
.  
Qiang Xue committed
125
	}
w  
Qiang Xue committed
126

.  
Qiang Xue committed
127
	/**
Qiang Xue committed
128 129
	 * Initializes the application by loading components declared in [[preload]].
	 * If you override this method, make sure the parent implementation is invoked.
.  
Qiang Xue committed
130 131 132
	 */
	public function init()
	{
w  
Qiang Xue committed
133 134 135 136 137
		$this->preloadComponents();
	}

	/**
	 * Terminates the application.
.  
Qiang Xue committed
138
	 * This method replaces PHP's exit() function by calling [[afterRequest()]] before exiting.
w  
Qiang Xue committed
139
	 * @param integer $status exit status (value 0 means normal exit while other values mean abnormal exit).
.  
Qiang Xue committed
140
	 * @param boolean $exit whether to exit the current request.
w  
Qiang Xue committed
141 142 143 144
	 * It defaults to true, meaning the PHP's exit() function will be called at the end of this method.
	 */
	public function end($status = 0, $exit = true)
	{
.  
Qiang Xue committed
145 146 147
		if (!$this->_ended) {
			$this->_ended = true;
			$this->afterRequest();
Qiang Xue committed
148
		}
149

150 151 152 153 154 155 156 157 158 159 160 161
		$this->handleFatalError();

		if ($exit) {
			exit($status);
		}
	}

	/**
	 * Handles fatal PHP errors
	 */
	public function handleFatalError()
	{
Qiang Xue committed
162
		if (YII_ENABLE_ERROR_HANDLER) {
163 164
			$error = error_get_last();

Qiang Xue committed
165
			if (ErrorException::isFatalErorr($error)) {
166 167 168
				unset($this->_memoryReserve);
				$exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);

Qiang Xue committed
169
				if (function_exists('xdebug_get_function_stack')) {
170
					$trace = array_slice(array_reverse(xdebug_get_function_stack()), 4, -1);
Qiang Xue committed
171 172
					foreach ($trace as &$frame) {
						if (!isset($frame['function'])) {
173 174 175 176
							$frame['function'] = 'unknown';
						}

						// XDebug < 2.1.1: http://bugs.xdebug.org/view.php?id=695
Qiang Xue committed
177
						if (!isset($frame['type'])) {
178 179 180 181 182
							$frame['type'] = '::';
						}

						// XDebug has a different key name
						$frame['args'] = array();
Qiang Xue committed
183
						if (isset($frame['params']) && !isset($frame['args'])) {
184 185 186 187 188 189 190 191 192 193 194 195
							$frame['args'] = $frame['params'];
						}
					}

					$ref = new \ReflectionProperty('Exception', 'trace');
					$ref->setAccessible(true);
					$ref->setValue($exception, $trace);
				}

				$this->logException($exception);

				if (($handler = $this->getErrorHandler()) !== null) {
196
					@$handler->handle($exception);
197 198 199 200
				} else {
					$this->renderException($exception);
				}

201
				exit(1);
202 203
			}
		}
w  
Qiang Xue committed
204 205
	}

Qiang Xue committed
206 207 208 209 210 211 212 213
	/**
	 * Runs the application.
	 * This is the main entrance of an application.
	 * @return integer the exit status (0 means normal, non-zero values mean abnormal)
	 */
	public function run()
	{
		$this->beforeRequest();
214 215
		// Allocating twice more than required to display memory exhausted error
		// in case of trying to allocate last 1 byte while all memory is taken.
Qiang Xue committed
216 217
		$this->_memoryReserve = str_repeat('x', 1024 * 256);
		register_shutdown_function(array($this, 'end'), 0, false);
Qiang Xue committed
218 219 220 221 222
		$status = $this->processRequest();
		$this->afterRequest();
		return $status;
	}

w  
Qiang Xue committed
223
	/**
Qiang Xue committed
224
	 * Raises the [[EVENT_BEFORE_REQUEST]] event right BEFORE the application processes the request.
w  
Qiang Xue committed
225
	 */
.  
Qiang Xue committed
226
	public function beforeRequest()
w  
Qiang Xue committed
227
	{
Qiang Xue committed
228
		$this->trigger(self::EVENT_BEFORE_REQUEST);
w  
Qiang Xue committed
229 230
	}

Qiang Xue committed
231
	/**
Qiang Xue committed
232
	 * Raises the [[EVENT_AFTER_REQUEST]] event right AFTER the application processes the request.
Qiang Xue committed
233
	 */
Qiang Xue committed
234
	public function afterRequest()
Qiang Xue committed
235
	{
Qiang Xue committed
236
		$this->trigger(self::EVENT_AFTER_REQUEST);
Qiang Xue committed
237 238
	}

w  
Qiang Xue committed
239
	/**
Qiang Xue committed
240
	 * Processes the request.
Qiang Xue committed
241
	 * Child classes should override this method with actual request processing logic.
Qiang Xue committed
242
	 * @return integer the exit status of the controller action (0 means normal, non-zero values mean abnormal)
Qiang Xue committed
243 244 245 246 247 248
	 */
	public function processRequest()
	{
		return 0;
	}

w  
Qiang Xue committed
249 250 251 252 253 254
	/**
	 * Returns the directory that stores runtime files.
	 * @return string the directory that stores runtime files. Defaults to 'protected/runtime'.
	 */
	public function getRuntimePath()
	{
Qiang Xue committed
255
		if ($this->_runtimePath !== null) {
w  
Qiang Xue committed
256 257
			$this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
		}
Qiang Xue committed
258
		return $this->_runtimePath;
w  
Qiang Xue committed
259 260 261 262 263
	}

	/**
	 * Sets the directory that stores runtime files.
	 * @param string $path the directory that stores runtime files.
Qiang Xue committed
264
	 * @throws InvalidConfigException if the directory does not exist or is not writable
w  
Qiang Xue committed
265 266 267
	 */
	public function setRuntimePath($path)
	{
Qiang Xue committed
268 269
		$p = FileHelper::ensureDirectory($path);
		if (is_writable($p)) {
Qiang Xue committed
270
			$this->_runtimePath = $p;
Qiang Xue committed
271 272
		} else {
			throw new InvalidConfigException("Runtime path must be writable by the Web server process: $path");
Qiang Xue committed
273
		}
w  
Qiang Xue committed
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
	}

	/**
	 * Returns the time zone used by this application.
	 * This is a simple wrapper of PHP function date_default_timezone_get().
	 * @return string the time zone used by this application.
	 * @see http://php.net/manual/en/function.date-default-timezone-get.php
	 */
	public function getTimeZone()
	{
		return date_default_timezone_get();
	}

	/**
	 * Sets the time zone used by this application.
	 * This is a simple wrapper of PHP function date_default_timezone_set().
	 * @param string $value the time zone used by this application.
	 * @see http://php.net/manual/en/function.date-default-timezone-set.php
	 */
	public function setTimeZone($value)
	{
		date_default_timezone_set($value);
	}

Qiang Xue committed
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
	//
	//	/**
	//	 * Returns the locale instance.
	//	 * @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used.
	//	 * @return CLocale the locale instance
	//	 */
	//	public function getLocale($localeID = null)
	//	{
	//		return CLocale::getInstance($localeID === null ? $this->getLanguage() : $localeID);
	//	}
	//
	//	/**
	//	 * @return CNumberFormatter the locale-dependent number formatter.
	//	 * The current {@link getLocale application locale} will be used.
	//	 */
	//	public function getNumberFormatter()
	//	{
	//		return $this->getLocale()->getNumberFormatter();
	//	}
	//
	//	/**
	//	 * Returns the locale-dependent date formatter.
	//	 * @return CDateFormatter the locale-dependent date formatter.
	//	 * The current {@link getLocale application locale} will be used.
	//	 */
	//	public function getDateFormatter()
	//	{
	//		return $this->getLocale()->getDateFormatter();
	//	}
	//
w  
Qiang Xue committed
328 329 330

	/**
	 * Returns the database connection component.
Qiang Xue committed
331
	 * @return \yii\db\Connection the database connection
w  
Qiang Xue committed
332 333 334 335 336 337 338 339
	 */
	public function getDb()
	{
		return $this->getComponent('db');
	}

	/**
	 * Returns the error handler component.
.  
Qiang Xue committed
340
	 * @return ErrorHandler the error handler application component.
w  
Qiang Xue committed
341 342 343 344 345 346 347 348
	 */
	public function getErrorHandler()
	{
		return $this->getComponent('errorHandler');
	}

	/**
	 * Returns the cache component.
.  
Qiang Xue committed
349
	 * @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
w  
Qiang Xue committed
350 351 352 353 354 355 356 357
	 */
	public function getCache()
	{
		return $this->getComponent('cache');
	}

	/**
	 * Returns the request component.
358
	 * @return \yii\web\Request|\yii\console\Request the request component
w  
Qiang Xue committed
359 360 361 362 363 364
	 */
	public function getRequest()
	{
		return $this->getComponent('request');
	}

Qiang Xue committed
365
	/**
Qiang Xue committed
366 367
	 * Returns the view object.
	 * @return View the view object that is used to render various view files.
Qiang Xue committed
368
	 */
Qiang Xue committed
369
	public function getView()
Qiang Xue committed
370
	{
Qiang Xue committed
371
		return $this->getComponent('view');
Qiang Xue committed
372 373
	}

Qiang Xue committed
374 375 376 377 378 379 380 381 382
	/**
	 * Returns the URL manager for this application.
	 * @return \yii\web\UrlManager the URL manager for this application.
	 */
	public function getUrlManager()
	{
		return $this->getComponent('urlManager');
	}

Qiang Xue committed
383 384 385 386 387 388 389 390 391
	/**
	 * Returns the internationalization (i18n) component
	 * @return \yii\i18n\I18N the internationalization component
	 */
	public function getI18N()
	{
		return $this->getComponent('i18n');
	}

Qiang Xue committed
392 393 394 395 396
	/**
	 * Sets default path aliases.
	 */
	public function registerDefaultAliases()
	{
Qiang Xue committed
397
		Yii::$aliases['@app'] = $this->getBasePath();
Qiang Xue committed
398 399
	}

w  
Qiang Xue committed
400 401 402 403
	/**
	 * Registers the core application components.
	 * @see setComponents
	 */
.  
Qiang Xue committed
404
	public function registerCoreComponents()
w  
Qiang Xue committed
405
	{
.  
Qiang Xue committed
406 407 408 409
		$this->setComponents(array(
			'errorHandler' => array(
				'class' => 'yii\base\ErrorHandler',
			),
Qiang Xue committed
410 411
			'i18n' => array(
				'class' => 'yii\i18n\I18N',
w  
Qiang Xue committed
412
			),
Qiang Xue committed
413 414
			'urlManager' => array(
				'class' => 'yii\web\UrlManager',
w  
Qiang Xue committed
415
			),
Qiang Xue committed
416 417 418
			'view' => array(
				'class' => 'yii\base\View',
			),
.  
Qiang Xue committed
419
		));
w  
Qiang Xue committed
420
	}
Qiang Xue committed
421 422 423 424 425 426 427 428 429 430

	/**
	 * Handles PHP execution errors such as warnings, notices.
	 *
	 * This method is used as a PHP error handler. It will simply raise an `ErrorException`.
	 *
	 * @param integer $code the level of the error raised
	 * @param string $message the error message
	 * @param string $file the filename that the error was raised in
	 * @param integer $line the line number the error was raised at
431 432
	 *
	 * @throws ErrorException
Qiang Xue committed
433 434 435 436
	 */
	public function handleError($code, $message, $file, $line)
	{
		if (error_reporting() !== 0) {
437 438 439 440 441
			$exception = new ErrorException($message, $code, $code, $file, $line);

			// in case error appeared in __toString method we can't throw any exception
			$trace = debug_backtrace(false);
			array_shift($trace);
Qiang Xue committed
442 443
			foreach ($trace as $frame) {
				if ($frame['function'] == '__toString') {
444 445 446 447 448
					$this->handleException($exception);
				}
			}

			throw $exception;
Qiang Xue committed
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
		}
	}

	/**
	 * Handles uncaught PHP exceptions.
	 *
	 * This method is implemented as a PHP exception handler. It requires
	 * that constant YII_ENABLE_ERROR_HANDLER be defined true.
	 *
	 * @param \Exception $exception exception that is not caught
	 */
	public function handleException($exception)
	{
		// disable error capturing to avoid recursive errors while handling exceptions
		restore_error_handler();
		restore_exception_handler();

		try {
			$this->logException($exception);

			if (($handler = $this->getErrorHandler()) !== null) {
				$handler->handle($exception);
			} else {
Qiang Xue committed
472
				$this->renderException($exception);
Qiang Xue committed
473 474 475 476
			}

			$this->end(1);

Qiang Xue committed
477
		} catch (\Exception $e) {
Qiang Xue committed
478 479 480 481
			// exception could be thrown in end() or ErrorHandler::handle()
			$msg = (string)$e;
			$msg .= "\nPrevious exception:\n";
			$msg .= (string)$exception;
Qiang Xue committed
482 483 484
			if (YII_DEBUG) {
				echo $msg;
			}
Qiang Xue committed
485 486 487 488 489 490
			$msg .= "\n\$_SERVER = " . var_export($_SERVER, true);
			error_log($msg);
			exit(1);
		}
	}

Qiang Xue committed
491 492 493 494 495 496
	/**
	 * Renders an exception without using rich format.
	 * @param \Exception $exception the exception to be rendered.
	 */
	public function renderException($exception)
	{
Qiang Xue committed
497
		if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
Qiang Xue committed
498 499 500 501 502 503 504 505 506 507 508
			$message = $exception->getName() . ': ' . $exception->getMessage();
		} else {
			$message = YII_DEBUG ? (string)$exception : 'Error: ' . $exception->getMessage();
		}
		if (PHP_SAPI) {
			echo $message . "\n";
		} else {
			echo '<pre>' . htmlspecialchars($message, ENT_QUOTES, $this->charset) . '</pre>';
		}
	}

Qiang Xue committed
509 510 511 512 513 514 515 516 517 518 519 520 521
	// todo: to be polished
	protected function logException($exception)
	{
		$category = get_class($exception);
		if ($exception instanceof HttpException) {
			/** @var $exception HttpException */
			$category .= '\\' . $exception->statusCode;
		} elseif ($exception instanceof \ErrorException) {
			/** @var $exception \ErrorException */
			$category .= '\\' . $exception->getSeverity();
		}
		Yii::error((string)$exception, $category);
	}
w  
Qiang Xue committed
522
}