ErrorHandler.php 20 KB

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