Base for a static organization website

ErrorHandler.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <?php
  2. /**
  3. * ErrorHandler class
  4. *
  5. * Provides Error Capturing for Framework errors.
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.Error
  17. * @since CakePHP(tm) v 0.10.5.1732
  18. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. App::uses('Debugger', 'Utility');
  21. App::uses('CakeLog', 'Log');
  22. App::uses('ExceptionRenderer', 'Error');
  23. App::uses('Router', 'Routing');
  24. /**
  25. * Error Handler provides basic error and exception handling for your application. It captures and
  26. * handles all unhandled exceptions and errors. Displays helpful framework errors when debug > 1.
  27. *
  28. * ### Uncaught exceptions
  29. *
  30. * When debug < 1 a CakeException will render 404 or 500 errors. If an uncaught exception is thrown
  31. * and it is a type that ErrorHandler does not know about it will be treated as a 500 error.
  32. *
  33. * ### Implementing application specific exception handling
  34. *
  35. * You can implement application specific exception handling in one of a few ways. Each approach
  36. * gives you different amounts of control over the exception handling process.
  37. *
  38. * - Set Configure::write('Exception.handler', 'YourClass::yourMethod');
  39. * - Create AppController::appError();
  40. * - Set Configure::write('Exception.renderer', 'YourClass');
  41. *
  42. * #### Create your own Exception handler with `Exception.handler`
  43. *
  44. * This gives you full control over the exception handling process. The class you choose should be
  45. * loaded in your app/Config/bootstrap.php, so its available to handle any exceptions. You can
  46. * define the handler as any callback type. Using Exception.handler overrides all other exception
  47. * handling settings and logic.
  48. *
  49. * #### Using `AppController::appError();`
  50. *
  51. * This controller method is called instead of the default exception rendering. It receives the
  52. * thrown exception as its only argument. You should implement your error handling in that method.
  53. * Using AppController::appError(), will supersede any configuration for Exception.renderer.
  54. *
  55. * #### Using a custom renderer with `Exception.renderer`
  56. *
  57. * If you don't want to take control of the exception handling, but want to change how exceptions are
  58. * rendered you can use `Exception.renderer` to choose a class to render exception pages. By default
  59. * `ExceptionRenderer` is used. Your custom exception renderer class should be placed in app/Lib/Error.
  60. *
  61. * Your custom renderer should expect an exception in its constructor, and implement a render method.
  62. * Failing to do so will cause additional errors.
  63. *
  64. * #### Logging exceptions
  65. *
  66. * Using the built-in exception handling, you can log all the exceptions
  67. * that are dealt with by ErrorHandler by setting `Exception.log` to true in your core.php.
  68. * Enabling this will log every exception to CakeLog and the configured loggers.
  69. *
  70. * ### PHP errors
  71. *
  72. * Error handler also provides the built in features for handling php errors (trigger_error).
  73. * While in debug mode, errors will be output to the screen using debugger. While in production mode,
  74. * errors will be logged to CakeLog. You can control which errors are logged by setting
  75. * `Error.level` in your core.php.
  76. *
  77. * #### Logging errors
  78. *
  79. * When ErrorHandler is used for handling errors, you can enable error logging by setting `Error.log` to true.
  80. * This will log all errors to the configured log handlers.
  81. *
  82. * #### Controlling what errors are logged/displayed
  83. *
  84. * You can control which errors are logged / displayed by ErrorHandler by setting `Error.level`. Setting this
  85. * to one or a combination of a few of the E_* constants will only enable the specified errors.
  86. *
  87. * e.g. `Configure::write('Error.level', E_ALL & ~E_NOTICE);`
  88. *
  89. * Would enable handling for all non Notice errors.
  90. *
  91. * @package Cake.Error
  92. * @see ExceptionRenderer for more information on how to customize exception rendering.
  93. */
  94. class ErrorHandler {
  95. /**
  96. * Whether to give up rendering an exception, if the renderer itself is
  97. * throwing exceptions.
  98. *
  99. * @var bool
  100. */
  101. protected static $_bailExceptionRendering = false;
  102. /**
  103. * Set as the default exception handler by the CakePHP bootstrap process.
  104. *
  105. * This will either use custom exception renderer class if configured,
  106. * or use the default ExceptionRenderer.
  107. *
  108. * @param Exception $exception The exception to render.
  109. * @return void
  110. * @see http://php.net/manual/en/function.set-exception-handler.php
  111. */
  112. public static function handleException(Exception $exception) {
  113. $config = Configure::read('Exception');
  114. static::_log($exception, $config);
  115. $renderer = isset($config['renderer']) ? $config['renderer'] : 'ExceptionRenderer';
  116. if ($renderer !== 'ExceptionRenderer') {
  117. list($plugin, $renderer) = pluginSplit($renderer, true);
  118. App::uses($renderer, $plugin . 'Error');
  119. }
  120. try {
  121. $error = new $renderer($exception);
  122. $error->render();
  123. } catch (Exception $e) {
  124. set_error_handler(Configure::read('Error.handler')); // Should be using configured ErrorHandler
  125. Configure::write('Error.trace', false); // trace is useless here since it's internal
  126. $message = sprintf("[%s] %s\n%s", // Keeping same message format
  127. get_class($e),
  128. $e->getMessage(),
  129. $e->getTraceAsString()
  130. );
  131. static::$_bailExceptionRendering = true;
  132. trigger_error($message, E_USER_ERROR);
  133. }
  134. }
  135. /**
  136. * Generates a formatted error message
  137. *
  138. * @param Exception $exception Exception instance
  139. * @return string Formatted message
  140. */
  141. protected static function _getMessage($exception) {
  142. $message = sprintf("[%s] %s",
  143. get_class($exception),
  144. $exception->getMessage()
  145. );
  146. if (method_exists($exception, 'getAttributes')) {
  147. $attributes = $exception->getAttributes();
  148. if ($attributes) {
  149. $message .= "\nException Attributes: " . var_export($exception->getAttributes(), true);
  150. }
  151. }
  152. if (PHP_SAPI !== 'cli') {
  153. $request = Router::getRequest();
  154. if ($request) {
  155. $message .= "\nRequest URL: " . $request->here();
  156. }
  157. }
  158. $message .= "\nStack Trace:\n" . $exception->getTraceAsString();
  159. return $message;
  160. }
  161. /**
  162. * Handles exception logging
  163. *
  164. * @param Exception $exception The exception to render.
  165. * @param array $config An array of configuration for logging.
  166. * @return bool
  167. */
  168. protected static function _log(Exception $exception, $config) {
  169. if (empty($config['log'])) {
  170. return false;
  171. }
  172. if (!empty($config['skipLog'])) {
  173. foreach ((array)$config['skipLog'] as $class) {
  174. if ($exception instanceof $class) {
  175. return false;
  176. }
  177. }
  178. }
  179. return CakeLog::write(LOG_ERR, static::_getMessage($exception));
  180. }
  181. /**
  182. * Set as the default error handler by CakePHP. Use Configure::write('Error.handler', $callback), to use your own
  183. * error handling methods. This function will use Debugger to display errors when debug > 0. And
  184. * will log errors to CakeLog, when debug == 0.
  185. *
  186. * You can use Configure::write('Error.level', $value); to set what type of errors will be handled here.
  187. * Stack traces for errors can be enabled with Configure::write('Error.trace', true);
  188. *
  189. * @param int $code Code of error
  190. * @param string $description Error description
  191. * @param string $file File on which error occurred
  192. * @param int $line Line that triggered the error
  193. * @param array $context Context
  194. * @return bool true if error was handled
  195. */
  196. public static function handleError($code, $description, $file = null, $line = null, $context = null) {
  197. if (error_reporting() === 0) {
  198. return false;
  199. }
  200. $errorConfig = Configure::read('Error');
  201. list($error, $log) = static::mapErrorCode($code);
  202. if ($log === LOG_ERR) {
  203. return static::handleFatalError($code, $description, $file, $line);
  204. }
  205. $debug = Configure::read('debug');
  206. if ($debug) {
  207. $data = array(
  208. 'level' => $log,
  209. 'code' => $code,
  210. 'error' => $error,
  211. 'description' => $description,
  212. 'file' => $file,
  213. 'line' => $line,
  214. 'context' => $context,
  215. 'start' => 2,
  216. 'path' => Debugger::trimPath($file)
  217. );
  218. return Debugger::getInstance()->outputError($data);
  219. }
  220. $message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
  221. if (!empty($errorConfig['trace'])) {
  222. // https://bugs.php.net/bug.php?id=65322
  223. if (version_compare(PHP_VERSION, '5.4.21', '<')) {
  224. if (!class_exists('Debugger')) {
  225. App::load('Debugger');
  226. }
  227. if (!class_exists('CakeText')) {
  228. App::uses('CakeText', 'Utility');
  229. App::load('CakeText');
  230. }
  231. }
  232. $trace = Debugger::trace(array('start' => 1, 'format' => 'log'));
  233. $message .= "\nTrace:\n" . $trace . "\n";
  234. }
  235. return CakeLog::write($log, $message);
  236. }
  237. /**
  238. * Generate an error page when some fatal error happens.
  239. *
  240. * @param int $code Code of error
  241. * @param string $description Error description
  242. * @param string $file File on which error occurred
  243. * @param int $line Line that triggered the error
  244. * @return bool
  245. * @throws FatalErrorException If the Exception renderer threw an exception during rendering, and debug > 0.
  246. * @throws InternalErrorException If the Exception renderer threw an exception during rendering, and debug is 0.
  247. */
  248. public static function handleFatalError($code, $description, $file, $line) {
  249. $logMessage = 'Fatal Error (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
  250. CakeLog::write(LOG_ERR, $logMessage);
  251. $exceptionHandler = Configure::read('Exception.handler');
  252. if (!is_callable($exceptionHandler)) {
  253. return false;
  254. }
  255. if (ob_get_level()) {
  256. ob_end_clean();
  257. }
  258. if (Configure::read('debug')) {
  259. $exception = new FatalErrorException($description, 500, $file, $line);
  260. } else {
  261. $exception = new InternalErrorException();
  262. }
  263. if (static::$_bailExceptionRendering) {
  264. static::$_bailExceptionRendering = false;
  265. throw $exception;
  266. }
  267. call_user_func($exceptionHandler, $exception);
  268. return false;
  269. }
  270. /**
  271. * Map an error code into an Error word, and log location.
  272. *
  273. * @param int $code Error code to map
  274. * @return array Array of error word, and log location.
  275. */
  276. public static function mapErrorCode($code) {
  277. $error = $log = null;
  278. switch ($code) {
  279. case E_PARSE:
  280. case E_ERROR:
  281. case E_CORE_ERROR:
  282. case E_COMPILE_ERROR:
  283. case E_USER_ERROR:
  284. $error = 'Fatal Error';
  285. $log = LOG_ERR;
  286. break;
  287. case E_WARNING:
  288. case E_USER_WARNING:
  289. case E_COMPILE_WARNING:
  290. case E_RECOVERABLE_ERROR:
  291. $error = 'Warning';
  292. $log = LOG_WARNING;
  293. break;
  294. case E_NOTICE:
  295. case E_USER_NOTICE:
  296. $error = 'Notice';
  297. $log = LOG_NOTICE;
  298. break;
  299. case E_STRICT:
  300. $error = 'Strict';
  301. $log = LOG_NOTICE;
  302. break;
  303. case E_DEPRECATED:
  304. case E_USER_DEPRECATED:
  305. $error = 'Deprecated';
  306. $log = LOG_NOTICE;
  307. break;
  308. }
  309. return array($error, $log);
  310. }
  311. }