* * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Debug; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Debug\Exception\FlattenException; use Symfony\Component\Debug\Exception\OutOfMemoryException; if (!defined('ENT_SUBSTITUTE')) { define('ENT_SUBSTITUTE', 8); } /** * ExceptionHandler converts an exception to a Response object. * * It is mostly useful in debug mode to replace the default PHP/XDebug * output with something prettier and more useful. * * As this class is mainly used during Kernel boot, where nothing is yet * available, the Response content is always HTML. * * @author Fabien Potencier * @author Nicolas Grekas */ class ExceptionHandler { private $debug; private $handler; private $caughtBuffer; private $caughtLength; public function __construct($debug = true) { $this->debug = $debug; } /** * Registers the exception handler. * * @param bool $debug * * @return ExceptionHandler The registered exception handler */ public static function register($debug = true) { $handler = new static($debug); $prev = set_exception_handler(array($handler, 'handle')); if (is_array($prev) && $prev[0] instanceof ErrorHandler) { restore_exception_handler(); $prev[0]->setExceptionHandler(array($handler, 'handle')); } return $handler; } /** * Sets a user exception handler. * * @param callable $handler An handler that will be called on Exception * * @return callable|null The previous exception handler if any */ public function setHandler($handler) { if (null !== $handler && !is_callable($handler)) { throw new \LogicException('The exception handler must be a valid PHP callable.'); } $old = $this->handler; $this->handler = $handler; return $old; } /** * Sends a response for the given Exception. * * To be as fail-safe as possible, the exception is first handled * by our simple exception handler, then by the user exception handler. * The latter takes precedence and any output from the former is cancelled, * if and only if nothing bad happens in this handling path. */ public function handle(\Exception $exception) { if (null === $this->handler || $exception instanceof OutOfMemoryException) { $this->failSafeHandle($exception); return; } $caughtLength = $this->caughtLength = 0; ob_start(array($this, 'catchOutput')); $this->failSafeHandle($exception); while (null === $this->caughtBuffer && ob_end_flush()) { // Empty loop, everything is in the condition } if (isset($this->caughtBuffer[0])) { ob_start(array($this, 'cleanOutput')); echo $this->caughtBuffer; $caughtLength = ob_get_length(); } $this->caughtBuffer = null; try { call_user_func($this->handler, $exception); $this->caughtLength = $caughtLength; } catch (\Exception $e) { if (!$caughtLength) { // All handlers failed. Let PHP handle that now. throw $exception; } } } /** * Sends a response for the given Exception. * * If you have the Symfony HttpFoundation component installed, * this method will use it to create and send the response. If not, * it will fallback to plain PHP functions. * * @see sendPhpResponse * @see createResponse */ private function failSafeHandle(\Exception $exception) { if (class_exists('Symfony\Component\HttpFoundation\Response', false)) { $response = $this->createResponse($exception); $response->sendHeaders(); $response->sendContent(); } else { $this->sendPhpResponse($exception); } } /** * Sends the error associated with the given Exception as a plain PHP response. * * This method uses plain PHP functions like header() and echo to output * the response. * * @param \Exception|FlattenException $exception An \Exception instance */ public function sendPhpResponse($exception) { if (!$exception instanceof FlattenException) { $exception = FlattenException::create($exception); } if (!headers_sent()) { header(sprintf('HTTP/1.0 %s', $exception->getStatusCode())); foreach ($exception->getHeaders() as $name => $value) { header($name.': '.$value, false); } } echo $this->decorate($this->getContent($exception), $this->getStylesheet($exception)); } /** * Creates the error Response associated with the given Exception. * * @param \Exception|FlattenException $exception An \Exception instance * * @return Response A Response instance */ public function createResponse($exception) { if (!$exception instanceof FlattenException) { $exception = FlattenException::create($exception); } return new Response($this->decorate($this->getContent($exception), $this->getStylesheet($exception)), $exception->getStatusCode(), $exception->getHeaders()); } /** * Gets the HTML content associated with the given exception. * * @param FlattenException $exception A FlattenException instance * * @return string The content as a string */ public function getContent(FlattenException $exception) { switch ($exception->getStatusCode()) { case 404: $title = 'Sorry, the page you are looking for could not be found.'; break; default: $title = 'Whoops, looks like something went wrong.'; } $content = ''; if ($this->debug) { try { $count = count($exception->getAllPrevious()); $total = $count + 1; foreach ($exception->toArray() as $position => $e) { $ind = $count - $position + 1; $class = $this->formatClass($e['class']); $message = nl2br(self::utf8Htmlize($e['message'])); $content .= sprintf(<< %d/%d %s%s: %s
    EOF , $ind, $total, $class, $this->formatPath($e['trace'][0]['file'], $e['trace'][0]['line']), $message); foreach ($e['trace'] as $trace) { $content .= '
  1. '; if ($trace['function']) { $content .= sprintf('at %s%s%s(%s)', $this->formatClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args'])); } if (isset($trace['file']) && isset($trace['line'])) { $content .= $this->formatPath($trace['file'], $trace['line']); } $content .= "
  2. \n"; } $content .= "
