Commit | Line | Data |
---|---|---|
6a488035 | 1 | <?php |
6a488035 TO |
2 | /* |
3 | +--------------------------------------------------------------------+ | |
7e9e8871 | 4 | | CiviCRM version 4.7 | |
6a488035 | 5 | +--------------------------------------------------------------------+ |
fa938177 | 6 | | Copyright CiviCRM LLC (c) 2004-2016 | |
6a488035 TO |
7 | +--------------------------------------------------------------------+ |
8 | | This file is a part of CiviCRM. | | |
9 | | | | |
10 | | CiviCRM is free software; you can copy, modify, and distribute it | | |
11 | | under the terms of the GNU Affero General Public License | | |
12 | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | |
13 | | | | |
14 | | CiviCRM is distributed in the hope that it will be useful, but | | |
15 | | WITHOUT ANY WARRANTY; without even the implied warranty of | | |
16 | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | |
17 | | See the GNU Affero General Public License for more details. | | |
18 | | | | |
19 | | You should have received a copy of the GNU Affero General Public | | |
20 | | License and the CiviCRM Licensing Exception along | | |
21 | | with this program; if not, contact CiviCRM LLC | | |
22 | | at info[AT]civicrm[DOT]org. If you have questions about the | | |
23 | | GNU Affero General Public License or the licensing of CiviCRM, | | |
24 | | see the CiviCRM license FAQ at http://civicrm.org/licensing | | |
25 | +--------------------------------------------------------------------+ | |
d25dd0ee | 26 | */ |
6a488035 TO |
27 | |
28 | /** | |
29 | * Start of the Error framework. We should check out and inherit from | |
30 | * PEAR_ErrorStack and use that framework | |
31 | * | |
32 | * @package CRM | |
fa938177 | 33 | * @copyright CiviCRM LLC (c) 2004-2016 |
6a488035 TO |
34 | */ |
35 | ||
36 | require_once 'PEAR/ErrorStack.php'; | |
37 | require_once 'PEAR/Exception.php'; | |
dcc4f6a7 | 38 | require_once 'CRM/Core/Exception.php'; |
6a488035 TO |
39 | |
40 | require_once 'Log.php'; | |
28518c90 EM |
41 | |
42 | /** | |
43 | * Class CRM_Exception | |
44 | */ | |
6a488035 | 45 | class CRM_Exception extends PEAR_Exception { |
b5c2afd0 | 46 | /** |
8eedd10a | 47 | * Redefine the exception so message isn't optional. |
48 | * | |
b5c2afd0 EM |
49 | * Supported signatures: |
50 | * - PEAR_Exception(string $message); | |
51 | * - PEAR_Exception(string $message, int $code); | |
52 | * - PEAR_Exception(string $message, Exception $cause); | |
53 | * - PEAR_Exception(string $message, Exception $cause, int $code); | |
54 | * - PEAR_Exception(string $message, PEAR_Error $cause); | |
55 | * - PEAR_Exception(string $message, PEAR_Error $cause, int $code); | |
56 | * - PEAR_Exception(string $message, array $causes); | |
57 | * - PEAR_Exception(string $message, array $causes, int $code); | |
da3c7979 | 58 | * |
3bdca100 | 59 | * @param string $message exception message |
da3c7979 EM |
60 | * @param int $code |
61 | * @param Exception $previous | |
b5c2afd0 | 62 | */ |
353ffa53 | 63 | public function __construct($message = NULL, $code = 0, Exception $previous = NULL) { |
6a488035 TO |
64 | parent::__construct($message, $code, $previous); |
65 | } | |
96025800 | 66 | |
6a488035 TO |
67 | } |
68 | ||
a0ee3941 EM |
69 | /** |
70 | * Class CRM_Core_Error | |
71 | */ | |
6a488035 TO |
72 | class CRM_Core_Error extends PEAR_ErrorStack { |
73 | ||
74 | /** | |
0880a9d0 | 75 | * Status code of various types of errors. |
6a488035 | 76 | */ |
7da04cde TO |
77 | const FATAL_ERROR = 2; |
78 | const DUPLICATE_CONTACT = 8001; | |
79 | const DUPLICATE_CONTRIBUTION = 8002; | |
80 | const DUPLICATE_PARTICIPANT = 8003; | |
6a488035 TO |
81 | |
82 | /** | |
83 | * We only need one instance of this object. So we use the singleton | |
84 | * pattern and cache the instance in this variable | |
85 | * @var object | |
6a488035 TO |
86 | */ |
87 | private static $_singleton = NULL; | |
88 | ||
89 | /** | |
d09edf64 | 90 | * The logger object for this application. |
6a488035 | 91 | * @var object |
6a488035 TO |
92 | */ |
93 | private static $_log = NULL; | |
94 | ||
95 | /** | |
96 | * If modeException == true, errors are raised as exception instead of returning civicrm_errors | |
6a488035 TO |
97 | */ |
98 | public static $modeException = NULL; | |
99 | ||
100 | /** | |
100fef9d | 101 | * Singleton function used to manage this object. |
6a488035 | 102 | * |
dd244018 EM |
103 | * @param null $package |
104 | * @param bool $msgCallback | |
105 | * @param bool $contextCallback | |
106 | * @param bool $throwPEAR_Error | |
107 | * @param string $stackClass | |
108 | * | |
6a488035 | 109 | * @return object |
6a488035 | 110 | */ |
2aa397bc | 111 | public static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') { |
6a488035 TO |
112 | if (self::$_singleton === NULL) { |
113 | self::$_singleton = new CRM_Core_Error('CiviCRM'); | |
114 | } | |
115 | return self::$_singleton; | |
116 | } | |
117 | ||
118 | /** | |
0880a9d0 | 119 | * Constructor. |
6a488035 | 120 | */ |
00be9182 | 121 | public function __construct() { |
6a488035 TO |
122 | parent::__construct('CiviCRM'); |
123 | ||
124 | $log = CRM_Core_Config::getLog(); | |
125 | $this->setLogger($log); | |
126 | ||
127 | // set up error handling for Pear Error Stack | |
128 | $this->setDefaultCallback(array($this, 'handlePES')); | |
129 | } | |
130 | ||
a0ee3941 EM |
131 | /** |
132 | * @param $error | |
133 | * @param string $separator | |
134 | * | |
135 | * @return array|null|string | |
136 | */ | |
93a11cd6 | 137 | static public function getMessages(&$error, $separator = '<br />') { |
6a488035 TO |
138 | if (is_a($error, 'CRM_Core_Error')) { |
139 | $errors = $error->getErrors(); | |
140 | $message = array(); | |
141 | foreach ($errors as $e) { | |
142 | $message[] = $e['code'] . ': ' . $e['message']; | |
143 | } | |
144 | $message = implode($separator, $message); | |
145 | return $message; | |
146 | } | |
147 | return NULL; | |
148 | } | |
149 | ||
dbddfb08 | 150 | /** |
0880a9d0 | 151 | * Status display function specific to payment processor errors. |
dbddfb08 EM |
152 | * @param $error |
153 | * @param string $separator | |
154 | */ | |
00be9182 | 155 | public static function displaySessionError(&$error, $separator = '<br />') { |
6a488035 TO |
156 | $message = self::getMessages($error, $separator); |
157 | if ($message) { | |
158 | $status = ts("Payment Processor Error message") . "{$separator} $message"; | |
159 | $session = CRM_Core_Session::singleton(); | |
160 | $session->setStatus($status); | |
161 | } | |
162 | } | |
163 | ||
164 | /** | |
100fef9d | 165 | * Create the main callback method. this method centralizes error processing. |
6a488035 TO |
166 | * |
167 | * the errors we expect are from the pear modules DB, DB_DataObject | |
168 | * which currently use PEAR::raiseError to notify of error messages. | |
169 | * | |
3bdca100 | 170 | * @param object $pearError PEAR_Error |
6a488035 TO |
171 | */ |
172 | public static function handle($pearError) { | |
2b2c4099 TO |
173 | if (defined('CIVICRM_TEST')) { |
174 | return self::simpleHandler($pearError); | |
175 | } | |
6a488035 TO |
176 | |
177 | // setup smarty with config, session and template location. | |
178 | $template = CRM_Core_Smarty::singleton(); | |
179 | $config = CRM_Core_Config::singleton(); | |
180 | ||
181 | if ($config->backtrace) { | |
182 | self::backtrace(); | |
183 | } | |
184 | ||
185 | // create the error array | |
ca8416c8 | 186 | $error = self::getErrorDetails($pearError); |
2e4ade96 TO |
187 | |
188 | // We access connection info via _DB_DATAOBJECT instead | |
189 | // of, e.g., calling getDatabaseConnection(), so that we | |
190 | // can avoid infinite loops. | |
191 | global $_DB_DATAOBJECT; | |
192 | ||
193 | if (!isset($_DB_DATAOBJECT['CONFIG']['database'])) { | |
194 | // we haven't setup sql, so it's not our sql error... | |
195 | } | |
196 | elseif (preg_match('/^mysql:/', $_DB_DATAOBJECT['CONFIG']['database']) && | |
6a488035 TO |
197 | mysql_error() |
198 | ) { | |
199 | $mysql_error = mysql_error() . ', ' . mysql_errno(); | |
200 | $template->assign_by_ref('mysql_code', $mysql_error); | |
201 | ||
202 | // execute a dummy query to clear error stack | |
203 | mysql_query('select 1'); | |
204 | } | |
2e4ade96 | 205 | elseif (preg_match('/^mysqli:/', $_DB_DATAOBJECT['CONFIG']['database'])) { |
6a488035 TO |
206 | $dao = new CRM_Core_DAO(); |
207 | ||
6a488035 TO |
208 | if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5])) { |
209 | $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5]; | |
210 | $link = $conn->connection; | |
211 | ||
212 | if (mysqli_error($link)) { | |
213 | $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link); | |
214 | $template->assign_by_ref('mysql_code', $mysql_error); | |
215 | ||
216 | // execute a dummy query to clear error stack | |
217 | mysqli_query($link, 'select 1'); | |
218 | } | |
219 | } | |
220 | } | |
221 | ||
222 | $template->assign_by_ref('error', $error); | |
223 | $errorDetails = CRM_Core_Error::debug('', $error, FALSE); | |
224 | $template->assign_by_ref('errorDetails', $errorDetails); | |
225 | ||
226 | CRM_Core_Error::debug_var('Fatal Error Details', $error); | |
227 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
228 | ||
229 | if ($config->initialized) { | |
230 | $content = $template->fetch('CRM/common/fatal.tpl'); | |
231 | echo CRM_Utils_System::theme($content); | |
232 | } | |
233 | else { | |
234 | echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>"; | |
235 | CRM_Core_Error::debug(NULL, $error); | |
236 | } | |
3a210ec0 E |
237 | static $runOnce = FALSE; |
238 | if ($runOnce) { | |
239 | exit; | |
240 | } | |
241 | $runOnce = TRUE; | |
6a488035 TO |
242 | self::abend(1); |
243 | } | |
244 | ||
a0ee3941 | 245 | /** |
4f1f1f2a CW |
246 | * this function is used to trap and print errors |
247 | * during system initialization time. Hence the error | |
248 | * message is quite ugly | |
249 | * | |
a0ee3941 EM |
250 | * @param $pearError |
251 | */ | |
6a488035 TO |
252 | public static function simpleHandler($pearError) { |
253 | ||
ca8416c8 | 254 | $error = self::getErrorDetails($pearError); |
255 | ||
256 | // ensure that debug does not check permissions since we are in bootstrap | |
257 | // mode and need to print a decent message to help the user | |
258 | CRM_Core_Error::debug('Initialization Error', $error, TRUE, TRUE, FALSE); | |
259 | ||
260 | // always log the backtrace to a file | |
261 | self::backtrace('backTrace', TRUE); | |
262 | ||
263 | exit(0); | |
264 | } | |
265 | ||
266 | /** | |
267 | * this function is used to return error details | |
268 | * | |
269 | * @param $pearError | |
270 | * | |
271 | * @return array $error | |
272 | */ | |
273 | public static function getErrorDetails($pearError) { | |
6a488035 | 274 | // create the error array |
353ffa53 TO |
275 | $error = array(); |
276 | $error['callback'] = $pearError->getCallback(); | |
277 | $error['code'] = $pearError->getCode(); | |
278 | $error['message'] = $pearError->getMessage(); | |
279 | $error['mode'] = $pearError->getMode(); | |
6a488035 | 280 | $error['debug_info'] = $pearError->getDebugInfo(); |
353ffa53 TO |
281 | $error['type'] = $pearError->getType(); |
282 | $error['user_info'] = $pearError->getUserInfo(); | |
283 | $error['to_string'] = $pearError->toString(); | |
6a488035 | 284 | |
ca8416c8 | 285 | return $error; |
6a488035 TO |
286 | } |
287 | ||
288 | /** | |
289 | * Handle errors raised using the PEAR Error Stack. | |
290 | * | |
291 | * currently the handler just requests the PES framework | |
292 | * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH). | |
293 | * | |
294 | * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE. | |
295 | * | |
296 | * Also, if we do not return any value the PEAR_ErrorStack::push() then does the | |
297 | * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen, | |
298 | * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog(); | |
ea3ddccf | 299 | * |
300 | * @param mixed $pearError | |
301 | * | |
302 | * @return int | |
6a488035 TO |
303 | */ |
304 | public static function handlePES($pearError) { | |
305 | return PEAR_ERRORSTACK_PUSH; | |
306 | } | |
307 | ||
308 | /** | |
0880a9d0 | 309 | * Display an error page with an error message describing what happened. |
6a488035 | 310 | * |
6a0b768e TO |
311 | * @param string $message |
312 | * The error message. | |
313 | * @param string $code | |
314 | * The error code if any. | |
315 | * @param string $email | |
316 | * The email address to notify of this situation. | |
77b97be7 EM |
317 | * |
318 | * @throws Exception | |
6a488035 | 319 | */ |
00be9182 | 320 | public static function fatal($message = NULL, $code = NULL, $email = NULL) { |
6a488035 | 321 | $vars = array( |
0ac9fd52 | 322 | 'message' => htmlspecialchars($message), |
6a488035 TO |
323 | 'code' => $code, |
324 | ); | |
325 | ||
326 | if (self::$modeException) { | |
327 | // CRM-11043 | |
328 | CRM_Core_Error::debug_var('Fatal Error Details', $vars); | |
329 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
330 | ||
331 | $details = 'A fatal error was triggered'; | |
332 | if ($message) { | |
333 | $details .= ': ' . $message; | |
2aa397bc | 334 | } |
6a488035 TO |
335 | throw new Exception($details, $code); |
336 | } | |
337 | ||
338 | if (!$message) { | |
339 | $message = ts('We experienced an unexpected error. Please post a detailed description and the backtrace on the CiviCRM forums: %1', array(1 => 'http://forum.civicrm.org/')); | |
340 | } | |
341 | ||
342 | if (php_sapi_name() == "cli") { | |
343 | print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n"); | |
0c4a3d8b | 344 | // Fix for CRM-16899 |
4c68cf7b | 345 | echo static::formatBacktrace(debug_backtrace()); |
6a488035 TO |
346 | die("\n"); |
347 | // FIXME: Why doesn't this call abend()? | |
348 | // Difference: abend() will cleanup transaction and (via civiExit) store session state | |
349 | // self::abend(CRM_Core_Error::FATAL_ERROR); | |
350 | } | |
351 | ||
352 | $config = CRM_Core_Config::singleton(); | |
353 | ||
354 | if ($config->fatalErrorHandler && | |
355 | function_exists($config->fatalErrorHandler) | |
356 | ) { | |
357 | $name = $config->fatalErrorHandler; | |
358 | $ret = $name($vars); | |
359 | if ($ret) { | |
360 | // the call has been successfully handled | |
361 | // so we just exit | |
362 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
363 | } | |
364 | } | |
365 | ||
25dc2153 PH |
366 | if ($config->backtrace) { |
367 | self::backtrace(); | |
368 | } | |
369 | ||
370 | CRM_Core_Error::debug_var('Fatal Error Details', $vars); | |
371 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
372 | ||
34866662 CW |
373 | // If we are in an ajax callback, format output appropriately |
374 | if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) { | |
375 | $out = array( | |
376 | 'status' => 'fatal', | |
377 | 'content' => '<div class="messages status no-popup"><div class="icon inform-icon"></div>' . ts('Sorry but we are not able to provide this at the moment.') . '</div>', | |
378 | ); | |
379 | if ($config->backtrace && CRM_Core_Permission::check('view debug output')) { | |
380 | $out['backtrace'] = self::parseBacktrace(debug_backtrace()); | |
381 | $message .= '<p><em>See console for backtrace</em></p>'; | |
382 | } | |
1528ac1d | 383 | CRM_Core_Session::setStatus($message, ts('Sorry an error occurred'), 'error'); |
34866662 CW |
384 | CRM_Core_Transaction::forceRollbackIfEnabled(); |
385 | CRM_Core_Page_AJAX::returnJsonResponse($out); | |
386 | } | |
387 | ||
6a488035 TO |
388 | $template = CRM_Core_Smarty::singleton(); |
389 | $template->assign($vars); | |
f431d51f | 390 | $config->userSystem->outputError($template->fetch('CRM/common/fatal.tpl')); |
6a488035 TO |
391 | |
392 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
393 | } | |
394 | ||
395 | /** | |
0880a9d0 | 396 | * Display an error page with an error message describing what happened. |
6a488035 TO |
397 | * |
398 | * This function is evil -- it largely replicates fatal(). Hopefully the | |
399 | * entire CRM_Core_Error system can be hollowed out and replaced with | |
400 | * something that follows a cleaner separation of concerns. | |
401 | * | |
402 | * @param Exception $exception | |
6a488035 | 403 | */ |
00be9182 | 404 | public static function handleUnhandledException($exception) { |
4b57bc9f EM |
405 | try { |
406 | CRM_Utils_Hook::unhandledException($exception); | |
0db6c3e1 TO |
407 | } |
408 | catch (Exception $other) { | |
4b57bc9f | 409 | // if the exception-handler generates an exception, then that sucks! oh, well. carry on. |
4fd5f07e | 410 | CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other)); |
4b57bc9f | 411 | } |
6a488035 TO |
412 | $config = CRM_Core_Config::singleton(); |
413 | $vars = array( | |
414 | 'message' => $exception->getMessage(), | |
415 | 'code' => NULL, | |
416 | 'exception' => $exception, | |
417 | ); | |
418 | if (!$vars['message']) { | |
419 | $vars['message'] = ts('We experienced an unexpected error. Please post a detailed description and the backtrace on the CiviCRM forums: %1', array(1 => 'http://forum.civicrm.org/')); | |
420 | } | |
421 | ||
422 | // Case A: CLI | |
423 | if (php_sapi_name() == "cli") { | |
424 | printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']); | |
425 | print self::formatTextException($exception); | |
426 | die("\n"); | |
427 | // FIXME: Why doesn't this call abend()? | |
428 | // Difference: abend() will cleanup transaction and (via civiExit) store session state | |
429 | // self::abend(CRM_Core_Error::FATAL_ERROR); | |
430 | } | |
431 | ||
432 | // Case B: Custom error handler | |
433 | if ($config->fatalErrorHandler && | |
434 | function_exists($config->fatalErrorHandler) | |
435 | ) { | |
436 | $name = $config->fatalErrorHandler; | |
437 | $ret = $name($vars); | |
438 | if ($ret) { | |
439 | // the call has been successfully handled | |
440 | // so we just exit | |
441 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
442 | } | |
443 | } | |
444 | ||
445 | // Case C: Default error handler | |
446 | ||
447 | // log to file | |
a3fab31f | 448 | CRM_Core_Error::debug_var('Fatal Error Details', $vars, FALSE); |
6a488035 TO |
449 | CRM_Core_Error::backtrace('backTrace', TRUE); |
450 | ||
451 | // print to screen | |
452 | $template = CRM_Core_Smarty::singleton(); | |
453 | $template->assign($vars); | |
f431d51f | 454 | $content = $template->fetch('CRM/common/fatal.tpl'); |
6a488035 TO |
455 | if ($config->backtrace) { |
456 | $content = self::formatHtmlException($exception) . $content; | |
457 | } | |
458 | if ($config->userFramework == 'Joomla' && | |
459 | class_exists('JError') | |
460 | ) { | |
461 | JError::raiseError('CiviCRM-001', $content); | |
462 | } | |
463 | else { | |
464 | echo CRM_Utils_System::theme($content); | |
465 | } | |
466 | ||
467 | // fin | |
468 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
469 | } | |
470 | ||
471 | /** | |
100fef9d | 472 | * Outputs pre-formatted debug information. Flushes the buffers |
6a488035 TO |
473 | * so we can interrupt a potential POST/redirect |
474 | * | |
3bdca100 | 475 | * @param string $name name of debug section |
476 | * @param $variable mixed reference to variables that we need a trace of | |
477 | * @param bool $log should we log or return the output | |
478 | * @param bool $html whether to generate a HTML-escaped output | |
479 | * @param bool $checkPermission should we check permissions before displaying output | |
90154ece DL |
480 | * useful when we die during initialization and permissioning |
481 | * subsystem is not initialized - CRM-13765 | |
6a488035 | 482 | * |
a6c01b45 CW |
483 | * @return string |
484 | * the generated output | |
6a488035 | 485 | */ |
00be9182 | 486 | public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) { |
6a488035 TO |
487 | $error = self::singleton(); |
488 | ||
489 | if ($variable === NULL) { | |
490 | $variable = $name; | |
491 | $name = NULL; | |
492 | } | |
493 | ||
494 | $out = print_r($variable, TRUE); | |
495 | $prefix = NULL; | |
496 | if ($html) { | |
497 | $out = htmlspecialchars($out); | |
498 | if ($name) { | |
499 | $prefix = "<p>$name</p>"; | |
500 | } | |
501 | $out = "{$prefix}<p><pre>$out</pre></p><p></p>"; | |
502 | } | |
503 | else { | |
504 | if ($name) { | |
505 | $prefix = "$name:\n"; | |
506 | } | |
507 | $out = "{$prefix}$out\n"; | |
508 | } | |
90154ece DL |
509 | if ( |
510 | $log && | |
511 | (!$checkPermission || CRM_Core_Permission::check('view debug output')) | |
512 | ) { | |
6a488035 TO |
513 | echo $out; |
514 | } | |
515 | ||
516 | return $out; | |
517 | } | |
518 | ||
519 | /** | |
520 | * Similar to the function debug. Only difference is | |
521 | * in the formatting of the output. | |
522 | * | |
c490a46a CW |
523 | * @param string $variable_name |
524 | * @param mixed $variable | |
6a0b768e TO |
525 | * @param bool $print |
526 | * Should we use print_r ? (else we use var_dump). | |
527 | * @param bool $log | |
528 | * Should we log or return the output. | |
529 | * @param string $comp | |
530 | * Variable name. | |
2a6da8d7 | 531 | * |
a6c01b45 CW |
532 | * @return string |
533 | * the generated output | |
6a488035 | 534 | * |
6a488035 | 535 | * |
6a488035 TO |
536 | * |
537 | * @see CRM_Core_Error::debug() | |
538 | * @see CRM_Core_Error::debug_log_message() | |
539 | */ | |
3bdca100 | 540 | public static function debug_var( |
f9f40af3 | 541 | $variable_name, |
6a488035 TO |
542 | $variable, |
543 | $print = TRUE, | |
2aa397bc TO |
544 | $log = TRUE, |
545 | $comp = '' | |
6a488035 TO |
546 | ) { |
547 | // check if variable is set | |
548 | if (!isset($variable)) { | |
549 | $out = "\$$variable_name is not set"; | |
550 | } | |
551 | else { | |
552 | if ($print) { | |
553 | $out = print_r($variable, TRUE); | |
554 | $out = "\$$variable_name = $out"; | |
555 | } | |
556 | else { | |
557 | // use var_dump | |
558 | ob_start(); | |
559 | var_dump($variable); | |
560 | $dump = ob_get_contents(); | |
561 | ob_end_clean(); | |
562 | $out = "\n\$$variable_name = $dump"; | |
563 | } | |
564 | // reset if it is an array | |
565 | if (is_array($variable)) { | |
566 | reset($variable); | |
567 | } | |
568 | } | |
569 | return self::debug_log_message($out, FALSE, $comp); | |
570 | } | |
571 | ||
572 | /** | |
edc8adfc | 573 | * Display the error message on terminal and append it to the log file. |
574 | * | |
575 | * Provided the user has the 'view debug output' the output should be displayed. In all | |
576 | * cases it should be logged. | |
6a488035 | 577 | * |
ea3ddccf | 578 | * @param string $message |
6a0b768e TO |
579 | * @param bool $out |
580 | * Should we log or return the output. | |
6a488035 | 581 | * |
6a0b768e TO |
582 | * @param string $comp |
583 | * Message to be output. | |
ea3ddccf | 584 | * @param string $priority |
6a488035 | 585 | * |
ea3ddccf | 586 | * @return string |
587 | * Format of the backtrace | |
6a488035 | 588 | */ |
6e5ad5ee | 589 | public static function debug_log_message($message, $out = FALSE, $comp = '', $priority = NULL) { |
213a5f19 | 590 | $config = CRM_Core_Config::singleton(); |
6a488035 TO |
591 | |
592 | $file_log = self::createDebugLogger($comp); | |
6e5ad5ee | 593 | $file_log->log("$message\n", $priority); |
0ac9fd52 CB |
594 | |
595 | $str = '<p/><code>' . htmlspecialchars($message) . '</code>'; | |
6a488035 TO |
596 | if ($out && CRM_Core_Permission::check('view debug output')) { |
597 | echo $str; | |
598 | } | |
599 | $file_log->close(); | |
600 | ||
3a036b15 | 601 | if (!empty($config->userFrameworkLogging)) { |
1fadd891 | 602 | // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why |
213a5f19 | 603 | if ($config->userSystem->is_drupal and function_exists('watchdog')) { |
eb9dd128 | 604 | watchdog('civicrm', '%message', array('%message' => $message), WATCHDOG_DEBUG); |
213a5f19 EM |
605 | } |
606 | } | |
6a488035 TO |
607 | |
608 | return $str; | |
609 | } | |
610 | ||
611 | /** | |
612 | * Append to the query log (if enabled) | |
ad37ac8e | 613 | * |
614 | * @param string $string | |
6a488035 | 615 | */ |
00be9182 | 616 | public static function debug_query($string) { |
481a74f4 | 617 | if (defined('CIVICRM_DEBUG_LOG_QUERY')) { |
7e7d0323 | 618 | if (CIVICRM_DEBUG_LOG_QUERY === 'backtrace') { |
481a74f4 | 619 | CRM_Core_Error::backtrace($string, TRUE); |
0db6c3e1 | 620 | } |
481a74f4 | 621 | elseif (CIVICRM_DEBUG_LOG_QUERY) { |
b0ccde7b | 622 | CRM_Core_Error::debug_var('Query', $string, TRUE, TRUE, 'sql_log'); |
6a488035 TO |
623 | } |
624 | } | |
625 | } | |
626 | ||
d090b80b TO |
627 | /** |
628 | * Execute a query and log the results. | |
629 | * | |
630 | * @param string $query | |
631 | */ | |
00be9182 | 632 | public static function debug_query_result($query) { |
7d0b8a47 | 633 | $results = CRM_Core_DAO::executeQuery($query)->fetchAll(); |
d090b80b TO |
634 | CRM_Core_Error::debug_var('dao result', array('query' => $query, 'results' => $results)); |
635 | } | |
636 | ||
6a488035 | 637 | /** |
0880a9d0 | 638 | * Obtain a reference to the error log. |
6a488035 | 639 | * |
edc8adfc | 640 | * @param string $prefix |
77b97be7 | 641 | * |
6a488035 TO |
642 | * @return Log |
643 | */ | |
edc8adfc | 644 | public static function createDebugLogger($prefix = '') { |
645 | self::generateLogFileName($prefix); | |
646 | return Log::singleton('file', \Civi::$statics[__CLASS__]['logger_file' . $prefix], ''); | |
647 | } | |
648 | ||
649 | /** | |
650 | * Generate the name of the logfile to use and store it as a static. | |
651 | * | |
652 | * This function includes poor man's log file management and a check as to whether the file exists. | |
653 | * | |
654 | * @param string $prefix | |
655 | */ | |
656 | protected static function generateLogFileName($prefix) { | |
657 | if (!isset(\Civi::$statics[__CLASS__]['logger_file' . $prefix])) { | |
931ba0f3 | 658 | $config = CRM_Core_Config::singleton(); |
6a488035 | 659 | |
edc8adfc | 660 | $prefixString = $prefix ? ($prefix . '.') : ''; |
6a488035 | 661 | |
edc8adfc | 662 | $fileName = $config->configAndLogDir . 'CiviCRM.' . $prefixString . md5($config->dsn) . '.log'; |
931ba0f3 | 663 | |
664 | // Roll log file monthly or if greater than 256M | |
665 | // note that PHP file functions have a limit of 2G and hence | |
666 | // the alternative was introduce | |
667 | if (file_exists($fileName)) { | |
668 | $fileTime = date("Ym", filemtime($fileName)); | |
669 | $fileSize = filesize($fileName); | |
670 | if (($fileTime < date('Ym')) || | |
671 | ($fileSize > 256 * 1024 * 1024) || | |
672 | ($fileSize < 0) | |
673 | ) { | |
674 | rename($fileName, | |
675 | $fileName . '.' . date('YmdHi') | |
676 | ); | |
677 | } | |
678 | } | |
edc8adfc | 679 | \Civi::$statics[__CLASS__]['logger_file' . $prefix] = $fileName; |
931ba0f3 | 680 | } |
6a488035 TO |
681 | } |
682 | ||
a0ee3941 EM |
683 | /** |
684 | * @param string $msg | |
685 | * @param bool $log | |
686 | */ | |
00be9182 | 687 | public static function backtrace($msg = 'backTrace', $log = FALSE) { |
6a488035 TO |
688 | $backTrace = debug_backtrace(); |
689 | $message = self::formatBacktrace($backTrace); | |
690 | if (!$log) { | |
691 | CRM_Core_Error::debug($msg, $message); | |
692 | } | |
693 | else { | |
694 | CRM_Core_Error::debug_var($msg, $message); | |
695 | } | |
696 | } | |
697 | ||
698 | /** | |
0880a9d0 | 699 | * Render a backtrace array as a string. |
6a488035 | 700 | * |
6a0b768e TO |
701 | * @param array $backTrace |
702 | * Array of stack frames. | |
703 | * @param bool $showArgs | |
704 | * TRUE if we should try to display content of function arguments (which could be sensitive); FALSE to display only the type of each function argument. | |
705 | * @param int $maxArgLen | |
706 | * Maximum number of characters to show from each argument string. | |
a6c01b45 CW |
707 | * @return string |
708 | * printable plain-text | |
6a488035 | 709 | */ |
00be9182 | 710 | public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) { |
6a488035 | 711 | $message = ''; |
34866662 CW |
712 | foreach (self::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) { |
713 | $message .= sprintf("#%s %s\n", $idx, $trace); | |
714 | } | |
2aa397bc | 715 | $message .= sprintf("#%s {main}\n", 1 + $idx); |
34866662 CW |
716 | return $message; |
717 | } | |
718 | ||
719 | /** | |
0880a9d0 | 720 | * Render a backtrace array as an array. |
34866662 | 721 | * |
6a0b768e TO |
722 | * @param array $backTrace |
723 | * Array of stack frames. | |
724 | * @param bool $showArgs | |
725 | * TRUE if we should try to display content of function arguments (which could be sensitive); FALSE to display only the type of each function argument. | |
726 | * @param int $maxArgLen | |
727 | * Maximum number of characters to show from each argument string. | |
34866662 CW |
728 | * @return array |
729 | * @see debug_backtrace | |
730 | * @see Exception::getTrace() | |
731 | */ | |
00be9182 | 732 | public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) { |
34866662 CW |
733 | $ret = array(); |
734 | foreach ($backTrace as $trace) { | |
6a488035 TO |
735 | $args = array(); |
736 | $fnName = CRM_Utils_Array::value('function', $trace); | |
34866662 | 737 | $className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : ''; |
6a488035 | 738 | |
83e7cba6 | 739 | // Do not show args for a few password related functions |
6a488035 TO |
740 | $skipArgs = ($className == 'DB::' && $fnName == 'connect') ? TRUE : FALSE; |
741 | ||
83e7cba6 CB |
742 | if (!empty($trace['args'])) { |
743 | foreach ($trace['args'] as $arg) { | |
353ffa53 | 744 | if (!$showArgs || $skipArgs) { |
83e7cba6 CB |
745 | $args[] = '(' . gettype($arg) . ')'; |
746 | continue; | |
747 | } | |
748 | switch ($type = gettype($arg)) { | |
749 | case 'boolean': | |
750 | $args[] = $arg ? 'TRUE' : 'FALSE'; | |
751 | break; | |
2aa397bc | 752 | |
83e7cba6 CB |
753 | case 'integer': |
754 | case 'double': | |
755 | $args[] = $arg; | |
756 | break; | |
2aa397bc | 757 | |
83e7cba6 | 758 | case 'string': |
86bfa4f6 | 759 | $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen) . '"'; |
83e7cba6 | 760 | break; |
2aa397bc | 761 | |
83e7cba6 | 762 | case 'array': |
92fcb95f | 763 | $args[] = '(Array:' . count($arg) . ')'; |
83e7cba6 | 764 | break; |
2aa397bc | 765 | |
83e7cba6 CB |
766 | case 'object': |
767 | $args[] = 'Object(' . get_class($arg) . ')'; | |
768 | break; | |
2aa397bc | 769 | |
83e7cba6 CB |
770 | case 'resource': |
771 | $args[] = 'Resource'; | |
772 | break; | |
2aa397bc | 773 | |
83e7cba6 CB |
774 | case 'NULL': |
775 | $args[] = 'NULL'; | |
776 | break; | |
2aa397bc | 777 | |
83e7cba6 CB |
778 | default: |
779 | $args[] = "($type)"; | |
780 | break; | |
781 | } | |
6a488035 TO |
782 | } |
783 | } | |
784 | ||
34866662 CW |
785 | $ret[] = sprintf( |
786 | "%s(%s): %s%s(%s)", | |
6a488035 TO |
787 | CRM_Utils_Array::value('file', $trace, '[internal function]'), |
788 | CRM_Utils_Array::value('line', $trace, ''), | |
789 | $className, | |
790 | $fnName, | |
791 | implode(", ", $args) | |
792 | ); | |
793 | } | |
34866662 | 794 | return $ret; |
6a488035 TO |
795 | } |
796 | ||
797 | /** | |
0880a9d0 | 798 | * Render an exception as HTML string. |
6a488035 TO |
799 | * |
800 | * @param Exception $e | |
a6c01b45 CW |
801 | * @return string |
802 | * printable HTML text | |
6a488035 | 803 | */ |
00be9182 | 804 | public static function formatHtmlException(Exception $e) { |
6a488035 TO |
805 | $msg = ''; |
806 | ||
807 | // Exception metadata | |
808 | ||
809 | // Exception backtrace | |
810 | if ($e instanceof PEAR_Exception) { | |
811 | $ei = $e; | |
812 | while (is_callable(array($ei, 'getCause'))) { | |
813 | if ($ei->getCause() instanceof PEAR_Error) { | |
814 | $msg .= '<table class="crm-db-error">'; | |
815 | $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value')); | |
816 | $msg .= '<tbody>'; | |
817 | foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) { | |
818 | $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f"))); | |
2aa397bc | 819 | } |
6a488035 | 820 | $msg .= '</tbody></table>'; |
2aa397bc | 821 | } |
6a488035 | 822 | $ei = $ei->getCause(); |
2aa397bc | 823 | } |
6a488035 | 824 | $msg .= $e->toHtml(); |
0db6c3e1 TO |
825 | } |
826 | else { | |
6a488035 TO |
827 | $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>'; |
828 | $msg .= '<pre>' . htmlentities(self::formatBacktrace($e->getTrace())) . '</pre>'; | |
829 | } | |
830 | return $msg; | |
831 | } | |
832 | ||
833 | /** | |
0880a9d0 | 834 | * Write details of an exception to the log. |
6a488035 TO |
835 | * |
836 | * @param Exception $e | |
a6c01b45 CW |
837 | * @return string |
838 | * printable plain text | |
6a488035 | 839 | */ |
00be9182 | 840 | public static function formatTextException(Exception $e) { |
6a488035 TO |
841 | $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n"; |
842 | ||
843 | $ei = $e; | |
844 | while (is_callable(array($ei, 'getCause'))) { | |
845 | if ($ei->getCause() instanceof PEAR_Error) { | |
846 | foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) { | |
847 | $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f"))); | |
848 | } | |
849 | } | |
850 | $ei = $ei->getCause(); | |
851 | } | |
852 | $msg .= self::formatBacktrace($e->getTrace()); | |
853 | return $msg; | |
854 | } | |
855 | ||
a0ee3941 EM |
856 | /** |
857 | * @param $message | |
858 | * @param int $code | |
859 | * @param string $level | |
100fef9d | 860 | * @param array $params |
a0ee3941 EM |
861 | * |
862 | * @return object | |
863 | */ | |
00be9182 | 864 | public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) { |
6a488035 TO |
865 | $error = CRM_Core_Error::singleton(); |
866 | $error->push($code, $level, array($params), $message); | |
867 | return $error; | |
868 | } | |
869 | ||
870 | /** | |
871 | * Set a status message in the session, then bounce back to the referrer. | |
872 | * | |
6a0b768e TO |
873 | * @param string $status |
874 | * The status message to set. | |
6a488035 | 875 | * |
2a6da8d7 EM |
876 | * @param null $redirect |
877 | * @param string $title | |
6a488035 | 878 | */ |
50ecd413 | 879 | public static function statusBounce($status, $redirect = NULL, $title = NULL) { |
6a488035 TO |
880 | $session = CRM_Core_Session::singleton(); |
881 | if (!$redirect) { | |
882 | $redirect = $session->readUserContext(); | |
883 | } | |
50ecd413 CW |
884 | if ($title === NULL) { |
885 | $title = ts('Error'); | |
886 | } | |
887 | $session->setStatus($status, $title, 'alert', array('expires' => 0)); | |
34866662 CW |
888 | if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) { |
889 | CRM_Core_Page_AJAX::returnJsonResponse(array('status' => 'error')); | |
890 | } | |
6a488035 TO |
891 | CRM_Utils_System::redirect($redirect); |
892 | } | |
893 | ||
894 | /** | |
0880a9d0 | 895 | * Reset the error stack. |
6a488035 | 896 | * |
6a488035 TO |
897 | */ |
898 | public static function reset() { | |
899 | $error = self::singleton(); | |
900 | $error->_errors = array(); | |
901 | $error->_errorsByLevel = array(); | |
902 | } | |
903 | ||
6a4257d4 | 904 | /** |
42c0daee TO |
905 | * PEAR error-handler which converts errors to exceptions |
906 | * | |
907 | * @param $pearError | |
908 | * @throws PEAR_Exception | |
6a4257d4 | 909 | */ |
6a488035 | 910 | public static function exceptionHandler($pearError) { |
ca8416c8 | 911 | CRM_Core_Error::debug_var('Fatal Error Details', self::getErrorDetails($pearError)); |
6a488035 TO |
912 | CRM_Core_Error::backtrace('backTrace', TRUE); |
913 | throw new PEAR_Exception($pearError->getMessage(), $pearError); | |
914 | } | |
915 | ||
916 | /** | |
42c0daee | 917 | * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport. |
6a488035 | 918 | * |
6a0b768e TO |
919 | * @param object $obj |
920 | * The PEAR_ERROR object. | |
a6c01b45 CW |
921 | * @return object |
922 | * $obj | |
6a488035 TO |
923 | */ |
924 | public static function nullHandler($obj) { | |
925 | CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}"); | |
926 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
927 | return $obj; | |
928 | } | |
929 | ||
d424ffde | 930 | /** |
6a488035 TO |
931 | * @deprecated |
932 | * This function is no longer used by v3 api. | |
933 | * @fixme Some core files call it but it should be re-thought & renamed or removed | |
d424ffde | 934 | * |
a0ee3941 EM |
935 | * @param $msg |
936 | * @param null $data | |
937 | * | |
938 | * @return array | |
939 | * @throws Exception | |
940 | */ | |
6a488035 TO |
941 | public static function &createAPIError($msg, $data = NULL) { |
942 | if (self::$modeException) { | |
943 | throw new Exception($msg, $data); | |
944 | } | |
945 | ||
946 | $values = array(); | |
947 | ||
948 | $values['is_error'] = 1; | |
949 | $values['error_message'] = $msg; | |
950 | if (isset($data)) { | |
951 | $values = array_merge($values, $data); | |
952 | } | |
953 | return $values; | |
954 | } | |
955 | ||
a0ee3941 EM |
956 | /** |
957 | * @param $file | |
958 | */ | |
6a488035 TO |
959 | public static function movedSiteError($file) { |
960 | $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend', | |
961 | 'reset=1', | |
962 | TRUE | |
963 | ); | |
964 | echo "We could not write $file. Have you moved your site directory or server?<p>"; | |
965 | echo "Please fix the setting by running the <a href=\"$url\">update config script</a>"; | |
966 | exit(); | |
967 | } | |
968 | ||
969 | /** | |
0880a9d0 | 970 | * Terminate execution abnormally. |
ad37ac8e | 971 | * |
972 | * @param string $code | |
6a488035 TO |
973 | */ |
974 | protected static function abend($code) { | |
975 | // do a hard rollback of any pending transactions | |
976 | // if we've come here, its because of some unexpected PEAR errors | |
977 | CRM_Core_Transaction::forceRollbackIfEnabled(); | |
978 | CRM_Utils_System::civiExit($code); | |
979 | } | |
980 | ||
a0ee3941 | 981 | /** |
3ab5efa9 EM |
982 | * @param array $error |
983 | * @param int $type | |
a0ee3941 EM |
984 | * |
985 | * @return bool | |
986 | */ | |
6a488035 | 987 | public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) { |
8cc574cf | 988 | if (is_array($error) && !empty($error['is_error'])) { |
6a488035 TO |
989 | $code = $error['error_message']['code']; |
990 | if ($code == $type) { | |
991 | return TRUE; | |
992 | } | |
993 | } | |
994 | return FALSE; | |
995 | } | |
96025800 | 996 | |
6a488035 TO |
997 | } |
998 | ||
999 | $e = new PEAR_ErrorStack('CRM'); | |
1000 | $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error'); |