PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

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

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