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