sfException.class.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
  5. * (c) 2004-2006 Sean Kerr <sean@code-box.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * sfException is the base class for all symfony related exceptions and
  12. * provides an additional method for printing up a detailed view of an
  13. * exception.
  14. *
  15. * @package symfony
  16. * @subpackage exception
  17. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  18. * @author Sean Kerr <sean@code-box.org>
  19. * @version SVN: $Id: sfException.class.php 15223 2009-02-03 12:02:45Z fabien $
  20. */
  21. class sfException extends Exception
  22. {
  23. protected
  24. $wrappedException = null;
  25. /**
  26. * Wraps an Exception.
  27. *
  28. * @param Exception $e An Exception instance
  29. *
  30. * @return sfException An sfException instance that wraps the given Exception object
  31. */
  32. static public function createFromException(Exception $e)
  33. {
  34. $exception = new sfException(sprintf('Wrapped %s: %s', get_class($e), $e->getMessage()));
  35. $exception->setWrappedException($e);
  36. return $exception;
  37. }
  38. /**
  39. * Changes the wrapped exception.
  40. *
  41. * @param Exception $e An Exception instance
  42. */
  43. public function setWrappedException(Exception $e)
  44. {
  45. $this->wrappedException = $e;
  46. }
  47. /**
  48. * Prints the stack trace for this exception.
  49. */
  50. public function printStackTrace()
  51. {
  52. $exception = is_null($this->wrappedException) ? $this : $this->wrappedException;
  53. if (!sfConfig::get('sf_test'))
  54. {
  55. // log all exceptions in php log
  56. error_log($exception->getMessage());
  57. // clean current output buffer
  58. while (ob_get_level())
  59. {
  60. if (!ob_end_clean())
  61. {
  62. break;
  63. }
  64. }
  65. ob_start();
  66. header('HTTP/1.0 500 Internal Server Error');
  67. }
  68. try
  69. {
  70. $this->outputStackTrace($exception);
  71. }
  72. catch (Exception $e)
  73. {
  74. }
  75. if (!sfConfig::get('sf_test'))
  76. {
  77. exit(1);
  78. }
  79. }
  80. /**
  81. * Gets the stack trace for this exception.
  82. */
  83. static protected function outputStackTrace(Exception $exception)
  84. {
  85. $format = 'html';
  86. $code = '500';
  87. $text = 'Internal Server Error';
  88. if (class_exists('sfContext', false) && sfContext::hasInstance() && is_object($request = sfContext::getInstance()->getRequest()) && is_object($response = sfContext::getInstance()->getResponse()))
  89. {
  90. $dispatcher = sfContext::getInstance()->getEventDispatcher();
  91. if (sfConfig::get('sf_logging_enabled'))
  92. {
  93. $dispatcher->notify(new sfEvent($exception, 'application.log', array($exception->getMessage(), 'priority' => sfLogger::ERR)));
  94. }
  95. $event = $dispatcher->notifyUntil(new sfEvent($exception, 'application.throw_exception'));
  96. if ($event->isProcessed())
  97. {
  98. return;
  99. }
  100. if ($response->getStatusCode() < 300)
  101. {
  102. // status code has already been sent, but is included here for the purpose of testing
  103. $response->setStatusCode(500);
  104. }
  105. $response->setContentType('text/html');
  106. if (!sfConfig::get('sf_test'))
  107. {
  108. foreach ($response->getHttpHeaders() as $name => $value)
  109. {
  110. header($name.': '.$value);
  111. }
  112. }
  113. $code = $response->getStatusCode();
  114. $text = $response->getStatusText();
  115. $format = $request->getRequestFormat();
  116. if (!$format)
  117. {
  118. $format = 'html';
  119. }
  120. if ($mimeType = $request->getMimeType($format))
  121. {
  122. $response->setContentType($mimeType);
  123. }
  124. }
  125. else
  126. {
  127. // a backward compatible default
  128. if (!sfConfig::get('sf_test'))
  129. {
  130. header('Content-Type: text/html; charset='.sfConfig::get('sf_charset', 'utf-8'));
  131. }
  132. }
  133. // send an error 500 if not in debug mode
  134. if (!sfConfig::get('sf_debug'))
  135. {
  136. if ($template = self::getTemplatePathForError($format, false))
  137. {
  138. include $template;
  139. return;
  140. }
  141. }
  142. $message = is_null($exception->getMessage()) ? 'n/a' : $exception->getMessage();
  143. $name = get_class($exception);
  144. $traces = self::getTraces($exception, 'html' != $format || 0 == strncasecmp(PHP_SAPI, 'cli', 3) ? 'plain' : 'html');
  145. // dump main objects values
  146. $sf_settings = '';
  147. $settingsTable = $requestTable = $responseTable = $globalsTable = $userTable = '';
  148. if (class_exists('sfContext', false) && sfContext::hasInstance())
  149. {
  150. $context = sfContext::getInstance();
  151. $settingsTable = self::formatArrayAsHtml(sfDebug::settingsAsArray());
  152. $requestTable = self::formatArrayAsHtml(sfDebug::requestAsArray($context->getRequest()));
  153. $responseTable = self::formatArrayAsHtml(sfDebug::responseAsArray($context->getResponse()));
  154. $userTable = self::formatArrayAsHtml(sfDebug::userAsArray($context->getUser()));
  155. $globalsTable = self::formatArrayAsHtml(sfDebug::globalsAsArray());
  156. }
  157. if ($template = self::getTemplatePathForError($format, true))
  158. {
  159. include $template;
  160. return;
  161. }
  162. }
  163. /**
  164. * Returns the path for the template error message.
  165. *
  166. * @param string $format The request format
  167. * @param Boolean $debug Whether to return a template for the debug mode or not
  168. *
  169. * @return string|Boolean false if the template cannot be found for the given format,
  170. * the absolute path to the template otherwise
  171. */
  172. static public function getTemplatePathForError($format, $debug)
  173. {
  174. $templatePaths = array(
  175. sfConfig::get('sf_app_config_dir').'/error',
  176. sfConfig::get('sf_config_dir').'/error',
  177. dirname(__FILE__).'/data',
  178. );
  179. $template = sprintf('%s.%s.php', $debug ? 'exception' : 'error', $format);
  180. foreach ($templatePaths as $path)
  181. {
  182. if (!is_null($path) && is_readable($file = $path.'/'.$template))
  183. {
  184. return $file;
  185. }
  186. }
  187. return false;
  188. }
  189. /**
  190. * Returns an array of exception traces.
  191. *
  192. * @param Exception $exception An Exception implementation instance
  193. * @param string $format The trace format (plain or html)
  194. *
  195. * @return array An array of traces
  196. */
  197. static protected function getTraces($exception, $format = 'plain')
  198. {
  199. $traceData = $exception->getTrace();
  200. array_unshift($traceData, array(
  201. 'function' => '',
  202. 'file' => $exception->getFile() != null ? $exception->getFile() : 'n/a',
  203. 'line' => $exception->getLine() != null ? $exception->getLine() : 'n/a',
  204. 'args' => array(),
  205. ));
  206. $traces = array();
  207. if ($format == 'html')
  208. {
  209. $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 id="%s" style="display: %s">%s</ul>';
  210. }
  211. else
  212. {
  213. $lineFormat = 'at %s%s%s(%s) in %s line %s';
  214. }
  215. for ($i = 0, $count = count($traceData); $i < $count; $i++)
  216. {
  217. $line = isset($traceData[$i]['line']) ? $traceData[$i]['line'] : 'n/a';
  218. $file = isset($traceData[$i]['file']) ? $traceData[$i]['file'] : 'n/a';
  219. $shortFile = preg_replace(array('#^'.preg_quote(sfConfig::get('sf_root_dir')).'#', '#^'.preg_quote(realpath(sfConfig::get('sf_symfony_lib_dir'))).'#'), array('SF_ROOT_DIR', 'SF_SYMFONY_LIB_DIR'), $file);
  220. $args = isset($traceData[$i]['args']) ? $traceData[$i]['args'] : array();
  221. $traces[] = sprintf($lineFormat,
  222. (isset($traceData[$i]['class']) ? $traceData[$i]['class'] : ''),
  223. (isset($traceData[$i]['type']) ? $traceData[$i]['type'] : ''),
  224. $traceData[$i]['function'],
  225. self::formatArgs($args, false, $format),
  226. $shortFile,
  227. $line,
  228. 'trace_'.$i,
  229. 'trace_'.$i,
  230. $i == 0 ? 'block' : 'none',
  231. self::fileExcerpt($file, $line)
  232. );
  233. }
  234. return $traces;
  235. }
  236. /**
  237. * Returns an HTML version of an array as YAML.
  238. *
  239. * @param array $values The values array
  240. *
  241. * @return string An HTML string
  242. */
  243. static protected function formatArrayAsHtml($values)
  244. {
  245. return '<pre>'.htmlspecialchars(@sfYaml::Dump($values), ENT_QUOTES, sfConfig::get('sf_charset', 'UTF-8')).'</pre>';
  246. }
  247. /**
  248. * Returns an excerpt of a code file around the given line number.
  249. *
  250. * @param string $file A file path
  251. * @param int $line The selected line number
  252. *
  253. * @return string An HTML string
  254. */
  255. static protected function fileExcerpt($file, $line)
  256. {
  257. if (is_readable($file))
  258. {
  259. $content = preg_split('#<br />#', highlight_file($file, true));
  260. $lines = array();
  261. for ($i = max($line - 3, 1), $max = min($line + 3, count($content)); $i <= $max; $i++)
  262. {
  263. $lines[] = '<li'.($i == $line ? ' class="selected"' : '').'>'.$content[$i - 1].'</li>';
  264. }
  265. return '<ol start="'.max($line - 3, 1).'">'.implode("\n", $lines).'</ol>';
  266. }
  267. }
  268. /**
  269. * Formats an array as a string.
  270. *
  271. * @param array $args The argument array
  272. * @param boolean $single
  273. * @param string $format The format string (html or plain)
  274. *
  275. * @return string
  276. */
  277. static protected function formatArgs($args, $single = false, $format = 'html')
  278. {
  279. $result = array();
  280. $single and $args = array($args);
  281. foreach ($args as $key => $value)
  282. {
  283. if (is_object($value))
  284. {
  285. $result[] = ($format == 'html' ? '<em>object</em>' : 'object').'(\''.get_class($value).'\')';
  286. }
  287. else if (is_array($value))
  288. {
  289. $result[] = ($format == 'html' ? '<em>array</em>' : 'array').'('.self::formatArgs($value).')';
  290. }
  291. else if ($value === null)
  292. {
  293. $result[] = $format == 'html' ? '<em>null</em>' : 'null';
  294. }
  295. else if (!is_int($key))
  296. {
  297. $result[] = $format == 'html' ? "'$key' =&gt; '$value'" : "'$key' => '$value'";
  298. }
  299. else
  300. {
  301. $result[] = "'".$value."'";
  302. }
  303. }
  304. return implode(', ', $result);
  305. }
  306. }