1 | <?php |
||
2 | /** |
||
3 | * @link http://www.yiiframework.com/ |
||
4 | * @copyright Copyright (c) 2008 Yii Software LLC |
||
5 | * @license http://www.yiiframework.com/license/ |
||
6 | */ |
||
7 | |||
8 | namespace yii\web; |
||
9 | |||
10 | use Yii; |
||
11 | use yii\base\ErrorException; |
||
12 | use yii\base\Exception; |
||
13 | use yii\base\UserException; |
||
14 | use yii\helpers\VarDumper; |
||
15 | |||
16 | /** |
||
17 | * ErrorHandler handles uncaught PHP errors and exceptions. |
||
18 | * |
||
19 | * ErrorHandler displays these errors using appropriate views based on the |
||
20 | * nature of the errors and the mode the application runs at. |
||
21 | * |
||
22 | * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default. |
||
23 | * You can access that instance via `Yii::$app->errorHandler`. |
||
24 | * |
||
25 | * For more details and usage information on ErrorHandler, see the [guide article on handling errors](guide:runtime-handling-errors). |
||
26 | * |
||
27 | * @author Qiang Xue <[email protected]> |
||
28 | * @author Timur Ruziev <[email protected]> |
||
29 | * @since 2.0 |
||
30 | */ |
||
31 | class ErrorHandler extends \yii\base\ErrorHandler |
||
32 | { |
||
33 | /** |
||
34 | * @var int maximum number of source code lines to be displayed. Defaults to 19. |
||
35 | */ |
||
36 | public $maxSourceLines = 19; |
||
37 | /** |
||
38 | * @var int maximum number of trace source code lines to be displayed. Defaults to 13. |
||
39 | */ |
||
40 | public $maxTraceSourceLines = 13; |
||
41 | /** |
||
42 | * @var string the route (e.g. `site/error`) to the controller action that will be used |
||
43 | * to display external errors. Inside the action, it can retrieve the error information |
||
44 | * using `Yii::$app->errorHandler->exception`. This property defaults to null, meaning ErrorHandler |
||
45 | * will handle the error display. |
||
46 | */ |
||
47 | public $errorAction; |
||
48 | /** |
||
49 | * @var string the path of the view file for rendering exceptions without call stack information. |
||
50 | */ |
||
51 | public $errorView = '@yii/views/errorHandler/error.php'; |
||
52 | /** |
||
53 | * @var string the path of the view file for rendering exceptions. |
||
54 | */ |
||
55 | public $exceptionView = '@yii/views/errorHandler/exception.php'; |
||
56 | /** |
||
57 | * @var string the path of the view file for rendering exceptions and errors call stack element. |
||
58 | */ |
||
59 | public $callStackItemView = '@yii/views/errorHandler/callStackItem.php'; |
||
60 | /** |
||
61 | * @var string the path of the view file for rendering previous exceptions. |
||
62 | */ |
||
63 | public $previousExceptionView = '@yii/views/errorHandler/previousException.php'; |
||
64 | /** |
||
65 | * @var array list of the PHP predefined variables that should be displayed on the error page. |
||
66 | * Note that a variable must be accessible via `$GLOBALS`. Otherwise it won't be displayed. |
||
67 | * Defaults to `['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION']`. |
||
68 | * @see renderRequest() |
||
69 | * @since 2.0.7 |
||
70 | */ |
||
71 | public $displayVars = ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION']; |
||
72 | /** |
||
73 | * @var string trace line with placeholders to be be substituted. |
||
74 | * The placeholders are {file}, {line} and {text} and the string should be as follows. |
||
75 | * |
||
76 | * `File: {file} - Line: {line} - Text: {text}` |
||
77 | * |
||
78 | * @example <a href="ide://open?file={file}&line={line}">{html}</a> |
||
79 | * @see https://github.com/yiisoft/yii2-debug#open-files-in-ide |
||
80 | * @since 2.0.14 |
||
81 | */ |
||
82 | public $traceLine = '{html}'; |
||
83 | |||
84 | |||
85 | /** |
||
86 | * Renders the exception. |
||
87 | * @param \Exception|\Error $exception the exception to be rendered. |
||
88 | */ |
||
89 | 2 | protected function renderException($exception) |
|
90 | { |
||
91 | 2 | if (Yii::$app->has('response')) { |
|
92 | 2 | $response = Yii::$app->getResponse(); |
|
93 | // reset parameters of response to avoid interference with partially created response data |
||
94 | // in case the error occurred while sending the response. |
||
95 | 2 | $response->isSent = false; |
|
96 | 2 | $response->stream = null; |
|
97 | 2 | $response->data = null; |
|
98 | 2 | $response->content = null; |
|
99 | } else { |
||
100 | $response = new Response(); |
||
101 | } |
||
102 | |||
103 | 2 | $response->setStatusCodeByException($exception); |
|
104 | |||
105 | 2 | $useErrorView = $response->format === Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException); |
|
106 | |||
107 | 2 | if ($useErrorView && $this->errorAction !== null) { |
|
108 | $result = Yii::$app->runAction($this->errorAction); |
||
109 | if ($result instanceof Response) { |
||
110 | $response = $result; |
||
111 | } else { |
||
112 | $response->data = $result; |
||
113 | } |
||
114 | 2 | } elseif ($response->format === Response::FORMAT_HTML) { |
|
115 | 2 | if ($this->shouldRenderSimpleHtml()) { |
|
116 | // AJAX request |
||
117 | $response->data = '<pre>' . $this->htmlEncode(static::convertExceptionToString($exception)) . '</pre>'; |
||
118 | } else { |
||
119 | // if there is an error during error rendering it's useful to |
||
120 | // display PHP error in debug mode instead of a blank screen |
||
121 | 2 | if (YII_DEBUG) { |
|
122 | 2 | ini_set('display_errors', 1); |
|
123 | } |
||
124 | 2 | $file = $useErrorView ? $this->errorView : $this->exceptionView; |
|
125 | 2 | $response->data = $this->renderFile($file, [ |
|
126 | 2 | 'exception' => $exception, |
|
127 | ]); |
||
128 | } |
||
129 | } elseif ($response->format === Response::FORMAT_RAW) { |
||
130 | $response->data = static::convertExceptionToString($exception); |
||
131 | } else { |
||
132 | $response->data = $this->convertExceptionToArray($exception); |
||
133 | } |
||
134 | |||
135 | 2 | $response->send(); |
|
136 | 2 | } |
|
137 | |||
138 | /** |
||
139 | * Converts an exception into an array. |
||
140 | * @param \Exception|\Error $exception the exception being converted |
||
141 | * @return array the array representation of the exception. |
||
142 | */ |
||
143 | protected function convertExceptionToArray($exception) |
||
144 | { |
||
145 | if (!YII_DEBUG && !$exception instanceof UserException && !$exception instanceof HttpException) { |
||
146 | $exception = new HttpException(500, Yii::t('yii', 'An internal server error occurred.')); |
||
147 | } |
||
148 | |||
149 | $array = [ |
||
150 | 'name' => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : 'Exception', |
||
151 | 'message' => $exception->getMessage(), |
||
152 | 'code' => $exception->getCode(), |
||
153 | ]; |
||
154 | if ($exception instanceof HttpException) { |
||
155 | $array['status'] = $exception->statusCode; |
||
156 | } |
||
157 | if (YII_DEBUG) { |
||
158 | $array['type'] = get_class($exception); |
||
159 | if (!$exception instanceof UserException) { |
||
160 | $array['file'] = $exception->getFile(); |
||
161 | $array['line'] = $exception->getLine(); |
||
162 | $array['stack-trace'] = explode("\n", $exception->getTraceAsString()); |
||
163 | if ($exception instanceof \yii\db\Exception) { |
||
164 | $array['error-info'] = $exception->errorInfo; |
||
165 | } |
||
166 | } |
||
167 | } |
||
168 | if (($prev = $exception->getPrevious()) !== null) { |
||
169 | $array['previous'] = $this->convertExceptionToArray($prev); |
||
170 | } |
||
171 | |||
172 | return $array; |
||
173 | } |
||
174 | |||
175 | /** |
||
176 | * Converts special characters to HTML entities. |
||
177 | * @param string $text to encode. |
||
178 | * @return string encoded original text. |
||
179 | */ |
||
180 | 4 | public function htmlEncode($text) |
|
181 | { |
||
182 | 4 | return htmlspecialchars($text, ENT_QUOTES, 'UTF-8'); |
|
183 | } |
||
184 | |||
185 | /** |
||
186 | * Adds informational links to the given PHP type/class. |
||
187 | * @param string $code type/class name to be linkified. |
||
188 | * @return string linkified with HTML type/class name. |
||
189 | */ |
||
190 | public function addTypeLinks($code) |
||
191 | { |
||
192 | if (preg_match('/(.*?)::([^(]+)/', $code, $matches)) { |
||
193 | $class = $matches[1]; |
||
194 | $method = $matches[2]; |
||
195 | $text = $this->htmlEncode($class) . '::' . $this->htmlEncode($method); |
||
196 | } else { |
||
197 | $class = $code; |
||
198 | $method = null; |
||
199 | $text = $this->htmlEncode($class); |
||
200 | } |
||
201 | |||
202 | $url = null; |
||
203 | |||
204 | $shouldGenerateLink = true; |
||
205 | if ($method !== null && substr_compare($method, '{closure}', -9) !== 0) { |
||
206 | $reflection = new \ReflectionClass($class); |
||
207 | if ($reflection->hasMethod($method)) { |
||
208 | $reflectionMethod = $reflection->getMethod($method); |
||
209 | $shouldGenerateLink = $reflectionMethod->isPublic() || $reflectionMethod->isProtected(); |
||
210 | } else { |
||
211 | $shouldGenerateLink = false; |
||
212 | } |
||
213 | } |
||
214 | |||
215 | if ($shouldGenerateLink) { |
||
216 | $url = $this->getTypeUrl($class, $method); |
||
217 | } |
||
218 | |||
219 | if ($url === null) { |
||
220 | return $text; |
||
221 | } |
||
222 | |||
223 | return '<a href="' . $url . '" target="_blank">' . $text . '</a>'; |
||
224 | } |
||
225 | |||
226 | /** |
||
227 | * Returns the informational link URL for a given PHP type/class. |
||
228 | * @param string $class the type or class name. |
||
229 | * @param string|null $method the method name. |
||
230 | * @return string|null the informational link URL. |
||
231 | * @see addTypeLinks() |
||
232 | */ |
||
233 | protected function getTypeUrl($class, $method) |
||
234 | { |
||
235 | if (strncmp($class, 'yii\\', 4) !== 0) { |
||
236 | return null; |
||
237 | } |
||
238 | |||
239 | $page = $this->htmlEncode(strtolower(str_replace('\\', '-', $class))); |
||
240 | $url = "http://www.yiiframework.com/doc-2.0/$page.html"; |
||
241 | if ($method) { |
||
242 | $url .= "#$method()-detail"; |
||
243 | } |
||
244 | |||
245 | return $url; |
||
246 | } |
||
247 | |||
248 | /** |
||
249 | * Renders a view file as a PHP script. |
||
250 | * @param string $_file_ the view file. |
||
251 | * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file. |
||
252 | * @return string the rendering result |
||
253 | */ |
||
254 | 6 | public function renderFile($_file_, $_params_) |
|
255 | { |
||
256 | 6 | $_params_['handler'] = $this; |
|
257 | 6 | if ($this->exception instanceof ErrorException || !Yii::$app->has('view')) { |
|
258 | ob_start(); |
||
259 | ob_implicit_flush(false); |
||
260 | extract($_params_, EXTR_OVERWRITE); |
||
261 | require Yii::getAlias($_file_); |
||
262 | |||
263 | return ob_get_clean(); |
||
264 | } |
||
265 | |||
266 | 6 | $view = Yii::$app->getView(); |
|
267 | 6 | $view->clear(); |
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
268 | |||
269 | 6 | return $view->renderFile($_file_, $_params_, $this); |
|
270 | } |
||
271 | |||
272 | /** |
||
273 | * Renders the previous exception stack for a given Exception. |
||
274 | * @param \Exception $exception the exception whose precursors should be rendered. |
||
275 | * @return string HTML content of the rendered previous exceptions. |
||
276 | * Empty string if there are none. |
||
277 | */ |
||
278 | public function renderPreviousExceptions($exception) |
||
279 | { |
||
280 | if (($previous = $exception->getPrevious()) !== null) { |
||
281 | return $this->renderFile($this->previousExceptionView, ['exception' => $previous]); |
||
282 | } |
||
283 | |||
284 | return ''; |
||
285 | } |
||
286 | |||
287 | /** |
||
288 | * Renders a single call stack element. |
||
289 | * @param string|null $file name where call has happened. |
||
290 | * @param int|null $line number on which call has happened. |
||
291 | * @param string|null $class called class name. |
||
292 | * @param string|null $method called function/method name. |
||
293 | * @param array $args array of method arguments. |
||
294 | * @param int $index number of the call stack element. |
||
295 | * @return string HTML content of the rendered call stack element. |
||
296 | */ |
||
297 | 1 | public function renderCallStackItem($file, $line, $class, $method, $args, $index) |
|
298 | { |
||
299 | 1 | $lines = []; |
|
300 | 1 | $begin = $end = 0; |
|
301 | 1 | if ($file !== null && $line !== null) { |
|
302 | 1 | $line--; // adjust line number from one-based to zero-based |
|
303 | 1 | $lines = @file($file); |
|
304 | 1 | if ($line < 0 || $lines === false || ($lineCount = count($lines)) < $line) { |
|
305 | return ''; |
||
306 | } |
||
307 | |||
308 | 1 | $half = (int) (($index === 1 ? $this->maxSourceLines : $this->maxTraceSourceLines) / 2); |
|
309 | 1 | $begin = $line - $half > 0 ? $line - $half : 0; |
|
310 | 1 | $end = $line + $half < $lineCount ? $line + $half : $lineCount - 1; |
|
311 | } |
||
312 | |||
313 | 1 | return $this->renderFile($this->callStackItemView, [ |
|
314 | 1 | 'file' => $file, |
|
315 | 1 | 'line' => $line, |
|
316 | 1 | 'class' => $class, |
|
317 | 1 | 'method' => $method, |
|
318 | 1 | 'index' => $index, |
|
319 | 1 | 'lines' => $lines, |
|
320 | 1 | 'begin' => $begin, |
|
321 | 1 | 'end' => $end, |
|
322 | 1 | 'args' => $args, |
|
323 | ]); |
||
324 | } |
||
325 | |||
326 | /** |
||
327 | * Renders call stack. |
||
328 | * @param \Exception|\ParseError $exception exception to get call stack from |
||
329 | * @return string HTML content of the rendered call stack. |
||
330 | * @since 2.0.12 |
||
331 | */ |
||
332 | public function renderCallStack($exception) |
||
333 | { |
||
334 | $out = '<ul>'; |
||
335 | $out .= $this->renderCallStackItem($exception->getFile(), $exception->getLine(), null, null, [], 1); |
||
336 | for ($i = 0, $trace = $exception->getTrace(), $length = count($trace); $i < $length; ++$i) { |
||
337 | $file = !empty($trace[$i]['file']) ? $trace[$i]['file'] : null; |
||
338 | $line = !empty($trace[$i]['line']) ? $trace[$i]['line'] : null; |
||
339 | $class = !empty($trace[$i]['class']) ? $trace[$i]['class'] : null; |
||
340 | $function = null; |
||
341 | if (!empty($trace[$i]['function']) && $trace[$i]['function'] !== 'unknown') { |
||
342 | $function = $trace[$i]['function']; |
||
343 | } |
||
344 | $args = !empty($trace[$i]['args']) ? $trace[$i]['args'] : []; |
||
345 | $out .= $this->renderCallStackItem($file, $line, $class, $function, $args, $i + 2); |
||
346 | } |
||
347 | $out .= '</ul>'; |
||
348 | return $out; |
||
349 | } |
||
350 | |||
351 | /** |
||
352 | * Renders the global variables of the request. |
||
353 | * List of global variables is defined in [[displayVars]]. |
||
354 | * @return string the rendering result |
||
355 | * @see displayVars |
||
356 | */ |
||
357 | public function renderRequest() |
||
358 | { |
||
359 | $request = ''; |
||
360 | foreach ($this->displayVars as $name) { |
||
361 | if (!empty($GLOBALS[$name])) { |
||
362 | $request .= '$' . $name . ' = ' . VarDumper::export($GLOBALS[$name]) . ";\n\n"; |
||
363 | } |
||
364 | } |
||
365 | |||
366 | return '<pre>' . $this->htmlEncode(rtrim($request, "\n")) . '</pre>'; |
||
367 | } |
||
368 | |||
369 | /** |
||
370 | * Determines whether given name of the file belongs to the framework. |
||
371 | * @param string $file name to be checked. |
||
372 | * @return bool whether given name of the file belongs to the framework. |
||
373 | */ |
||
374 | 1 | public function isCoreFile($file) |
|
375 | { |
||
376 | 1 | return $file === null || strpos(realpath($file), YII2_PATH . DIRECTORY_SEPARATOR) === 0; |
|
377 | } |
||
378 | |||
379 | /** |
||
380 | * Creates HTML containing link to the page with the information on given HTTP status code. |
||
381 | * @param int $statusCode to be used to generate information link. |
||
382 | * @param string $statusDescription Description to display after the the status code. |
||
383 | * @return string generated HTML with HTTP status code information. |
||
384 | */ |
||
385 | public function createHttpStatusLink($statusCode, $statusDescription) |
||
386 | { |
||
387 | return '<a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#' . (int) $statusCode . '" target="_blank">HTTP ' . (int) $statusCode . ' – ' . $statusDescription . '</a>'; |
||
388 | } |
||
389 | |||
390 | /** |
||
391 | * Creates string containing HTML link which refers to the home page of determined web-server software |
||
392 | * and its full name. |
||
393 | * @return string server software information hyperlink. |
||
394 | */ |
||
395 | public function createServerInformationLink() |
||
396 | { |
||
397 | $serverUrls = [ |
||
398 | 'http://httpd.apache.org/' => ['apache'], |
||
399 | 'http://nginx.org/' => ['nginx'], |
||
400 | 'http://lighttpd.net/' => ['lighttpd'], |
||
401 | 'http://gwan.com/' => ['g-wan', 'gwan'], |
||
402 | 'http://iis.net/' => ['iis', 'services'], |
||
403 | 'https://secure.php.net/manual/en/features.commandline.webserver.php' => ['development'], |
||
404 | ]; |
||
405 | if (isset($_SERVER['SERVER_SOFTWARE'])) { |
||
406 | foreach ($serverUrls as $url => $keywords) { |
||
407 | foreach ($keywords as $keyword) { |
||
408 | if (stripos($_SERVER['SERVER_SOFTWARE'], $keyword) !== false) { |
||
409 | return '<a href="' . $url . '" target="_blank">' . $this->htmlEncode($_SERVER['SERVER_SOFTWARE']) . '</a>'; |
||
410 | } |
||
411 | } |
||
412 | } |
||
413 | } |
||
414 | |||
415 | return ''; |
||
416 | } |
||
417 | |||
418 | /** |
||
419 | * Creates string containing HTML link which refers to the page with the current version |
||
420 | * of the framework and version number text. |
||
421 | * @return string framework version information hyperlink. |
||
422 | */ |
||
423 | public function createFrameworkVersionLink() |
||
424 | { |
||
425 | return '<a href="http://github.com/yiisoft/yii2/" target="_blank">' . $this->htmlEncode(Yii::getVersion()) . '</a>'; |
||
426 | } |
||
427 | |||
428 | /** |
||
429 | * Converts arguments array to its string representation. |
||
430 | * |
||
431 | * @param array $args arguments array to be converted |
||
432 | * @return string string representation of the arguments array |
||
433 | */ |
||
434 | public function argumentsToString($args) |
||
435 | { |
||
436 | $count = 0; |
||
437 | $isAssoc = $args !== array_values($args); |
||
438 | |||
439 | foreach ($args as $key => $value) { |
||
440 | $count++; |
||
441 | if ($count >= 5) { |
||
442 | if ($count > 5) { |
||
443 | unset($args[$key]); |
||
444 | } else { |
||
445 | $args[$key] = '...'; |
||
446 | } |
||
447 | continue; |
||
448 | } |
||
449 | |||
450 | if (is_object($value)) { |
||
451 | $args[$key] = '<span class="title">' . $this->htmlEncode(get_class($value)) . '</span>'; |
||
452 | } elseif (is_bool($value)) { |
||
453 | $args[$key] = '<span class="keyword">' . ($value ? 'true' : 'false') . '</span>'; |
||
454 | } elseif (is_string($value)) { |
||
455 | $fullValue = $this->htmlEncode($value); |
||
456 | if (mb_strlen($value, 'UTF-8') > 32) { |
||
457 | $displayValue = $this->htmlEncode(mb_substr($value, 0, 32, 'UTF-8')) . '...'; |
||
458 | $args[$key] = "<span class=\"string\" title=\"$fullValue\">'$displayValue'</span>"; |
||
459 | } else { |
||
460 | $args[$key] = "<span class=\"string\">'$fullValue'</span>"; |
||
461 | } |
||
462 | } elseif (is_array($value)) { |
||
463 | $args[$key] = '[' . $this->argumentsToString($value) . ']'; |
||
464 | } elseif ($value === null) { |
||
465 | $args[$key] = '<span class="keyword">null</span>'; |
||
466 | } elseif (is_resource($value)) { |
||
467 | $args[$key] = '<span class="keyword">resource</span>'; |
||
468 | } else { |
||
469 | $args[$key] = '<span class="number">' . $value . '</span>'; |
||
470 | } |
||
471 | |||
472 | if (is_string($key)) { |
||
473 | $args[$key] = '<span class="string">\'' . $this->htmlEncode($key) . "'</span> => $args[$key]"; |
||
474 | } elseif ($isAssoc) { |
||
475 | $args[$key] = "<span class=\"number\">$key</span> => $args[$key]"; |
||
476 | } |
||
477 | } |
||
478 | |||
479 | return implode(', ', $args); |
||
480 | } |
||
481 | |||
482 | /** |
||
483 | * Returns human-readable exception name. |
||
484 | * @param \Exception $exception |
||
485 | * @return string human-readable exception name or null if it cannot be determined |
||
486 | */ |
||
487 | 3 | public function getExceptionName($exception) |
|
488 | { |
||
489 | 3 | if ($exception instanceof \yii\base\Exception || $exception instanceof \yii\base\InvalidCallException || $exception instanceof \yii\base\InvalidParamException || $exception instanceof \yii\base\UnknownMethodException) { |
|
490 | 3 | return $exception->getName(); |
|
491 | } |
||
492 | |||
493 | return null; |
||
494 | } |
||
495 | |||
496 | /** |
||
497 | * @return bool if simple HTML should be rendered |
||
498 | * @since 2.0.12 |
||
499 | */ |
||
500 | protected function shouldRenderSimpleHtml() |
||
501 | { |
||
502 | return YII_ENV_TEST || Yii::$app->request->getIsAjax(); |
||
503 | } |
||
504 | } |
||
505 |