Drupal investigation

ExceptionHandler.php 19KB

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