ErrorHandler.php 7.43 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 20
use yii\util\VarDumper;

21
class ErrorHandler extends Component
Qiang Xue committed
22 23 24 25
{
	/**
	 * @var integer maximum number of source code lines to be displayed. Defaults to 25.
	 */
Qiang Xue committed
26
	public $maxSourceLines = 25;
Qiang Xue committed
27 28 29 30 31 32 33
	/**
	 * @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
34
	public $discardExistingOutput = true;
Qiang Xue committed
35 36
	/**
	 * @var string the route (eg 'site/error') to the controller action that will be used to display external errors.
Qiang Xue committed
37
	 * Inside the action, it can retrieve the error information by \Yii::$app->errorHandler->error.
Qiang Xue committed
38
	 * This property defaults to null, meaning ErrorHandler will handle the error display.
Qiang Xue committed
39 40
	 */
	public $errorAction;
Qiang Xue committed
41 42 43
	/**
	 * @var string the path of the view file for rendering exceptions
	 */
Qiang Xue committed
44
	public $exceptionView = '@yii/views/exception.php';
Qiang Xue committed
45 46 47
	/**
	 * @var string the path of the view file for rendering errors
	 */
Qiang Xue committed
48 49 50 51
	public $errorView = '@yii/views/error.php';
	/**
	 * @var \Exception the exception that is being handled currently
	 */
Qiang Xue committed
52
	public $exception;
Qiang Xue committed
53

Qiang Xue committed
54

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

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

Qiang Xue committed
66
		$this->render($exception);
Qiang Xue committed
67 68
	}

Qiang Xue committed
69
	protected function render($exception)
Qiang Xue committed
70
	{
Qiang Xue committed
71
		if ($this->errorAction !== null) {
Qiang Xue committed
72 73
			\Yii::$app->runAction($this->errorAction);
		} elseif (\Yii::$app instanceof \yii\web\Application) {
Qiang Xue committed
74 75 76 77 78
			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
79
				\Yii::$app->renderException($exception);
Qiang Xue committed
80
			} else {
Qiang Xue committed
81
				$view = new View($this);
Qiang Xue committed
82
				if (!YII_DEBUG || $exception instanceof UserException) {
Qiang Xue committed
83 84 85 86 87 88 89
					$viewName = $this->errorView;
				} else {
					$viewName = $this->exceptionView;
				}
				echo $view->render($viewName, array(
					'exception' => $exception,
				));
Qiang Xue committed
90
			}
Qiang Xue committed
91
		} else {
Qiang Xue committed
92
			\Yii::$app->renderException($exception);
Qiang Xue committed
93 94 95 96
		}
	}

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

Qiang Xue committed
130
			if (is_object($value)) {
Qiang Xue committed
131
				$args[$key] = get_class($value);
Qiang Xue committed
132
			} elseif (is_bool($value)) {
Qiang Xue committed
133
				$args[$key] = $value ? 'true' : 'false';
Qiang Xue committed
134 135
			} elseif (is_string($value)) {
				if (strlen($value) > 64) {
Qiang Xue committed
136
					$args[$key] = '"' . substr($value, 0, 64) . '..."';
Qiang Xue committed
137
				} else {
Qiang Xue committed
138
					$args[$key] = '"' . $value . '"';
Qiang Xue committed
139 140
				}
			} elseif (is_array($value)) {
Qiang Xue committed
141
				$args[$key] = 'array(' . $this->argumentsToString($value) . ')';
Qiang Xue committed
142
			} elseif ($value === null) {
Qiang Xue committed
143
				$args[$key] = 'null';
Qiang Xue committed
144
			} elseif (is_resource($value)) {
Qiang Xue committed
145
				$args[$key] = 'resource';
Qiang Xue committed
146
			}
Qiang Xue committed
147

Qiang Xue committed
148 149
			if (is_string($key)) {
				$args[$key] = '"' . $key . '" => ' . $args[$key];
Qiang Xue committed
150
			} elseif ($isAssoc) {
Qiang Xue committed
151
				$args[$key] = $key . ' => ' . $args[$key];
Qiang Xue committed
152 153
			}
		}
Qiang Xue committed
154
		return implode(', ', $args);
Qiang Xue committed
155 156 157 158 159 160 161
	}

	/**
	 * 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
162
	public function isCoreCode($trace)
Qiang Xue committed
163
	{
Qiang Xue committed
164
		if (isset($trace['file'])) {
Qiang Xue committed
165
			return $trace['file'] === 'unknown' || strpos(realpath($trace['file']), YII_PATH . DIRECTORY_SEPARATOR) === 0;
Qiang Xue committed
166 167 168 169 170 171 172 173 174 175
		}
		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
176
	public function renderSourceCode($file, $errorLine, $maxLines)
Qiang Xue committed
177
	{
Qiang Xue committed
178
		$errorLine--; // adjust line number to 0-based from 1-based
Qiang Xue committed
179 180 181
		if ($errorLine < 0 || ($lines = @file($file)) === false || ($lineCount = count($lines)) <= $errorLine) {
			return;
		}
Qiang Xue committed
182

Qiang Xue committed
183 184 185 186
		$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
187

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

	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';
			}
213 214

			$hasCode = isset($t['file']) && $t['file'] !== 'unknown' && is_file($t['file']);
Qiang Xue committed
215 216 217 218 219 220
			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;';
221 222 223
			if(isset($t['file'])) {
				echo $this->htmlEncode($t['file']) . '(' . $t['line'] . '): ';
			}
Qiang Xue committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
			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>';
	}

	public function htmlEncode($text)
	{
Qiang Xue committed
240
		return htmlspecialchars($text, ENT_QUOTES, \Yii::$app->charset);
Qiang Xue committed
241 242 243 244 245 246 247
	}

	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
248
		}
Qiang Xue committed
249 250
	}

Qiang Xue committed
251 252 253 254 255
	/**
	 * @param \Exception $exception
	 */
	public function renderAsHtml($exception)
	{
Qiang Xue committed
256
		$view = new View;
Qiang Xue committed
257
		$name = !YII_DEBUG || $exception instanceof HttpException ? $this->errorView : $this->exceptionView;
Qiang Xue committed
258
		echo $view->render($this, $name, array(
Qiang Xue committed
259 260
			'exception' => $exception,
		));
Qiang Xue committed
261 262
	}
}