ErrorHandler.php 7.94 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

/**
Qiang Xue committed
11
 * ErrorHandler handles uncaught PHP errors and exceptions.
Qiang Xue committed
12
 *
Qiang Xue committed
13 14 15
 * ErrorHandler displays these errors using appropriate views based on the
 * nature of the errors and the mode the application runs at.
 *
Qiang Xue committed
16
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
17
 * @since 2.0
Qiang Xue committed
18
 */
19
class ErrorHandler extends Component
Qiang Xue committed
20 21 22 23
{
	/**
	 * @var integer maximum number of source code lines to be displayed. Defaults to 25.
	 */
Qiang Xue committed
24
	public $maxSourceLines = 25;
Qiang Xue committed
25 26 27 28 29 30 31
	/**
	 * @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
32
	public $discardExistingOutput = true;
Qiang Xue committed
33 34
	/**
	 * @var string the route (eg 'site/error') to the controller action that will be used to display external errors.
Qiang Xue committed
35
	 * Inside the action, it can retrieve the error information by \Yii::$app->errorHandler->error.
Qiang Xue committed
36
	 * This property defaults to null, meaning ErrorHandler will handle the error display.
Qiang Xue committed
37 38
	 */
	public $errorAction;
Qiang Xue committed
39 40 41
	/**
	 * @var string the path of the view file for rendering exceptions
	 */
Qiang Xue committed
42
	public $exceptionView = '@yii/views/exception.php';
Qiang Xue committed
43 44 45
	/**
	 * @var string the path of the view file for rendering errors
	 */
Qiang Xue committed
46 47 48 49
	public $errorView = '@yii/views/error.php';
	/**
	 * @var \Exception the exception that is being handled currently
	 */
Qiang Xue committed
50
	public $exception;
Qiang Xue committed
51

Qiang Xue committed
52

Qiang Xue committed
53
	/**
Alexander Makarov committed
54
	 * Handles exception
Qiang Xue committed
55
	 * @param \Exception $exception
Qiang Xue committed
56
	 */
Qiang Xue committed
57
	public function handle($exception)
Qiang Xue committed
58
	{
Qiang Xue committed
59 60
		$this->exception = $exception;

Qiang Xue committed
61 62 63 64
		if ($this->discardExistingOutput) {
			$this->clearOutput();
		}

Qiang Xue committed
65
		$this->renderException($exception);
Qiang Xue committed
66 67
	}

Alexander Makarov committed
68 69 70 71
	/**
	 * Renders exception
	 * @param \Exception $exception
	 */
Qiang Xue committed
72
	protected function renderException($exception)
Qiang Xue committed
73
	{
Qiang Xue committed
74
		if ($this->errorAction !== null) {
Qiang Xue committed
75 76
			\Yii::$app->runAction($this->errorAction);
		} elseif (\Yii::$app instanceof \yii\web\Application) {
Qiang Xue committed
77
			if (!headers_sent()) {
78 79 80 81 82
				if ($exception instanceof HttpException) {
					header('HTTP/1.0 ' . $exception->statusCode . ' ' . $exception->getName());
				} else {
					header('HTTP/1.0 500 ' . get_class($exception));
				}
Qiang Xue committed
83 84
			}
			if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
Qiang Xue committed
85
				\Yii::$app->renderException($exception);
Qiang Xue committed
86
			} else {
87 88
				// 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
89
				if (YII_DEBUG) {
90
					ini_set('display_errors', 1);
91
				}
92 93 94 95 96 97 98 99 100 101

				$view = new View;
				if (!YII_DEBUG || $exception instanceof UserException) {
					$viewName = $this->errorView;
				} else {
					$viewName = $this->exceptionView;
				}
				echo $view->renderFile($viewName, array(
					'exception' => $exception,
				), $this);
Qiang Xue committed
102
			}
Qiang Xue committed
103
		} else {
Qiang Xue committed
104
			\Yii::$app->renderException($exception);
Qiang Xue committed
105 106 107 108
		}
	}

	/**
Qiang Xue committed
109 110
	 * Returns server and Yii version information.
	 * @return string server version information.
Qiang Xue committed
111
	 */
