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