ErrorHandler.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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\base;
  8. use Yii;
  9. use yii\web\HttpException;
  10. /**
  11. * ErrorHandler handles uncaught PHP errors and exceptions.
  12. *
  13. * ErrorHandler displays these errors using appropriate views based on the
  14. * nature of the errors and the mode the application runs at.
  15. *
  16. * ErrorHandler is configured as an application component in [[yii\base\Application]] by default.
  17. * You can access that instance via `Yii::$app->errorHandler`.
  18. *
  19. * @author Qiang Xue <[email protected]>
  20. * @author Timur Ruziev <[email protected]>
  21. * @since 2.0
  22. */
  23. class ErrorHandler extends Component
  24. {
  25. /**
  26. * @var integer maximum number of source code lines to be displayed. Defaults to 25.
  27. */
  28. public $maxSourceLines = 25;
  29. /**
  30. * @var integer maximum number of trace source code lines to be displayed. Defaults to 10.
  31. */
  32. public $maxTraceSourceLines = 10;
  33. /**
  34. * @var boolean whether to discard any existing page output before error display. Defaults to true.
  35. */
  36. public $discardExistingOutput = true;
  37. /**
  38. * @var string the route (e.g. 'site/error') to the controller action that will be used
  39. * to display external errors. Inside the action, it can retrieve the error information
  40. * by Yii::$app->exception. This property defaults to null, meaning ErrorHandler
  41. * will handle the error display.
  42. */
  43. public $errorAction;
  44. /**
  45. * @var string the path of the view file for rendering exceptions without call stack information.
  46. */
  47. public $errorView = '@yii/views/errorHandler/error.php';
  48. /**
  49. * @var string the path of the view file for rendering exceptions.
  50. */
  51. public $exceptionView = '@yii/views/errorHandler/exception.php';
  52. /**
  53. * @var string the path of the view file for rendering exceptions and errors call stack element.
  54. */
  55. public $callStackItemView = '@yii/views/errorHandler/callStackItem.php';
  56. /**
  57. * @var string the path of the view file for rendering previous exceptions.
  58. */
  59. public $previousExceptionView = '@yii/views/errorHandler/previousException.php';
  60. /**
  61. * @var \Exception the exception that is being handled currently.
  62. */
  63. public $exception;
  64. /**
  65. * Handles exception.
  66. * @param \Exception $exception to be handled.
  67. */
  68. public function handle($exception)
  69. {
  70. $this->exception = $exception;
  71. if ($this->discardExistingOutput) {
  72. $this->clearOutput();
  73. }
  74. $this->renderException($exception);
  75. }
  76. /**
  77. * Renders the exception.
  78. * @param \Exception $exception the exception to be handled.
  79. */
  80. protected function renderException($exception)
  81. {
  82. if (Yii::$app instanceof \yii\console\Application || YII_ENV_TEST) {
  83. echo Yii::$app->renderException($exception);
  84. return;
  85. }
  86. $useErrorView = !YII_DEBUG || $exception instanceof UserException;
  87. $response = Yii::$app->getResponse();
  88. $response->getHeaders()->removeAll();
  89. if ($useErrorView && $this->errorAction !== null) {
  90. $result = Yii::$app->runAction($this->errorAction);
  91. if ($result instanceof Response) {
  92. $response = $result;
  93. } else {
  94. $response->data = $result;
  95. }
  96. } elseif ($response->format === \yii\web\Response::FORMAT_HTML) {
  97. if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
  98. // AJAX request
  99. $response->data = Yii::$app->renderException($exception);
  100. } else {
  101. // if there is an error during error rendering it's useful to
  102. // display PHP error in debug mode instead of a blank screen
  103. if (YII_DEBUG) {
  104. ini_set('display_errors', 1);
  105. }
  106. $file = $useErrorView ? $this->errorView : $this->exceptionView;
  107. $response->data = $this->renderFile($file, [
  108. 'exception' => $exception,
  109. ]);
  110. }
  111. } elseif ($exception instanceof Arrayable) {
  112. $response->data = $exception;
  113. } else {
  114. $response->data = [
  115. 'type' => get_class($exception),
  116. 'name' => 'Exception',
  117. 'message' => $exception->getMessage(),
  118. 'code' => $exception->getCode(),
  119. ];
  120. }
  121. if ($exception instanceof HttpException) {
  122. $response->setStatusCode($exception->statusCode);
  123. } else {
  124. $response->setStatusCode(500);
  125. }
  126. $response->send();
  127. }
  128. /**
  129. * Converts special characters to HTML entities.
  130. * @param string $text to encode.
  131. * @return string encoded original text.
  132. */
  133. public function htmlEncode($text)
  134. {
  135. return htmlspecialchars($text, ENT_QUOTES, Yii::$app->charset);
  136. }
  137. /**
  138. * Removes all output echoed before calling this method.
  139. */
  140. public function clearOutput()
  141. {
  142. // the following manual level counting is to deal with zlib.output_compression set to On
  143. for ($level = ob_get_level(); $level > 0; --$level) {
  144. if (!@ob_end_clean()) {
  145. ob_clean();
  146. }
  147. }
  148. }
  149. /**
  150. * Adds informational links to the given PHP type/class.
  151. * @param string $code type/class name to be linkified.
  152. * @return string linkified with HTML type/class name.
  153. */
  154. public function addTypeLinks($code)
  155. {
  156. $html = '';
  157. if (strpos($code, '\\') !== false) {
  158. // namespaced class
  159. foreach (explode('\\', $code) as $part) {
  160. $html .= '<a href="http://yiiframework.com/doc/api/2.0/' . $this->htmlEncode($part) . '" target="_blank">' . $this->htmlEncode($part) . '</a>\\';
  161. }
  162. $html = rtrim($html, '\\');
  163. } elseif (strpos($code, '()') !== false) {
  164. // method/function call
  165. $html = preg_replace_callback('/^(.*)\(\)$/', function ($matches) {
  166. return '<a href="http://yiiframework.com/doc/api/2.0/' . $this->htmlEncode($matches[1]) . '" target="_blank">' .
  167. $this->htmlEncode($matches[1]) . '</a>()';
  168. }, $code);
  169. }
  170. return $html;
  171. }
  172. /**
  173. * Renders a view file as a PHP script.
  174. * @param string $_file_ the view file.
  175. * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
  176. * @return string the rendering result
  177. */
  178. public function renderFile($_file_, $_params_)
  179. {
  180. $_params_['handler'] = $this;
  181. if ($this->exception instanceof ErrorException) {
  182. ob_start();
  183. ob_implicit_flush(false);
  184. extract($_params_, EXTR_OVERWRITE);
  185. require(Yii::getAlias($_file_));
  186. return ob_get_clean();
  187. } else {
  188. return Yii::$app->getView()->renderFile($_file_, $_params_, $this);
  189. }
  190. }
  191. /**
  192. * Renders the previous exception stack for a given Exception.
  193. * @param \Exception $exception the exception whose precursors should be rendered.
  194. * @return string HTML content of the rendered previous exceptions.
  195. * Empty string if there are none.
  196. */
  197. public function renderPreviousExceptions($exception)
  198. {
  199. if (($previous = $exception->getPrevious()) !== null) {
  200. return $this->renderFile($this->previousExceptionView, ['exception' => $previous]);
  201. } else {
  202. return '';
  203. }
  204. }
  205. /**
  206. * Renders a single call stack element.
  207. * @param string|null $file name where call has happened.
  208. * @param integer|null $line number on which call has happened.
  209. * @param string|null $class called class name.
  210. * @param string|null $method called function/method name.
  211. * @param integer $index number of the call stack element.
  212. * @return string HTML content of the rendered call stack element.
  213. */
  214. public function renderCallStackItem($file, $line, $class, $method, $index)
  215. {
  216. $lines = [];
  217. $begin = $end = 0;
  218. if ($file !== null && $line !== null) {
  219. $line--; // adjust line number from one-based to zero-based
  220. $lines = @file($file);
  221. if ($line < 0 || $lines === false || ($lineCount = count($lines)) < $line + 1) {
  222. return '';
  223. }
  224. $half = (int)(($index == 0 ? $this->maxSourceLines : $this->maxTraceSourceLines) / 2);
  225. $begin = $line - $half > 0 ? $line - $half : 0;
  226. $end = $line + $half < $lineCount ? $line + $half : $lineCount - 1;
  227. }
  228. return $this->renderFile($this->callStackItemView, [
  229. 'file' => $file,
  230. 'line' => $line,
  231. 'class' => $class,
  232. 'method' => $method,
  233. 'index' => $index,
  234. 'lines' => $lines,
  235. 'begin' => $begin,
  236. 'end' => $end,
  237. ]);
  238. }
  239. /**
  240. * Renders the request information.
  241. * @return string the rendering result
  242. */
  243. public function renderRequest()
  244. {
  245. $request = '';
  246. foreach (['_GET', '_POST', '_SERVER', '_FILES', '_COOKIE', '_SESSION', '_ENV'] as $name) {
  247. if (!empty($GLOBALS[$name])) {
  248. $request .= '$' . $name . ' = ' . var_export($GLOBALS[$name], true) . ";\n\n";
  249. }
  250. }
  251. return '<pre>' . rtrim($request, "\n") . '</pre>';
  252. }
  253. /**
  254. * Determines whether given name of the file belongs to the framework.
  255. * @param string $file name to be checked.
  256. * @return boolean whether given name of the file belongs to the framework.
  257. */
  258. public function isCoreFile($file)
  259. {
  260. return $file === null || strpos(realpath($file), YII_PATH . DIRECTORY_SEPARATOR) === 0;
  261. }
  262. /**
  263. * Creates HTML containing link to the page with the information on given HTTP status code.
  264. * @param integer $statusCode to be used to generate information link.
  265. * @param string $statusDescription Description to display after the the status code.
  266. * @return string generated HTML with HTTP status code information.
  267. */
  268. public function createHttpStatusLink($statusCode, $statusDescription)
  269. {
  270. return '<a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#' . (int)$statusCode . '" target="_blank">HTTP ' . (int)$statusCode . ' &ndash; ' . $statusDescription . '</a>';
  271. }
  272. /**
  273. * Creates string containing HTML link which refers to the home page of determined web-server software
  274. * and its full name.
  275. * @return string server software information hyperlink.
  276. */
  277. public function createServerInformationLink()
  278. {
  279. static $serverUrls = [
  280. 'http://httpd.apache.org/' => ['apache'],
  281. 'http://nginx.org/' => ['nginx'],
  282. 'http://lighttpd.net/' => ['lighttpd'],
  283. 'http://gwan.com/' => ['g-wan', 'gwan'],
  284. 'http://iis.net/' => ['iis', 'services'],
  285. 'http://php.net/manual/en/features.commandline.webserver.php' => ['development'],
  286. ];
  287. if (isset($_SERVER['SERVER_SOFTWARE'])) {
  288. foreach ($serverUrls as $url => $keywords) {
  289. foreach ($keywords as $keyword) {
  290. if (stripos($_SERVER['SERVER_SOFTWARE'], $keyword) !== false) {
  291. return '<a href="' . $url . '" target="_blank">' . $this->htmlEncode($_SERVER['SERVER_SOFTWARE']) . '</a>';
  292. }
  293. }
  294. }
  295. }
  296. return '';
  297. }
  298. /**
  299. * Creates string containing HTML link which refers to the page with the current version
  300. * of the framework and version number text.
  301. * @return string framework version information hyperlink.
  302. */
  303. public function createFrameworkVersionLink()
  304. {
  305. return '<a href="http://github.com/yiisoft/yii2/" target="_blank">' . $this->htmlEncode(Yii::getVersion()) . '</a>';
  306. }
  307. }