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