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