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