PageRenderTime 20ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/servers/urlcatcher.org/htdocs/lib/vendor/symfony/lib/exception/sfException.class.php

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