ExceptionHandler.php 18 KB

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