1. sfException.class.php
  2. /** * sfException is the base class for all symfony related exceptions and * provides an additional method for printing up a detailed view of an * exception. * * @package symfony * @subpackage exception * @author Fabien Potencier * @author Sean Kerr * @version SVN: $Id: sfException.class.php 23901 2009-11-14 13:33:03Z bschussek $ */
  3. class sfException extends Exception
  4. {
  5. protected
  6. $wrappedException = null;
  7. static protected
  8. $lastException = null;
  9. /**
  10. * Wraps an Exception.
  11. *
  12. * @param Exception $e An Exception instance
  13. *
  14. * @return sfException An sfException instance that wraps the given Exception object
  15. */
  16. static public function createFromException(Exception $e)
  17. {
  18. $exception = new sfException(sprintf('Wrapped %s: %s', get_class($e), $e->getMessage()));
  19. $exception->setWrappedException($e);
  20. self::$lastException = $e;
  21. return $exception;
  22. }
  23. /**
  24. * Sets the wrapped exception.
  25. *
  26. * @param Exception $e An Exception instance
  27. */
  28. public function setWrappedException(Exception $e)
  29. {
  30. $this->wrappedException = $e;
  31. self::$lastException = $e;
  32. }
  33. /**
  34. * Gets the last wrapped exception.
  35. *
  36. * @return Exception An Exception instance
  37. */
  38. static public function getLastException()
  39. {
  40. return self::$lastException;
  41. }
  42. /**
  43. * Clears the $lastException property (added for #6342)
  44. */
  45. static public function clearLastException()
  46. {
  47. self::$lastException = null;
  48. }
  49. /**
  50. * Prints the stack trace for this exception.
  51. */
  52. public function printStackTrace()
  53. {
  54. if (null === $this->wrappedException)
  55. {
  56. $this->setWrappedException($this);
  57. }
  58. $exception = $this->wrappedException;
  59. if (!sfConfig::get('sf_test'))
  60. {
  61. // log all exceptions in php log
  62. error_log($exception->getMessage());
  63. // clean current output buffer
  64. while (ob_get_level())
  65. {
  66. if (!ob_end_clean())
  67. {
  68. break;
  69. }
  70. }
  71. ob_start(sfConfig::get('sf_compressed') ? 'ob_gzhandler' : '');
  72. header('HTTP/1.0 500 Internal Server Error');
  73. }
  74. try
  75. {
  76. $this->outputStackTrace($exception);
  77. }
  78. catch (Exception $e)
  79. {
  80. }
  81. if (!sfConfig::get('sf_test'))
  82. {
  83. exit(1);
  84. }
  85. }
  86. /**
  87. * Gets the stack trace for this exception.
  88. */
  89. static protected function outputStackTrace(Exception $exception)
  90. {
  91. $format = 'html';
  92. $code = '500';
  93. $text = 'Internal Server Error';
  94. $response = null;
  95. if (class_exists('sfContext', false) && sfContext::hasInstance() && is_object($request = sfContext::getInstance()->getRequest()) && is_object($response = sfContext::getInstance()->getResponse()))
  96. {
  97. $dispatcher = sfContext::getInstance()->getEventDispatcher();
  98. if (sfConfig::get('sf_logging_enabled'))
  99. {
  100. $dispatcher->notify(new sfEvent($exception, 'application.log', array($exception->getMessage(), 'priority' => sfLogger::ERR)));
  101. }
  102. $event = $dispatcher->notifyUntil(new sfEvent($exception, 'application.throw_exception'));
  103. if ($event->isProcessed())
  104. {
  105. return;
  106. }
  107. if ($response->getStatusCode() < 300)
  108. {
  109. // status code has already been sent, but is included here for the purpose of testing
  110. $response->setStatusCode(500);
  111. }
  112. $response->setContentType('text/html');
  113. if (!sfConfig::get('sf_test'))
  114. {
  115. foreach ($response->getHttpHeaders() as $name => $value)
  116. {
  117. header($name.': '.$value);
  118. }
  119. }
  120. $code = $response->getStatusCode();
  121. $text = $response->getStatusText();
  122. $format = $request->getRequestFormat();
  123. if (!$format)
  124. {
  125. $format = 'html';
  126. }
  127. if ($mimeType = $request->getMimeType($format))
  128. {
  129. $response->setContentType($mimeType);
  130. }
  131. }
  132. else
  133. {
  134. // a backward compatible default
  135. if (!sfConfig::get('sf_test'))
  136. {
  137. header('Content-Type: text/html; charset='.sfConfig::get('sf_charset', 'utf-8'));
  138. }
  139. }
  140. // send an error 500 if not in debug mode
  141. if (!sfConfig::get('sf_debug'))
  142. {
  143. if ($template = self::getTemplatePathForError($format, false))
  144. {
  145. include $template;
  146. return;
  147. }
  148. }
  149. // when using CLI, we force the format to be TXT
  150. if (0 == strncasecmp(PHP_SAPI, 'cli', 3))
  151. {
  152. $format = 'txt';
  153. }
  154. $message = null === $exception->getMessage() ? 'n/a' : $exception->getMessage();
  155. $name = get_class($exception);
  156. $traces = self::getTraces($exception, $format);
  157. // dump main objects values
  158. $sf_settings = '';
  159. $settingsTable = $requestTable = $responseTable = $globalsTable = $userTable = '';
  160. if (class_exists('sfContext', false) && sfContext::hasInstance())
  161. {
  162. $context = sfContext::getInstance();
  163. $settingsTable = self::formatArrayAsHtml(sfDebug::settingsAsArray());
  164. $requestTable = self::formatArrayAsHtml(sfDebug::requestAsArray($context->getRequest()));
  165. $responseTable = self::formatArrayAsHtml(sfDebug::responseAsArray($context->getResponse()));
  166. $userTable = self::formatArrayAsHtml(sfDebug::userAsArray($context->getUser()));
  167. $globalsTable = self::formatArrayAsHtml(sfDebug::globalsAsArray());
  168. }
  169. if (isset($response) && $response)
  170. {
  171. $response->sendHttpHeaders();
  172. }
  173. if ($template = self::getTemplatePathForError($format, true))
  174. {
  175. if (isset($dispatcher))
  176. {
  177. ob_start();
  178. include $template;
  179. $content = ob_get_clean();
  180. $event = $dispatcher->filter(new sfEvent($response, 'response.filter_content'), $content);
  181. echo $event->getReturnValue();
  182. }
  183. else
  184. {
  185. include $template;
  186. }
  187. return;
  188. }
  189. }
  190. /**
  191. * Returns the path for the template error message.
  192. *
  193. * @param string $format The request format
  194. * @param Boolean $debug Whether to return a template for the debug mode or not
  195. *
  196. * @return string|Boolean false if the template cannot be found for the given format,
  197. * the absolute path to the template otherwise
  198. */
  199. static public function getTemplatePathForError($format, $debug)
  200. {
  201. $templatePaths = array(
  202. sfConfig::get('sf_app_config_dir').'/error',
  203. sfConfig::get('sf_config_dir').'/error',
  204. dirname(__FILE__).'/data',
  205. );
  206. $template = sprintf('%s.%s.php', $debug ? 'exception' : 'error', $format);
  207. foreach ($templatePaths as $path)
  208. {
  209. if (null !== $path && is_readable($file = $path.'/'.$template))
  210. {
  211. return $file;
  212. }
  213. }
  214. return false;
  215. }
  216. /**
  217. * Returns an array of exception traces.
  218. *
  219. * @param Exception $exception An Exception implementation instance
  220. * @param string $format The trace format (txt or html)
  221. *
  222. * @return array An array of traces
  223. */
  224. static protected function getTraces($exception, $format = 'txt')
  225. {
  226. $traceData = $exception->getTrace();
  227. array_unshift($traceData, array(
  228. 'function' => '',
  229. 'file' => $exception->getFile() != null ? $exception->getFile() : null,
  230. 'line' => $exception->getLine() != null ? $exception->getLine() : null,
  231. 'args' => array(),
  232. ));
  233. $traces = array();
  234. if ($format == 'html')
  235. {
  236. $lineFormat = 'at <strong>%s%s%s</strong>(%s)<br />in <em>%s</em> line %s <a href="#" onclick="toggle(\'%s\'); return false;">...</a><br /><ul class="code" id="%s" style="display: %s">%s</ul>';
  237. }
  238. else
  239. {
  240. $lineFormat = 'at %s%s%s(%s) in %s line %s';
  241. }
  242. for ($i = 0, $count = count($traceData); $i < $count; $i++)
  243. {
  244. $line = isset($traceData[$i]['line']) ? $traceData[$i]['line'] : null;
  245. $file = isset($traceData[$i]['file']) ? $traceData[$i]['file'] : null;
  246. $args = isset($traceData[$i]['args']) ? $traceData[$i]['args'] : array();
  247. $traces[] = sprintf($lineFormat,
  248. (isset($traceData[$i]['class']) ? $traceData[$i]['class'] : ''),
  249. (isset($traceData[$i]['type']) ? $traceData[$i]['type'] : ''),
  250. $traceData[$i]['function'],
  251. self::formatArgs($args, false, $format),
  252. self::formatFile($file, $line, $format, null === $file ? 'n/a' : sfDebug::shortenFilePath($file)),
  253. null === $line ? 'n/a' : $line,
  254. 'trace_'.$i,
  255. 'trace_'.$i,
  256. $i == 0 ? 'block' : 'none',
  257. self::fileExcerpt($file, $line)
  258. );
  259. }
  260. return $traces;
  261. }
  262. /**
  263. * Returns an HTML version of an array as YAML.
  264. *
  265. * @param array $values The values array
  266. *
  267. * @return string An HTML string
  268. */
  269. static protected function formatArrayAsHtml($values)
  270. {
  271. return '<pre>'.self::escape(@sfYaml::dump($values)).'</pre>';
  272. }
  273. /**
  274. * Returns an excerpt of a code file around the given line number.
  275. *
  276. * @param string $file A file path
  277. * @param int $line The selected line number
  278. *
  279. * @return string An HTML string
  280. */
  281. static protected function fileExcerpt($file, $line)
  282. {
  283. if (is_readable($file))
  284. {
  285. $content = preg_split('#<br />#', highlight_file($file, true));
  286. $lines = array();
  287. for ($i = max($line - 3, 1), $max = min($line + 3, count($content)); $i <= $max; $i++)
  288. {
  289. $lines[] = '<li'.($i == $line ? ' class="selected"' : '').'>'.$content[$i - 1].'</li>';
  290. }
  291. return '<ol start="'.max($line - 3, 1).'">'.implode("\n", $lines).'</ol>';
  292. }
  293. }
  294. /**
  295. * Formats an array as a string.
  296. *
  297. * @param array $args The argument array
  298. * @param boolean $single
  299. * @param string $format The format string (html or txt)
  300. *
  301. * @return string
  302. */
  303. static protected function formatArgs($args, $single = false, $format = 'html')
  304. {
  305. $result = array();
  306. $single and $args = array($args);
  307. foreach ($args as $key => $value)
  308. {
  309. if (is_object($value))
  310. {
  311. $formattedValue = ($format == 'html' ? '<em>object</em>' : 'object').sprintf("('%s')", get_class($value));
  312. }
  313. else if (is_array($value))
  314. {
  315. $formattedValue = ($format == 'html' ? '<em>array</em>' : 'array').sprintf("(%s)", self::formatArgs($value));
  316. }
  317. else if (is_string($value))
  318. {
  319. $formattedValue = ($format == 'html' ? sprintf("'%s'", self::escape($value)) : "'$value'");
  320. }
  321. else if (null === $value)
  322. {
  323. $formattedValue = ($format == 'html' ? '<em>null</em>' : 'null');
  324. }
  325. else
  326. {
  327. $formattedValue = $value;
  328. }
  329. $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", self::escape($key), $formattedValue);
  330. }
  331. return implode(', ', $result);
  332. }
  333. /**
  334. * Formats a file path.
  335. *
  336. * @param string $file An absolute file path
  337. * @param integer $line The line number
  338. * @param string $format The output format (txt or html)
  339. * @param string $text Use this text for the link rather than the file path
  340. *
  341. * @return string
  342. */
  343. static protected function formatFile($file, $line, $format = 'html', $text = null)
  344. {
  345. if (null === $text)
  346. {
  347. $text = $file;
  348. }
  349. if ('html' == $format && $file && $line && $linkFormat = sfConfig::get('sf_file_link_format', ini_get('xdebug.file_link_format')))
  350. {
  351. $link = strtr($linkFormat, array('%f' => $file, '%l' => $line));
  352. $text = sprintf('<a href="%s" title="Click to open this file" class="file_link">%s</a>', $link, $text);
  353. }
  354. return $text;
  355. }
  356. /**
  357. * Escapes a string value with html entities
  358. *
  359. * @param string $value
  360. *
  361. * @return string
  362. */
  363. static protected function escape($value)
  364. {
  365. if (!is_string($value))
  366. {
  367. return $value;
  368. }
  369. return htmlspecialchars($value, ENT_QUOTES, sfConfig::get('sf_charset', 'UTF-8'));
  370. }
  371. }

Debug toolbar