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: * Set as the default exception handler by the CakePHP bootstrap process.
100: *
101: * This will either use custom exception renderer class if configured,
102: * or use the default ExceptionRenderer.
103: *
104: * @param Exception $exception The exception to render.
105: * @return void
106: * @see http://php.net/manual/en/function.set-exception-handler.php
107: */
108: public static function handleException(Exception $exception) {
109: $config = Configure::read('Exception');
110: self::_log($exception, $config);
111:
112: $renderer = isset($config['renderer']) ? $config['renderer'] : 'ExceptionRenderer';
113: if ($renderer !== 'ExceptionRenderer') {
114: list($plugin, $renderer) = pluginSplit($renderer, true);
115: App::uses($renderer, $plugin . 'Error');
116: }
117: try {
118: $error = new $renderer($exception);
119: $error->render();
120: } catch (Exception $e) {
121: set_error_handler(Configure::read('Error.handler')); // Should be using configured ErrorHandler
122: Configure::write('Error.trace', false); // trace is useless here since it's internal
123: $message = sprintf("[%s] %s\n%s", // Keeping same message format
124: get_class($e),
125: $e->getMessage(),
126: $e->getTraceAsString()
127: );
128: trigger_error($message, E_USER_ERROR);
129: }
130: }
131:
132: /**
133: * Generates a formatted error message
134: *
135: * @param Exception $exception Exception instance
136: * @return string Formatted message
137: */
138: protected static function _getMessage($exception) {
139: $message = sprintf("[%s] %s",
140: get_class($exception),
141: $exception->getMessage()
142: );
143: if (method_exists($exception, 'getAttributes')) {
144: $attributes = $exception->getAttributes();
145: if ($attributes) {
146: $message .= "\nException Attributes: " . var_export($exception->getAttributes(), true);
147: }
148: }
149: if (php_sapi_name() !== 'cli') {
150: $request = Router::getRequest();
151: if ($request) {
152: $message .= "\nRequest URL: " . $request->here();
153: }
154: }
155: $message .= "\nStack Trace:\n" . $exception->getTraceAsString();
156: return $message;
157: }
158:
159: /**
160: * Handles exception logging
161: *
162: * @param Exception $exception The exception to render.
163: * @param array $config An array of configuration for logging.
164: * @return bool
165: */
166: protected static function _log(Exception $exception, $config) {
167: if (empty($config['log'])) {
168: return false;
169: }
170:
171: if (!empty($config['skipLog'])) {
172: foreach ((array)$config['skipLog'] as $class) {
173: if ($exception instanceof $class) {
174: return false;
175: }
176: }
177: }
178: return CakeLog::write(LOG_ERR, self::_getMessage($exception));
179: }
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) = self::mapErrorCode($code);
202: if ($log === LOG_ERR) {
203: return self::handleFatalError($code, $description, $file, $line);
204: }
205:
206: $debug = Configure::read('debug');
207: if ($debug) {
208: $data = array(
209: 'level' => $log,
210: 'code' => $code,
211: 'error' => $error,
212: 'description' => $description,
213: 'file' => $file,
214: 'line' => $line,
215: 'context' => $context,
216: 'start' => 2,
217: 'path' => Debugger::trimPath($file)
218: );
219: return Debugger::getInstance()->outputError($data);
220: }
221: $message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
222: if (!empty($errorConfig['trace'])) {
223: $trace = Debugger::trace(array('start' => 1, 'format' => 'log'));
224: $message .= "\nTrace:\n" . $trace . "\n";
225: }
226: return CakeLog::write($log, $message);
227: }
228:
229: /**
230: * Generate an error page when some fatal error happens.
231: *
232: * @param int $code Code of error
233: * @param string $description Error description
234: * @param string $file File on which error occurred
235: * @param int $line Line that triggered the error
236: * @return bool
237: */
238: public static function handleFatalError($code, $description, $file, $line) {
239: $logMessage = 'Fatal Error (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
240: CakeLog::write(LOG_ERR, $logMessage);
241:
242: $exceptionHandler = Configure::read('Exception.handler');
243: if (!is_callable($exceptionHandler)) {
244: return false;
245: }
246:
247: if (ob_get_level()) {
248: ob_end_clean();
249: }
250:
251: if (Configure::read('debug')) {
252: call_user_func($exceptionHandler, new FatalErrorException($description, 500, $file, $line));
253: } else {
254: call_user_func($exceptionHandler, new InternalErrorException());
255: }
256: return false;
257: }
258:
259: /**
260: * Map an error code into an Error word, and log location.
261: *
262: * @param int $code Error code to map
263: * @return array Array of error word, and log location.
264: */
265: public static function mapErrorCode($code) {
266: $error = $log = null;
267: switch ($code) {
268: case E_PARSE:
269: case E_ERROR:
270: case E_CORE_ERROR:
271: case E_COMPILE_ERROR:
272: case E_USER_ERROR:
273: $error = 'Fatal Error';
274: $log = LOG_ERR;
275: break;
276: case E_WARNING:
277: case E_USER_WARNING:
278: case E_COMPILE_WARNING:
279: case E_RECOVERABLE_ERROR:
280: $error = 'Warning';
281: $log = LOG_WARNING;
282: break;
283: case E_NOTICE:
284: case E_USER_NOTICE:
285: $error = 'Notice';
286: $log = LOG_NOTICE;
287: break;
288: case E_STRICT:
289: $error = 'Strict';
290: $log = LOG_NOTICE;
291: break;
292: case E_DEPRECATED:
293: case E_USER_DEPRECATED:
294: $error = 'Deprecated';
295: $log = LOG_NOTICE;
296: break;
297: }
298: return array($error, $log);
299: }
300:
301: }
302: