ExceptionHandler.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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, '%')) {
  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. private function failSafeHandle(\Exception $exception)
  140. {
  141. if (class_exists('Symfony\Component\HttpFoundation\Response', false)
  142. && __CLASS__ !== get_class($this)
  143. && ($reflector = new \ReflectionMethod($this, 'createResponse'))
  144. && __CLASS__ !== $reflector->class
  145. ) {
  146. $response = $this->createResponse($exception);
  147. $response->sendHeaders();
  148. $response->sendContent();
  149. return;
  150. }
  151. $this->sendPhpResponse($exception);
  152. }
  153. /**
  154. * Sends the error associated with the given Exception as a plain PHP response.
  155. *
  156. * This method uses plain PHP functions like header() and echo to output
  157. * the response.
  158. *
  159. * @param \Exception|FlattenException $exception An \Exception instance
  160. */
  161. public function sendPhpResponse($exception)
  162. {
  163. if (!$exception instanceof FlattenException) {
  164. $exception = FlattenException::create($exception);
  165. }
  166. if (!headers_sent()) {
  167. header(sprintf('HTTP/1.0 %s', $exception->getStatusCode()));
  168. foreach ($exception->getHeaders() as $name => $value) {
  169. header($name.': '.$value, false);
  170. }
  171. header('Content-Type: text/html; charset='.$this->charset);
  172. }
  173. echo $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
  174. }
  175. /**
  176. * Creates the error Response associated with the given Exception.
  177. *
  178. * @param \Exception|FlattenException $exception An \Exception instance
  179. *
  180. * @return Response A Response instance
  181. */
  182. public function createResponse($exception)
  183. {
  184. if (!$exception instanceof FlattenException) {
  185. $exception = FlattenException::create($exception);
  186. }
  187. return Response::create($this->decorate($this->getContent($exception), $this->getStylesheet($exception)), $exception->getStatusCode(), $exception->getHeaders())->setCharset($this->charset);
  188. }
  189. /**
  190. * Gets the HTML content associated with the given exception.
  191. *
  192. * @param FlattenException $exception A FlattenException instance
  193. *
  194. * @return string The content as a string
  195. */
  196. public function getContent(FlattenException $exception)
  197. {
  198. switch ($exception->getStatusCode()) {
  199. case 404:
  200. $title = 'Sorry, the page you are looking for could not be found.';
  201. break;
  202. default:
  203. $title = 'Whoops, looks like something went wrong.';
  204. }
  205. $content = '';
  206. if ($this->debug) {
  207. try {
  208. $count = count($exception->getAllPrevious());
  209. $total = $count + 1;
  210. foreach ($exception->toArray() as $position => $e) {
  211. $ind = $count - $position + 1;
  212. $class = $this->formatClass($e['class']);
  213. $message = nl2br($this->escapeHtml($e['message']));
  214. $content .= sprintf(<<<EOF
  215. <h2 class="block_exception clear_fix">
  216. <span class="exception_counter">%d/%d</span>
  217. <span class="exception_title">%s%s:</span>
  218. <span class="exception_message">%s</span>
  219. </h2>
  220. <div class="block">
  221. <ol class="traces list_exception">
  222. EOF
  223. , $ind, $total, $class, $this->formatPath($e['trace'][0]['file'], $e['trace'][0]['line']), $message);
  224. foreach ($e['trace'] as $trace) {
  225. $content .= ' <li>';
  226. if ($trace['function']) {
  227. $content .= sprintf('at %s%s%s(%s)', $this->formatClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args']));
  228. }
  229. if (isset($trace['file']) && isset($trace['line'])) {
  230. $content .= $this->formatPath($trace['file'], $trace['line']);
  231. }
  232. $content .= "</li>\n";
  233. }
  234. $content .= " </ol>\n</div>\n";
  235. }
  236. } catch (\Exception $e) {
  237. // something nasty happened and we cannot throw an exception anymore
  238. if ($this->debug) {
  239. $title = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $this->escapeHtml($e->getMessage()));
  240. } else {
  241. $title = 'Whoops, looks like something went wrong.';
  242. }
  243. }
  244. }
  245. return <<<EOF
  246. <div id="sf-resetcontent" class="sf-reset">
  247. <h1>$title</h1>
  248. $content
  249. </div>
  250. EOF;
  251. }
  252. /**
  253. * Gets the stylesheet associated with the given exception.
  254. *
  255. * @param FlattenException $exception A FlattenException instance
  256. *
  257. * @return string The stylesheet as a string
  258. */
  259. public function getStylesheet(FlattenException $exception)
  260. {
  261. return <<<EOF
  262. .sf-reset { font: 11px Verdana, Arial, sans-serif; color: #333 }
  263. .sf-reset .clear { clear:both; height:0; font-size:0; line-height:0; }
  264. .sf-reset .clear_fix:after { display:block; height:0; clear:both; visibility:hidden; }
  265. .sf-reset .clear_fix { display:inline-block; }
  266. .sf-reset * html .clear_fix { height:1%; }
  267. .sf-reset .clear_fix { display:block; }
  268. .sf-reset, .sf-reset .block { margin: auto }
  269. .sf-reset abbr { border-bottom: 1px dotted #000; cursor: help; }
  270. .sf-reset p { font-size:14px; line-height:20px; color:#868686; padding-bottom:20px }
  271. .sf-reset strong { font-weight:bold; }
  272. .sf-reset a { color:#6c6159; cursor: default; }
  273. .sf-reset a img { border:none; }
  274. .sf-reset a:hover { text-decoration:underline; }
  275. .sf-reset em { font-style:italic; }
  276. .sf-reset h1, .sf-reset h2 { font: 20px Georgia, "Times New Roman", Times, serif }
  277. .sf-reset .exception_counter { background-color: #fff; color: #333; padding: 6px; float: left; margin-right: 10px; float: left; display: block; }
  278. .sf-reset .exception_title { margin-left: 3em; margin-bottom: 0.7em; display: block; }
  279. .sf-reset .exception_message { margin-left: 3em; display: block; }
  280. .sf-reset .traces li { font-size:12px; padding: 2px 4px; list-style-type:decimal; margin-left:20px; }
  281. .sf-reset .block { background-color:#FFFFFF; padding:10px 28px; margin-bottom:20px;
  282. -webkit-border-bottom-right-radius: 16px;
  283. -webkit-border-bottom-left-radius: 16px;
  284. -moz-border-radius-bottomright: 16px;
  285. -moz-border-radius-bottomleft: 16px;
  286. border-bottom-right-radius: 16px;
  287. border-bottom-left-radius: 16px;
  288. border-bottom:1px solid #ccc;
  289. border-right:1px solid #ccc;
  290. border-left:1px solid #ccc;
  291. }
  292. .sf-reset .block_exception { background-color:#ddd; color: #333; padding:20px;
  293. -webkit-border-top-left-radius: 16px;
  294. -webkit-border-top-right-radius: 16px;
  295. -moz-border-radius-topleft: 16px;
  296. -moz-border-radius-topright: 16px;
  297. border-top-left-radius: 16px;
  298. border-top-right-radius: 16px;
  299. border-top:1px solid #ccc;
  300. border-right:1px solid #ccc;
  301. border-left:1px solid #ccc;
  302. overflow: hidden;
  303. word-wrap: break-word;
  304. }
  305. .sf-reset a { background:none; color:#868686; text-decoration:none; }
  306. .sf-reset a:hover { background:none; color:#313131; text-decoration:underline; }
  307. .sf-reset ol { padding: 10px 0; }
  308. .sf-reset h1 { background-color:#FFFFFF; padding: 15px 28px; margin-bottom: 20px;
  309. -webkit-border-radius: 10px;
  310. -moz-border-radius: 10px;
  311. border-radius: 10px;
  312. border: 1px solid #ccc;
  313. }
  314. EOF;
  315. }
  316. private function decorate($content, $css)
  317. {
  318. return <<<EOF
  319. <!DOCTYPE html>
  320. <html>
  321. <head>
  322. <meta charset="{$this->charset}" />
  323. <meta name="robots" content="noindex,nofollow" />
  324. <style>
  325. /* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html */
  326. 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;}
  327. html { background: #eee; padding: 10px }
  328. img { border: 0; }
  329. #sf-resetcontent { width:970px; margin:0 auto; }
  330. $css
  331. </style>
  332. </head>
  333. <body>
  334. $content
  335. </body>
  336. </html>
  337. EOF;
  338. }
  339. private function formatClass($class)
  340. {
  341. $parts = explode('\\', $class);
  342. return sprintf('<abbr title="%s">%s</abbr>', $class, array_pop($parts));
  343. }
  344. private function formatPath($path, $line)
  345. {
  346. $path = $this->escapeHtml($path);
  347. $file = preg_match('#[^/\\\\]*$#', $path, $file) ? $file[0] : $path;
  348. if ($linkFormat = $this->fileLinkFormat) {
  349. $link = strtr($this->escapeHtml($linkFormat), array('%f' => $path, '%l' => (int) $line));
  350. return sprintf(' in <a href="%s" title="Go to source">%s line %d</a>', $link, $file, $line);
  351. }
  352. 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);
  353. }
  354. /**
  355. * Formats an array as a string.
  356. *
  357. * @param array $args The argument array
  358. *
  359. * @return string
  360. */
  361. private function formatArgs(array $args)
  362. {
  363. $result = array();
  364. foreach ($args as $key => $item) {
  365. if ('object' === $item[0]) {
  366. $formattedValue = sprintf('<em>object</em>(%s)', $this->formatClass($item[1]));
  367. } elseif ('array' === $item[0]) {
  368. $formattedValue = sprintf('<em>array</em>(%s)', is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
  369. } elseif ('string' === $item[0]) {
  370. $formattedValue = sprintf("'%s'", $this->escapeHtml($item[1]));
  371. } elseif ('null' === $item[0]) {
  372. $formattedValue = '<em>null</em>';
  373. } elseif ('boolean' === $item[0]) {
  374. $formattedValue = '<em>'.strtolower(var_export($item[1], true)).'</em>';
  375. } elseif ('resource' === $item[0]) {
  376. $formattedValue = '<em>resource</em>';
  377. } else {
  378. $formattedValue = str_replace("\n", '', var_export($this->escapeHtml((string) $item[1]), true));
  379. }
  380. $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
  381. }
  382. return implode(', ', $result);
  383. }
  384. /**
  385. * Returns an UTF-8 and HTML encoded string.
  386. *
  387. * @deprecated since version 2.7, to be removed in 3.0.
  388. */
  389. protected static function utf8Htmlize($str)
  390. {
  391. @trigger_error('The '.__METHOD__.' method is deprecated since version 2.7 and will be removed in 3.0.', E_USER_DEPRECATED);
  392. return htmlspecialchars($str, ENT_QUOTES | (PHP_VERSION_ID >= 50400 ? ENT_SUBSTITUTE : 0), 'UTF-8');
  393. }
  394. /**
  395. * HTML-encodes a string.
  396. */
  397. private function escapeHtml($str)
  398. {
  399. return htmlspecialchars($str, ENT_QUOTES | (PHP_VERSION_ID >= 50400 ? ENT_SUBSTITUTE : 0), $this->charset);
  400. }
  401. /**
  402. * @internal
  403. */
  404. public function catchOutput($buffer)
  405. {
  406. $this->caughtBuffer = $buffer;
  407. return '';
  408. }
  409. /**
  410. * @internal
  411. */
  412. public function cleanOutput($buffer)
  413. {
  414. if ($this->caughtLength) {
  415. // use substr_replace() instead of substr() for mbstring overloading resistance
  416. $cleanBuffer = substr_replace($buffer, '', 0, $this->caughtLength);
  417. if (isset($cleanBuffer[0])) {
  418. $buffer = $cleanBuffer;
  419. }
  420. }
  421. return $buffer;
  422. }
  423. }