\n
\n"; } } catch (\Exception $e) { // something nasty happened and we cannot throw an exception anymore if ($this->debug) { $title = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($exception), $exception->getMessage()); } else { $title = 'Whoops, looks like something went wrong.'; } } } return <<

$title

$content EOF; } /** * Gets the stylesheet associated with the given exception. * * @param FlattenException $exception A FlattenException instance * * @return string The stylesheet as a string */ public function getStylesheet(FlattenException $exception) { return << $content EOF; } private function formatClass($class) { $parts = explode('\\', $class); return sprintf("%s", $class, array_pop($parts)); } private function formatPath($path, $line) { $path = self::utf8Htmlize($path); $file = preg_match('#[^/\\\\]*$#', $path, $file) ? $file[0] : $path; if ($linkFormat = ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format')) { $link = str_replace(array('%f', '%l'), array($path, $line), $linkFormat); return sprintf(' in %s line %d', $link, $file, $line); } return sprintf(' in %s line %d', $path, $file, $line); } /** * Formats an array as a string. * * @param array $args The argument array * * @return string */ private function formatArgs(array $args) { $result = array(); foreach ($args as $key => $item) { if ('object' === $item[0]) { $formattedValue = sprintf("object(%s)", $this->formatClass($item[1])); } elseif ('array' === $item[0]) { $formattedValue = sprintf("array(%s)", is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]); } elseif ('string' === $item[0]) { $formattedValue = sprintf("'%s'", self::utf8Htmlize($item[1])); } elseif ('null' === $item[0]) { $formattedValue = 'null'; } elseif ('boolean' === $item[0]) { $formattedValue = ''.strtolower(var_export($item[1], true)).''; } elseif ('resource' === $item[0]) { $formattedValue = 'resource'; } else { $formattedValue = str_replace("\n", '', var_export(self::utf8Htmlize((string) $item[1]), true)); } $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue); } return implode(', ', $result); } /** * Returns an UTF-8 and HTML encoded string */ protected static function utf8Htmlize($str) { if (!preg_match('//u', $str) && function_exists('iconv')) { set_error_handler('var_dump', 0); $charset = ini_get('default_charset'); if ('UTF-8' === $charset || $str !== @iconv($charset, $charset, $str)) { $charset = 'CP1252'; } restore_error_handler(); $str = iconv($charset, 'UTF-8', $str); } return htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); } /** * @internal */ public function catchOutput($buffer) { $this->caughtBuffer = $buffer; return ''; } /** * @internal */ public function cleanOutput($buffer) { if ($this->caughtLength) { // use substr_replace() instead of substr() for mbstring overloading resistance $cleanBuffer = substr_replace($buffer, '', 0, $this->caughtLength); if (isset($cleanBuffer[0])) { $buffer = $cleanBuffer; } } return $buffer; } }