ExceptionHandler.php 16 KB

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