You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

443 lines
16KB

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