ErrorHandler.php 7.88 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 78 79 80 81
			if (!headers_sent()) {
				$errorCode = $exception instanceof HttpException ? $exception->statusCode : 500;
				header("HTTP/1.0 $errorCode " . get_class($exception));
			}
			if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
Qiang Xue committed
82
				\Yii::$app->renderException($exception);
Qiang Xue committed
83
			} else {
84 85
				// if there is an error during error rendering it's useful to
				// display PHP error in debug mode instead of a blank screen
86 87
				if(YII_DEBUG) {
					ini_set('display_errors', 1);
88
				}
89 90 91 92 93 94 95 96 97 98

				$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
99
			}
Qiang Xue committed
100
		} else {
Qiang Xue committed
101
			\Yii::$app->renderException($exception);
Qiang Xue committed
102 103 104 105
		}
	}

	/**
Qiang Xue committed
106 107
	 * Returns server and Yii version information.
	 * @return string server version information.
Qiang Xue committed
108
	 */
Qiang Xue committed
109
	public function getVersionInfo()
Qiang Xue committed
110
	{
Qiang Xue committed
111 112 113
		$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
114 115 116 117 118 119 120 121 122 123
		}
		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
124
	public function argumentsToString($args)
Qiang Xue committed
125
	{
Qiang Xue committed
126
		$isAssoc = $args !== array_values($args);
Qiang Xue committed
127 128
		$count = 0;
		foreach ($args as $key => $value) {
Qiang Xue committed
129
			$count++;
Qiang Xue committed
130
			if ($count >= 5) {
Qiang Xue committed
131
				if ($count > 5) {
Qiang Xue committed
132
					unset($args[$key]);
Qiang Xue committed
133
				} else {
Qiang Xue committed
134
					$args[$key] = '...';
Qiang Xue committed
135
				}
Qiang Xue committed
136 137 138
				continue;
			}

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

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

	/**
	 * 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
171
	public function isCoreCode($trace)
Qiang Xue committed
172
	{
Qiang Xue committed
173
		if (isset($trace['file'])) {
Qiang Xue committed
174
			return $trace['file'] === 'unknown' || strpos(realpath($trace['file']), YII_PATH . DIRECTORY_SEPARATOR) === 0;
Qiang Xue committed
175 176 177 178 179 180 181 182 183 184
		}
		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
185
	public function renderSourceCode($file, $errorLine, $maxLines)
Qiang Xue committed
186
	{
Qiang Xue committed
187
		$errorLine--; // adjust line number to 0-based from 1-based
Qiang Xue committed
188 189 190
		if ($errorLine < 0 || ($lines = @file($file)) === false || ($lineCount = count($lines)) <= $errorLine) {
			return;
		}
Qiang Xue committed
191

Qiang Xue committed
192 193 194 195
		$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
196

Qiang Xue committed
197
		$output = '';
Qiang Xue committed
198
		for ($i = $beginLine; $i <= $endLine; ++$i) {
Qiang Xue committed
199
			$isErrorLine = $i === $errorLine;
Qiang Xue committed
200 201
			$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
202
				$output .= $code;
Qiang Xue committed
203
			} else {
Qiang Xue committed
204
				$output .= '<span class="error">' . $code . '</span>';
Qiang Xue committed
205 206 207 208 209
			}
		}
		echo '<div class="code"><pre>' . $output . '</pre></div>';
	}

Alexander Makarov committed
210 211 212 213
	/**
	 * Renders calls stack trace
	 * @param array $trace
	 */
Qiang Xue committed
214 215 216 217 218 219 220 221 222 223 224 225
	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';
			}
226 227

			$hasCode = isset($t['file']) && $t['file'] !== 'unknown' && is_file($t['file']);
Qiang Xue committed
228 229 230 231 232 233
			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;';
234 235 236
			if(isset($t['file'])) {
				echo $this->htmlEncode($t['file']) . '(' . $t['line'] . '): ';
			}
Qiang Xue committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250
			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
251 252 253 254 255
	/**
	 * Converts special characters to HTML entities
	 * @param string $text text to encode
	 * @return string
	 */
Qiang Xue committed
256 257
	public function htmlEncode($text)
	{
Qiang Xue committed
258
		return htmlspecialchars($text, ENT_QUOTES, \Yii::$app->charset);
Qiang Xue committed
259 260 261 262 263 264 265
	}

	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
266
		}
Qiang Xue committed
267 268
	}

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