ExceptionHandler.php 19 KB

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