No Description

ExceptionHandler.php 17KB

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