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

Qiang Xue committed
8
namespace yii\base;
Qiang Xue committed
9

10
use Yii;
Qiang Xue committed
11
use yii\web\HttpException;
12

Qiang Xue committed
13
/**
Qiang Xue committed
14
 * ErrorHandler handles uncaught PHP errors and exceptions.
Qiang Xue committed
15
 *
Qiang Xue committed
16 17 18
 * ErrorHandler displays these errors using appropriate views based on the
 * nature of the errors and the mode the application runs at.
 *
19
 * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
20 21
 * You can access that instance via `Yii::$app->errorHandler`.
 *
Qiang Xue committed
22
 * @author Qiang Xue <qiang.xue@gmail.com>
resurtm committed
23
 * @author Timur Ruziev <resurtm@gmail.com>
Qiang Xue committed
24
 * @since 2.0
Qiang Xue committed
25
 */
26
class ErrorHandler extends Component
Qiang Xue committed
27 28 29 30
{
	/**
	 * @var integer maximum number of source code lines to be displayed. Defaults to 25.
	 */
Qiang Xue committed
31
	public $maxSourceLines = 25;
Qiang Xue committed
32 33 34 35 36 37 38
	/**
	 * @var integer maximum number of trace source code lines to be displayed. Defaults to 10.
	 */
	public $maxTraceSourceLines = 10;
	/**
	 * @var boolean whether to discard any existing page output before error display. Defaults to true.
	 */
Qiang Xue committed
39
	public $discardExistingOutput = true;
Qiang Xue committed
40
	/**
41 42
	 * @var string the route (e.g. 'site/error') to the controller action that will be used
	 * to display external errors. Inside the action, it can retrieve the error information
43
	 * by Yii::$app->exception. This property defaults to null, meaning ErrorHandler
44
	 * will handle the error display.
Qiang Xue committed
45 46
	 */
	public $errorAction;
Qiang Xue committed
47
	/**
48
	 * @var string the path of the view file for rendering exceptions without call stack information.
Qiang Xue committed
49
	 */
50 51 52 53 54
	public $errorView = '@yii/views/errorHandler/error.php';
	/**
	 * @var string the path of the view file for rendering exceptions.
	 */
	public $exceptionView = '@yii/views/errorHandler/exception.php';
resurtm committed
55 56 57 58
	/**
	 * @var string the path of the view file for rendering exceptions and errors call stack element.
	 */
	public $callStackItemView = '@yii/views/errorHandler/callStackItem.php';
59 60 61 62
	/**
	 * @var string the path of the view file for rendering previous exceptions.
	 */
	public $previousExceptionView = '@yii/views/errorHandler/previousException.php';
Qiang Xue committed
63
	/**
64
	 * @var \Exception the exception that is being handled currently.
Qiang Xue committed
65
	 */
Qiang Xue committed
66
	public $exception;
Qiang Xue committed
67

Qiang Xue committed
68

Qiang Xue committed
69
	/**
70 71
	 * Handles exception.
	 * @param \Exception $exception to be handled.
Qiang Xue committed
72
	 */
Qiang Xue committed
73
	public function handle($exception)
Qiang Xue committed
74
	{
Qiang Xue committed
75
		$this->exception = $exception;
Qiang Xue committed
76 77 78
		if ($this->discardExistingOutput) {
			$this->clearOutput();
		}
Qiang Xue committed
79
		$this->renderException($exception);
Qiang Xue committed
80 81
	}

Alexander Makarov committed
82
	/**
83 84
	 * Renders the exception.
	 * @param \Exception $exception the exception to be handled.
Alexander Makarov committed
85
	 */
Qiang Xue committed
86
	protected function renderException($exception)
Qiang Xue committed
87
	{
88
		if (Yii::$app instanceof \yii\console\Application || YII_ENV_TEST) {
89
			echo Yii::$app->renderException($exception);
90 91 92 93
			if (!YII_ENV_TEST) {
				exit(1);
			}
			return;
94 95 96 97
		}

		$useErrorView = !YII_DEBUG || $exception instanceof UserException;

98 99
		$response = Yii::$app->getResponse();
		$response->getHeaders()->removeAll();
100

101 102 103 104 105
		if ($useErrorView && $this->errorAction !== null) {
			$result = Yii::$app->runAction($this->errorAction);
			if ($result instanceof Response) {
				$response = $result;
			} else {
106
				$response->data = $result;
Qiang Xue committed
107
			}
108
		} elseif ($response->format === \yii\web\Response::FORMAT_HTML) {
Qiang Xue committed
109
			if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
110
				// AJAX request
111
				$response->data = Yii::$app->renderException($exception);
Qiang Xue committed
112
			} else {
113 114
				// if there is an error during error rendering it's useful to
				// display PHP error in debug mode instead of a blank screen
resurtm committed
115
				if (YII_DEBUG) {
116
					ini_set('display_errors', 1);
117
				}
118
				$file = $useErrorView ? $this->errorView : $this->exceptionView;
Alexander Makarov committed
119
				$response->data = $this->renderFile($file, [
120
					'exception' => $exception,
Alexander Makarov committed
121
				]);
122
			}
Qiang Xue committed
123 124
		} elseif ($exception instanceof Arrayable) {
			$response->data = $exception;
125
		} else {
Alexander Makarov committed
126
			$response->data = [
Qiang Xue committed
127 128 129 130
				'type' => get_class($exception),
				'name' => 'Exception',
				'message' => $exception->getMessage(),
				'code' => $exception->getCode(),
Alexander Makarov committed
131
			];
Qiang Xue committed
132
		}
133 134 135 136 137 138 139 140

		if ($exception instanceof HttpException) {
			$response->setStatusCode($exception->statusCode);
		} else {
			$response->setStatusCode(500);
		}

		$response->send();
Qiang Xue committed
141 142 143
	}

	/**
144 145
	 * Converts special characters to HTML entities.
	 * @param string $text to encode.
resurtm committed
146
	 * @return string encoded original text.
Qiang Xue committed
147
	 */
148
	public function htmlEncode($text)
Qiang Xue committed
149
	{
150
		return htmlspecialchars($text, ENT_QUOTES, Yii::$app->charset);
Qiang Xue committed
151 152
	}

Alexander Makarov committed
153
	/**
154
	 * Removes all output echoed before calling this method.
Alexander Makarov committed
155
	 */
Qiang Xue committed
156 157 158 159
	public function clearOutput()
	{
		// the following manual level counting is to deal with zlib.output_compression set to On
		for ($level = ob_get_level(); $level > 0; --$level) {
160 161 162
			if (!@ob_end_clean()) {
				ob_clean();
			}
Qiang Xue committed
163
		}
Qiang Xue committed
164
	}
resurtm committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

	/**
	 * Adds informational links to the given PHP type/class.
	 * @param string $code type/class name to be linkified.
	 * @return string linkified with HTML type/class name.
	 */
	public function addTypeLinks($code)
	{
		$html = '';
		if (strpos($code, '\\') !== false) {
			// namespaced class
			foreach (explode('\\', $code) as $part) {
				$html .= '<a href="http://yiiframework.com/doc/api/2.0/' . $this->htmlEncode($part) . '" target="_blank">' . $this->htmlEncode($part) . '</a>\\';
			}
			$html = rtrim($html, '\\');
180 181
		} elseif (strpos($code, '()') !== false) {
			// method/function call
182
			$html = preg_replace_callback('/^(.*)\(\)$/', function ($matches) {
183 184
				return '<a href="http://yiiframework.com/doc/api/2.0/' . $this->htmlEncode($matches[1]) . '" target="_blank">' .
					$this->htmlEncode($matches[1]) . '</a>()';
185
			}, $code);
resurtm committed
186 187 188 189 190
		}
		return $html;
	}

	/**
191 192 193 194
	 * Renders a view file as a PHP script.
	 * @param string $_file_ the view file.
	 * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
	 * @return string the rendering result
resurtm committed
195
	 */
196
	public function renderFile($_file_, $_params_)
resurtm committed
197
	{
198 199 200 201 202 203 204 205 206 207
		$_params_['handler'] = $this;
		if ($this->exception instanceof ErrorException) {
			ob_start();
			ob_implicit_flush(false);
			extract($_params_, EXTR_OVERWRITE);
			require(Yii::getAlias($_file_));
			return ob_get_clean();
		} else {
			return Yii::$app->getView()->renderFile($_file_, $_params_, $this);
		}
resurtm committed
208 209
	}

210 211 212 213 214 215 216 217
	/**
	 * Renders the previous exception stack for a given Exception.
	 * @param \Exception $exception the exception whose precursors should be rendered.
	 * @return string HTML content of the rendered previous exceptions.
	 * Empty string if there are none.
	 */
	public function renderPreviousExceptions($exception)
	{
218
		if (($previous = $exception->getPrevious()) !== null) {
Alexander Makarov committed
219
			return $this->renderFile($this->previousExceptionView, ['exception' => $previous]);
220
		} else {
221 222 223 224
			return '';
		}
	}

resurtm committed
225 226
	/**
	 * Renders a single call stack element.
227 228 229 230
	 * @param string|null $file name where call has happened.
	 * @param integer|null $line number on which call has happened.
	 * @param string|null $class called class name.
	 * @param string|null $method called function/method name.
resurtm committed
231 232 233
	 * @param integer $index number of the call stack element.
	 * @return string HTML content of the rendered call stack element.
	 */
