暂无描述

ExceptionHandler.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Debug;
  11. use Symfony\Component\Debug\Exception\FlattenException;
  12. use Symfony\Component\Debug\Exception\OutOfMemoryException;
  13. use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
  14. /**
  15. * ExceptionHandler converts an exception to a Response object.
  16. *
  17. * It is mostly useful in debug mode to replace the default PHP/XDebug
  18. * output with something prettier and more useful.
  19. *
  20. * As this class is mainly used during Kernel boot, where nothing is yet
  21. * available, the Response content is always HTML.
  22. *
  23. * @author Fabien Potencier <fabien@symfony.com>
  24. * @author Nicolas Grekas <p@tchwork.com>
  25. */
  26. class ExceptionHandler
  27. {
  28. private $debug;
  29. private $charset;
  30. private $handler;
  31. private $caughtBuffer;
  32. private $caughtLength;
  33. private $fileLinkFormat;
  34. public function __construct($debug = true, $charset = null, $fileLinkFormat = null)
  35. {
  36. $this->debug = $debug;
  37. $this->charset = $charset ?: ini_get('default_charset') ?: 'UTF-8';
  38. $this->fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
  39. }
  40. /**
  41. * Registers the exception handler.
  42. *
  43. * @param bool $debug Enable/disable debug mode, where the stack trace is displayed
  44. * @param string|null $charset The charset used by exception messages
  45. * @param string|null $fileLinkFormat The IDE link template
  46. *
  47. * @return static
  48. */
  49. public static function register($debug = true, $charset = null, $fileLinkFormat = null)
  50. {
  51. $handler = new static($debug, $charset, $fileLinkFormat);
  52. $prev = set_exception_handler(array($handler, 'handle'));
  53. if (is_array($prev) && $prev[0] instanceof ErrorHandler) {
  54. restore_exception_handler();
  55. $prev[0]->setExceptionHandler(array($handler, 'handle'));
  56. }
  57. return $handler;
  58. }
  59. /**
  60. * Sets a user exception handler.
  61. *
  62. * @param callable $handler An handler that will be called on Exception
  63. *
  64. * @return callable|null The previous exception handler if any
  65. */
  66. public function setHandler(callable $handler = null)
  67. {
  68. $old = $this->handler;
  69. $this->handler = $handler;
  70. return $old;
  71. }
  72. /**
  73. * Sets the format for links to source files.
  74. *
  75. * @param string|FileLinkFormatter $format The format for links to source files
  76. *
  77. * @return string The previous file link format
  78. */
  79. public function setFileLinkFormat($fileLinkFormat)
  80. {
  81. $old = $this->fileLinkFormat;
  82. $this->fileLinkFormat = $fileLinkFormat;
  83. return $old;
  84. }
  85. /**
  86. * Sends a response for the given Exception.
  87. *
  88. * To be as fail-safe as possible, the exception is first handled
  89. * by our simple exception handler, then by the user exception handler.
  90. * The latter takes precedence and any output from the former is cancelled,
  91. * if and only if nothing bad happens in this handling path.
  92. */
  93. public function handle(\Exception $exception)
  94. {
  95. if (null === $this->handler || $exception instanceof OutOfMemoryException) {
  96. $this->sendPhpResponse($exception);
  97. return;
  98. }
  99. $caughtLength = $this->caughtLength = 0;
  100. ob_start(function ($buffer) {
  101. $this->caughtBuffer = $buffer;
  102. return '';
  103. });
  104. $this->sendPhpResponse($exception);
  105. while (null === $this->caughtBuffer && ob_end_flush()) {
  106. // Empty loop, everything is in the condition
  107. }
  108. if (isset($this->caughtBuffer[0])) {
  109. ob_start(function ($buffer) {
  110. if ($this->caughtLength) {
  111. // use substr_replace() instead of substr() for mbstring overloading resistance
  112. $cleanBuffer = substr_replace($buffer, '', 0, $this->caughtLength);
  113. if (isset($cleanBuffer[0])) {
  114. $buffer = $cleanBuffer;
  115. }
  116. }
  117. return $buffer;
  118. });
  119. echo $this->caughtBuffer;
  120. $caughtLength = ob_get_length();
  121. }
  122. $this->caughtBuffer = null;
  123. try {
  124. call_user_func($this->handler, $exception);
  125. $this->caughtLength = $caughtLength;
  126. } catch (\Exception $e) {
  127. if (!$caughtLength) {
  128. // All handlers failed. Let PHP handle that now.
  129. throw $exception;
  130. }
  131. }
  132. }
  133. /**
  134. * Sends the error associated with the given Exception as a plain PHP response.
  135. *
  136. * This method uses plain PHP functions like header() and echo to output
  137. * the response.
  138. *
  139. * @param \Exception|FlattenException $exception An \Exception or FlattenException instance
  140. */
  141. public function sendPhpResponse($exception)
  142. {
  143. if (!$exception instanceof FlattenException) {
  144. $exception = FlattenException::create($exception);
  145. }
  146. if (!headers_sent()) {
  147. header(sprintf('HTTP/1.0 %s', $exception->getStatusCode()));
  148. foreach ($exception->getHeaders() as $name => $value) {
  149. header($name.': '.$value, false);
  150. }
  151. header('Content-Type: text/html; charset='.$this->charset);
  152. }
  153. echo $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
  154. }
  155. /**
  156. * Gets the full HTML content associated with the given exception.
  157. *
  158. * @param \Exception|FlattenException $exception An \Exception or FlattenException instance
  159. *
  160. * @return string The HTML content as a string
  161. */
  162. public function getHtml($exception)
  163. {
  164. if (!$exception instanceof FlattenException) {
  165. $exception = FlattenException::create($exception);
  166. }
  167. return $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
  168. }
  169. /**
  170. * Gets the HTML content associated with the given exception.
  171. *
  172. * @param FlattenException $exception A FlattenException instance
  173. *
  174. * @return string The content as a string
  175. */
  176. public function getContent(FlattenException $exception)
  177. {
  178. switch ($exception->getStatusCode()) {
  179. case 404:
  180. $title = 'Sorry, the page you are looking for could not be found.';
  181. break;
  182. default:
  183. $title = 'Whoops, looks like something went wrong.';
  184. }
  185. $content = '';
  186. if ($this->debug) {
  187. try {
  188. $count = count($exception->getAllPrevious());
  189. $total = $count + 1;
  190. foreach ($exception->toArray() as $position => $e) {
  191. $ind = $count - $position + 1;
  192. $class = $this->formatClass($e['class']);
  193. $message = nl2br($this->escapeHtml($e['message']));
  194. $content .= sprintf(<<<'EOF'
  195. <h2 class="block_exception clear_fix">
  196. <span class="exception_counter">%d/%d</span>
  197. <span class="exception_title">%s%s:</span>
  198. <span class="exception_message">%s</span>
  199. </h2>
  200. <div class="block">
  201. <ol class="traces list_exception">
  202. EOF
  203. , $ind, $total, $class, $this->formatPath($e['trace'][0]['file'], $e['trace'][0]['line']), $message);
  204. foreach ($e['trace'] as $trace) {
  205. $content .= ' <li>';
  206. if ($trace['function']) {
  207. $content .= sprintf('at %s%s%s(%s)', $this->formatClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args']));
  208. }
  209. if (isset($trace['file']) && isset($trace['line'])) {
  210. $content .= $this->formatPath($trace['file'], $trace['line']);
  211. }
  212. $content .= "</li>\n";
  213. }
  214. $content .= " </ol>\n</div>\n";
  215. }
  216. } catch (\Exception $e) {
  217. // something nasty happened and we cannot throw an exception anymore
  218. if ($this->debug) {
  219. $title = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $this->escapeHtml($e->getMessage()));
  220. } else {
  221. $title = 'Whoops, looks like something went wrong.';
  222. }
  223. }
  224. }
  225. return <<<EOF
  226. <div id="sf-resetcontent" class="sf-reset">
  227. <h1>$title</h1>
  228. $content
  229. </div>
  230. EOF;
  231. }
  232. /**
  233. * Gets the stylesheet associated with the given exception.
  234. *
  235. * @param FlattenException $exception A FlattenException instance
  236. *
  237. * @return string The stylesheet as a string
  238. */
  239. public function getStylesheet(FlattenException $exception)
  240. {
  241. return <<<'EOF'
  242. .sf-reset { font: 11px Verdana, Arial, sans-serif; color: #333 }
  243. .sf-reset .clear { clear:both; height:0; font-size:0; line-height:0; }
  244. .sf-reset .clear_fix:after { display:block; height:0; clear:both; visibility:hidden; }
  245. .sf-reset .clear_fix { display:inline-block; }
  246. .sf-reset * html .clear_fix { height:1%; }
  247. .sf-reset .clear_fix { display:block; }
  248. .sf-reset, .sf-reset .block { margin: auto }
  249. .sf-reset abbr { border-bottom: 1px dotted #000; cursor: help; }
  250. .sf-reset p { font-size:14px; line-height:20px; color:#868686; padding-bottom:20px }
  251. .sf-reset strong { font-weight:bold; }
  252. .sf-reset a { color:#6c6159; cursor: default; }
  253. .sf-reset a img { border:none; }
  254. .sf-reset a:hover { text-decoration:underline; }
  255. .sf-reset em { font-style:italic; }
  256. .sf-reset h1, .sf-reset h2 { font: 20px Georgia, "Times New Roman", Times, serif }
  257. .sf-reset .exception_counter { background-color: #fff; color: #333; padding: 6px; float: left; margin-right: 10px; float: left; display: block; }
  258. .sf-reset .exception_title { margin-left: 3em; margin-bottom: 0.7em; display: block; }
  259. .sf-reset .exception_message { margin-left: 3em; display: block; }
  260. .sf-reset .traces li { font-size:12px; padding: 2px 4px; list-style-type:decimal; margin-left:20px; }
  261. .sf-reset .block { background-color:#FFFFFF; padding:10px 28px; margin-bottom:20px;
  262. border-bottom-right-radius: 16px;
  263. border-bottom-left-radius: 16px;
  264. border-bottom:1px solid #ccc;
  265. border-right:1px solid #ccc;
  266. border-left:1px solid #ccc;
  267. word-wrap: break-word;
  268. }
  269. .sf-reset .block_exception { background-color:#ddd; color: #333; padding:20px;
  270. border-top-left-radius: 16px;
  271. border-top-right-radius: 16px;
  272. border-top:1px solid #ccc;
  273. border-right:1px solid #ccc;
  274. border-left:1px solid #ccc;
  275. overflow: hidden;
  276. word-wrap: break-word;
  277. }
  278. .sf-reset a { background:none; color:#868686; text-decoration:none; }
  279. .sf-reset a:hover { background:none; color:#313131; text-decoration:underline; }
  280. .sf-reset ol { padding: 10px 0; }
  281. .sf-reset h1 { background-color:#FFFFFF; padding: 15px 28px; margin-bottom: 20px;
  282. border-radius: 10px;
  283. border: 1px solid #ccc;
  284. }
  285. EOF;
  286. }
  287. private function decorate($content, $css)
  288. {
  289. return <<<EOF
  290. <!DOCTYPE html>
  291. <html>
  292. <head>
  293. <meta charset="{$this->charset}" />
  294. <meta name="robots" content="noindex,nofollow" />
  295. <style>
  296. /* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html */
  297. html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:text-top;}sub{vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}
  298. html { background: #eee; padding: 10px }
  299. img { border: 0; }
  300. #sf-resetcontent { width:970px; margin:0 auto; }
  301. $css
  302. </style>
  303. </head>
  304. <body ondblclick="var t = event.target; if (t.title && !t.href) { var f = t.innerHTML; t.innerHTML = t.title; t.title = f; }">
  305. $content
  306. </body>
  307. </html>
  308. EOF;
  309. }
  310. private function formatClass($class)
  311. {
  312. $parts = explode('\\', $class);
  313. return sprintf('<abbr title="%s">%s</abbr>', $class, array_pop($parts));
  314. }
  315. private function formatPath($path, $line)
  316. {
  317. $file = $this->escapeHtml(preg_match('#[^/\\\\]*+$#', $path, $file) ? $file[0] : $path);
  318. $fmt = $this->fileLinkFormat;
  319. if ($fmt && $link = is_string($fmt) ? strtr($fmt, array('%f' => $path, '%l' => $line)) : $fmt->format($path, $line)) {
  320. return sprintf(' in <a href="%s" title="Go to source">%s line %d</a>', $this->escapeHtml($link), $file, $line);
  321. }
  322. return sprintf(' in <a title="%s line %3$d">%s line %d</a>', $this->escapeHtml($path), $file, $line);
  323. }
  324. /**
  325. * Formats an array as a string.
  326. *
  327. * @param array $args The argument array
  328. *
  329. * @return string
  330. */
  331. private function formatArgs(array $args)
  332. {
  333. $result = array();
  334. foreach ($args as $key => $item) {
  335. if ('object' === $item[0]) {
  336. $formattedValue = sprintf('<em>object</em>(%s)', $this->formatClass($item[1]));
  337. } elseif ('array' === $item[0]) {
  338. $formattedValue = sprintf('<em>array</em>(%s)', is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
  339. } elseif ('null' === $item[0]) {
  340. $formattedValue = '<em>null</em>';
  341. } elseif ('boolean' === $item[0]) {
  342. $formattedValue = '<em>'.strtolower(var_export($item[1], true)).'</em>';
  343. } elseif ('resource' === $item[0]) {
  344. $formattedValue = '<em>resource</em>';
  345. } else {
  346. $formattedValue = str_replace("\n", '', $this->escapeHtml(var_export($item[1], true)));
  347. }
  348. $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
  349. }
  350. return implode(', ', $result);
  351. }
  352. /**
  353. * HTML-encodes a string.
  354. */
  355. private function escapeHtml($str)
  356. {
  357. return htmlspecialchars($str, ENT_COMPAT | ENT_SUBSTITUTE, $this->charset);
  358. }
  359. }