Qiang Xue committed
112
	public function getVersionInfo()
Qiang Xue committed
113
	{
Qiang Xue committed
114 115 116
		$version = '<a href="http://www.yiiframework.com/">Yii Framework</a>/' . \Yii::getVersion();
		if (isset($_SERVER['SERVER_SOFTWARE'])) {
			$version = $_SERVER['SERVER_SOFTWARE'] . ' ' . $version;
Qiang Xue committed
117 118 119 120 121 122 123 124 125 126
		}
		return $version;
	}

	/**
	 * Converts arguments array to its string representation
	 *
	 * @param array $args arguments array to be converted
	 * @return string string representation of the arguments array
	 */
Qiang Xue committed
127
	public function argumentsToString($args)
Qiang Xue committed
128
	{
Qiang Xue committed
129
		$isAssoc = $args !== array_values($args);
Qiang Xue committed
130 131
		$count = 0;
		foreach ($args as $key => $value) {
Qiang Xue committed
132
			$count++;
Qiang Xue committed
133
			if ($count >= 5) {
Qiang Xue committed
134
				if ($count > 5) {
Qiang Xue committed
135
					unset($args[$key]);
Qiang Xue committed
136
				} else {
Qiang Xue committed
137
					$args[$key] = '...';
Qiang Xue committed
138
				}
Qiang Xue committed
139 140 141
				continue;
			}

Qiang Xue committed
142
			if (is_object($value)) {
Qiang Xue committed
143
				$args[$key] = get_class($value);
Qiang Xue committed
144
			} elseif (is_bool($value)) {
Qiang Xue committed
145
				$args[$key] = $value ? 'true' : 'false';
Qiang Xue committed
146 147
			} elseif (is_string($value)) {
				if (strlen($value) > 64) {
Qiang Xue committed
148
					$args[$key] = '"' . substr($value, 0, 64) . '..."';
Qiang Xue committed
149
				} else {
Qiang Xue committed
150
					$args[$key] = '"' . $value . '"';
Qiang Xue committed
151 152
				}
			} elseif (is_array($value)) {
Qiang Xue committed
153
				$args[$key] = 'array(' . $this->argumentsToString($value) . ')';
Qiang Xue committed
154
			} elseif ($value === null) {
Qiang Xue committed
155
				$args[$key] = 'null';
Qiang Xue committed
156
			} elseif (is_resource($value)) {
Qiang Xue committed
157
				$args[$key] = 'resource';
Qiang Xue committed
158
			}
Qiang Xue committed
159

Qiang Xue committed
160 161
			if (is_string($key)) {
				$args[$key] = '"' . $key . '" => ' . $args[$key];
Qiang Xue committed
162
			} elseif ($isAssoc) {
Qiang Xue committed
163
				$args[$key] = $key . ' => ' . $args[$key];
Qiang Xue committed
164 165
			}
		}
Qiang Xue committed
166
		return implode(', ', $args);
Qiang Xue committed
167 168 169 170 171 172 173
	}

	/**
	 * Returns a value indicating whether the call stack is from application code.
	 * @param array $trace the trace data
	 * @return boolean whether the call stack is from application code.
	 */
Qiang Xue committed
174
	public function isCoreCode($trace)
Qiang Xue committed
175
	{
Qiang Xue committed
176
		if (isset($trace['file'])) {
Qiang Xue committed
177
			return $trace['file'] === 'unknown' || strpos(realpath($trace['file']), YII_PATH . DIRECTORY_SEPARATOR) === 0;
Qiang Xue committed
178 179 180 181 182 183 184 185 186 187
		}
		return false;
	}

	/**
	 * Renders the source code around the error line.
	 * @param string $file source file path
	 * @param integer $errorLine the error line number
	 * @param integer $maxLines maximum number of lines to display
	 */
Qiang Xue committed
188
	public function renderSourceCode($file, $errorLine, $maxLines)
