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