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