ErrorHandler.php 19 KB

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