234
	public function renderCallStackItem($file, $line, $class, $method, $index)
resurtm committed
235
	{
Alexander Makarov committed
236
		$lines = [];
237 238 239 240 241 242 243
		$begin = $end = 0;
		if ($file !== null && $line !== null) {
			$line--; // adjust line number from one-based to zero-based
			$lines = @file($file);
			if ($line < 0 || $lines === false || ($lineCount = count($lines)) < $line + 1) {
				return '';
			}
resurtm committed
244

245 246 247 248
			$half = (int)(($index == 0 ? $this->maxSourceLines : $this->maxTraceSourceLines) / 2);
			$begin = $line - $half > 0 ? $line - $half : 0;
			$end = $line + $half < $lineCount ? $line + $half : $lineCount - 1;
		}
resurtm committed
249

Alexander Makarov committed
250
		return $this->renderFile($this->callStackItemView, [
resurtm committed
251 252
			'file' => $file,
			'line' => $line,
253 254
			'class' => $class,
			'method' => $method,
resurtm committed
255 256 257 258
			'index' => $index,
			'lines' => $lines,
			'begin' => $begin,
			'end' => $end,
Alexander Makarov committed
259
		]);
resurtm committed
260 261
	}

262 263 264 265 266 267 268
	/**
	 * Renders the request information.
	 * @return string the rendering result
	 */
	public function renderRequest()
	{
		$request = '';
Alexander Makarov committed
269
		foreach (['_GET', '_POST', '_SERVER', '_FILES', '_COOKIE', '_SESSION', '_ENV'] as $name) {
270 271 272 273 274 275 276
			if (!empty($GLOBALS[$name])) {
				$request .= '$' . $name . ' = ' . var_export($GLOBALS[$name], true) . ";\n\n";
			}
		}
		return '<pre>' . rtrim($request, "\n") . '</pre>';
	}

resurtm committed
277 278 279 280 281 282 283
	/**
	 * Determines whether given name of the file belongs to the framework.
	 * @param string $file name to be checked.
	 * @return boolean whether given name of the file belongs to the framework.
	 */
	public function isCoreFile($file)
	{
284
		return $file === null || strpos(realpath($file), YII_PATH . DIRECTORY_SEPARATOR) === 0;
resurtm committed
285 286
	}

287 288 289 290 291 292 293 294
	/**
	 * Creates HTML containing link to the page with the information on given HTTP status code.
	 * @param integer $statusCode to be used to generate information link.
	 * @param string $statusDescription Description to display after the the status code.
	 * @return string generated HTML with HTTP status code information.
	 */
	public function createHttpStatusLink($statusCode, $statusDescription)
	{
Luciano Baraglia committed
295
		return '<a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#' . (int)$statusCode . '" target="_blank">HTTP ' . (int)$statusCode . ' &ndash; ' . $statusDescription . '</a>';
296 297
	}

resurtm committed
298 299 300 301 302 303 304
	/**
	 * Creates string containing HTML link which refers to the home page of determined web-server software
	 * and its full name.
	 * @return string server software information hyperlink.
	 */
	public function createServerInformationLink()
	{
Alexander Makarov committed
305 306 307 308 309 310 311 312
		static $serverUrls = [
			'http://httpd.apache.org/' => ['apache'],
			'http://nginx.org/' => ['nginx'],
			'http://lighttpd.net/' => ['lighttpd'],
			'http://gwan.com/' => ['g-wan', 'gwan'],
			'http://iis.net/' => ['iis', 'services'],
			'http://php.net/manual/en/features.commandline.webserver.php' => ['development'],
		];
resurtm committed
313 314 315
		if (isset($_SERVER['SERVER_SOFTWARE'])) {
			foreach ($serverUrls as $url => $keywords) {
				foreach ($keywords as $keyword) {
resurtm committed
316
					if (stripos($_SERVER['SERVER_SOFTWARE'], $keyword) !== false) {
resurtm committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
						return '<a href="' . $url . '" target="_blank">' . $this->htmlEncode($_SERVER['SERVER_SOFTWARE']) . '</a>';
					}
				}
			}
		}
		return '';
	}

	/**
	 * Creates string containing HTML link which refers to the page with the current version
	 * of the framework and version number text.
	 * @return string framework version information hyperlink.
	 */
	public function createFrameworkVersionLink()
	{
		return '<a href="http://github.com/yiisoft/yii2/" target="_blank">' . $this->htmlEncode(Yii::getVersion()) . '</a>';
	}
Qiang Xue committed
334
}