Qiang Xue committed
189
	{
Qiang Xue committed
190
		$errorLine--; // adjust line number to 0-based from 1-based
Qiang Xue committed
191 192 193
		if ($errorLine < 0 || ($lines = @file($file)) === false || ($lineCount = count($lines)) <= $errorLine) {
			return;
		}
Qiang Xue committed
194

Qiang Xue committed
195 196 197 198
		$halfLines = (int)($maxLines / 2);
		$beginLine = $errorLine - $halfLines > 0 ? $errorLine - $halfLines : 0;
		$endLine = $errorLine + $halfLines < $lineCount ? $errorLine + $halfLines : $lineCount - 1;
		$lineNumberWidth = strlen($endLine + 1);
Qiang Xue committed
199

Qiang Xue committed
200
		$output = '';
Qiang Xue committed
201
		for ($i = $beginLine; $i <= $endLine; ++$i) {
Qiang Xue committed
202
			$isErrorLine = $i === $errorLine;
Qiang Xue committed
203 204
			$code = sprintf("<span class=\"ln" . ($isErrorLine ? ' error-ln' : '') . "\">%0{$lineNumberWidth}d</span> %s", $i + 1, $this->htmlEncode(str_replace("\t", '    ', $lines[$i])));
			if (!$isErrorLine) {
Qiang Xue committed
205
				$output .= $code;
Qiang Xue committed
206
			} else {
Qiang Xue committed
207
				$output .= '<span class="error">' . $code . '</span>';
Qiang Xue committed
208 209 210 211 212
			}
		}
		echo '<div class="code"><pre>' . $output . '</pre></div>';
	}

Alexander Makarov committed
213 214 215 216
	/**
	 * Renders calls stack trace
	 * @param array $trace
	 */
Qiang Xue committed
217 218 219 220 221 222 223 224 225 226 227 228
	public function renderTrace($trace)
	{
		$count = 0;
		echo "<table>\n";
		foreach ($trace as $n => $t) {
			if ($this->isCoreCode($t)) {
				$cssClass = 'core collapsed';
			} elseif (++$count > 3) {
				$cssClass = 'app collapsed';
			} else {
				$cssClass = 'app expanded';
			}
229 230

			$hasCode = isset($t['file']) && $t['file'] !== 'unknown' && is_file($t['file']);
Qiang Xue committed
231 232 233 234 235 236
			echo "<tr class=\"trace $cssClass\"><td class=\"number\">#$n</td><td class=\"content\">";
			echo '<div class="trace-file">';
			if ($hasCode) {
				echo '<div class="plus">+</div><div class="minus">-</div>';
			}
			echo '&nbsp;';
resurtm committed
237
			if (isset($t['file'])) {
238 239
				echo $this->htmlEncode($t['file']) . '(' . $t['line'] . '): ';
			}
Qiang Xue committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253
			if (!empty($t['class'])) {
				echo '<strong>' . $t['class'] . '</strong>' . $t['type'];
			}
			echo '<strong>' . $t['function'] . '</strong>';
			echo '(' . (empty($t['args']) ? '' : $this->htmlEncode($this->argumentsToString($t['args']))) . ')';
			echo '</div>';
			if ($hasCode) {
				$this->renderSourceCode($t['file'], $t['line'], $this->maxTraceSourceLines);
			}
			echo "</td></tr>\n";
		}
		echo '</table>';
	}

Alexander Makarov committed
254 255 256 257 258
	/**
	 * Converts special characters to HTML entities
	 * @param string $text text to encode
	 * @return string
	 */
Qiang Xue committed
259 260
	public function htmlEncode($text)
	{
Qiang Xue committed
261
		return htmlspecialchars($text, ENT_QUOTES, \Yii::$app->charset);
Qiang Xue committed
262 263 264 265 266 267 268
	}

	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) {
			@ob_end_clean();
Qiang Xue committed
269
		}
Qiang Xue committed
270 271
	}

Qiang Xue committed
272 273 274 275 276
	/**
	 * @param \Exception $exception
	 */
	public function renderAsHtml($exception)
	{
Qiang Xue committed
277
		$view = new View;
Qiang Xue committed
278
		$name = !YII_DEBUG || $exception instanceof HttpException ? $this->errorView : $this->exceptionView;
Qiang Xue committed
279
		echo $view->renderFile($name, array(
Qiang Xue committed
280
			'exception' => $exception,
Qiang Xue committed
281
		), $this);
Qiang Xue committed
282 283
	}
}