PageRenderTime 34ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Error/ErrorHandler.php

https://gitlab.com/grlopez90/servipro
PHP | 345 lines | 165 code | 20 blank | 160 comment | 21 complexity | 626a569f8e80dea706ff804ed938528f MD5 | raw file
  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|ParseError $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) {
  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|ParseError $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, $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. list($error, $log) = static::mapErrorCode($code);
  201. if ($log === LOG_ERR) {
  202. return static::handleFatalError($code, $description, $file, $line);
  203. }
  204. $debug = Configure::read('debug');
  205. if ($debug) {
  206. $data = array(
  207. 'level' => $log,
  208. 'code' => $code,
  209. 'error' => $error,
  210. 'description' => $description,
  211. 'file' => $file,
  212. 'line' => $line,
  213. 'context' => $context,
  214. 'start' => 2,
  215. 'path' => Debugger::trimPath($file)
  216. );
  217. return Debugger::getInstance()->outputError($data);
  218. }
  219. $message = static::_getErrorMessage($error, $code, $description, $file, $line);
  220. return CakeLog::write($log, $message);
  221. }
  222. /**
  223. * Generate an error page when some fatal error happens.
  224. *
  225. * @param int $code Code of error
  226. * @param string $description Error description
  227. * @param string $file File on which error occurred
  228. * @param int $line Line that triggered the error
  229. * @return bool
  230. * @throws FatalErrorException If the Exception renderer threw an exception during rendering, and debug > 0.
  231. * @throws InternalErrorException If the Exception renderer threw an exception during rendering, and debug is 0.
  232. */
  233. public static function handleFatalError($code, $description, $file, $line) {
  234. $logMessage = 'Fatal Error (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
  235. CakeLog::write(LOG_ERR, $logMessage);
  236. $exceptionHandler = Configure::read('Exception.handler');
  237. if (!is_callable($exceptionHandler)) {
  238. return false;
  239. }
  240. if (ob_get_level()) {
  241. ob_end_clean();
  242. }
  243. if (Configure::read('debug')) {
  244. $exception = new FatalErrorException($description, 500, $file, $line);
  245. } else {
  246. $exception = new InternalErrorException();
  247. }
  248. if (static::$_bailExceptionRendering) {
  249. static::$_bailExceptionRendering = false;
  250. throw $exception;
  251. }
  252. call_user_func($exceptionHandler, $exception);
  253. return false;
  254. }
  255. /**
  256. * Map an error code into an Error word, and log location.
  257. *
  258. * @param int $code Error code to map
  259. * @return array Array of error word, and log location.
  260. */
  261. public static function mapErrorCode($code) {
  262. $error = $log = null;
  263. switch ($code) {
  264. case E_PARSE:
  265. case E_ERROR:
  266. case E_CORE_ERROR:
  267. case E_COMPILE_ERROR:
  268. case E_USER_ERROR:
  269. $error = 'Fatal Error';
  270. $log = LOG_ERR;
  271. break;
  272. case E_WARNING:
  273. case E_USER_WARNING:
  274. case E_COMPILE_WARNING:
  275. case E_RECOVERABLE_ERROR:
  276. $error = 'Warning';
  277. $log = LOG_WARNING;
  278. break;
  279. case E_NOTICE:
  280. case E_USER_NOTICE:
  281. $error = 'Notice';
  282. $log = LOG_NOTICE;
  283. break;
  284. case E_STRICT:
  285. $error = 'Strict';
  286. $log = LOG_NOTICE;
  287. break;
  288. case E_DEPRECATED:
  289. case E_USER_DEPRECATED:
  290. $error = 'Deprecated';
  291. $log = LOG_NOTICE;
  292. break;
  293. }
  294. return array($error, $log);
  295. }
  296. /**
  297. * Generate the string to use to describe the error.
  298. *
  299. * @param string $error The error type (e.g. "Warning")
  300. * @param int $code Code of error
  301. * @param string $description Error description
  302. * @param string $file File on which error occurred
  303. * @param int $line Line that triggered the error
  304. * @return string
  305. */
  306. protected static function _getErrorMessage($error, $code, $description, $file, $line) {
  307. $errorConfig = Configure::read('Error');
  308. $message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
  309. if (!empty($errorConfig['trace'])) {
  310. // https://bugs.php.net/bug.php?id=65322
  311. if (version_compare(PHP_VERSION, '5.4.21', '<')) {
  312. if (!class_exists('Debugger')) {
  313. App::load('Debugger');
  314. }
  315. if (!class_exists('CakeText')) {
  316. App::uses('CakeText', 'Utility');
  317. App::load('CakeText');
  318. }
  319. }
  320. $trace = Debugger::trace(array('start' => 1, 'format' => 'log'));
  321. $message .= "\nTrace:\n" . $trace . "\n";
  322. }
  323. return $message;
  324. }
  325. }