PageRenderTime 51ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/vendor/symfony/lib/exception/sfException.class.php

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