ErrorHandler.php 18 KB

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