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