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