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); | |
388 | $content = $template->fetch($config->fatalErrorTemplate); | |
e8cd958c DL |
389 | // JErrorPage exists only in 3.x and not 2.x |
390 | // CRM-13714 | |
391 | if ($config->userFramework == 'Joomla' && class_exists('JErrorPage')) { | |
392 | $error = new Exception($content); | |
393 | JErrorPage::render($error); | |
394 | } | |
395 | else if ($config->userFramework == 'Joomla' && class_exists('JError')) { | |
396 | JError::raiseError('CiviCRM-001', $content); | |
6a488035 | 397 | } |
28c8781b DL |
398 | else { |
399 | echo CRM_Utils_System::theme($content); | |
400 | } | |
6a488035 TO |
401 | |
402 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
403 | } | |
404 | ||
405 | /** | |
406 | * display an error page with an error message describing what happened | |
407 | * | |
408 | * This function is evil -- it largely replicates fatal(). Hopefully the | |
409 | * entire CRM_Core_Error system can be hollowed out and replaced with | |
410 | * something that follows a cleaner separation of concerns. | |
411 | * | |
412 | * @param Exception $exception | |
413 | * | |
414 | * @return void | |
415 | * @static | |
416 | * @acess public | |
417 | */ | |
418 | static function handleUnhandledException($exception) { | |
419 | $config = CRM_Core_Config::singleton(); | |
420 | $vars = array( | |
421 | 'message' => $exception->getMessage(), | |
422 | 'code' => NULL, | |
423 | 'exception' => $exception, | |
424 | ); | |
425 | if (!$vars['message']) { | |
426 | $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/')); | |
427 | } | |
428 | ||
429 | // Case A: CLI | |
430 | if (php_sapi_name() == "cli") { | |
431 | printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']); | |
432 | print self::formatTextException($exception); | |
433 | die("\n"); | |
434 | // FIXME: Why doesn't this call abend()? | |
435 | // Difference: abend() will cleanup transaction and (via civiExit) store session state | |
436 | // self::abend(CRM_Core_Error::FATAL_ERROR); | |
437 | } | |
438 | ||
439 | // Case B: Custom error handler | |
440 | if ($config->fatalErrorHandler && | |
441 | function_exists($config->fatalErrorHandler) | |
442 | ) { | |
443 | $name = $config->fatalErrorHandler; | |
444 | $ret = $name($vars); | |
445 | if ($ret) { | |
446 | // the call has been successfully handled | |
447 | // so we just exit | |
448 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
449 | } | |
450 | } | |
451 | ||
452 | // Case C: Default error handler | |
453 | ||
454 | // log to file | |
455 | CRM_Core_Error::debug_var('Fatal Error Details', $vars); | |
456 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
457 | ||
458 | // print to screen | |
459 | $template = CRM_Core_Smarty::singleton(); | |
460 | $template->assign($vars); | |
461 | $content = $template->fetch($config->fatalErrorTemplate); | |
462 | if ($config->backtrace) { | |
463 | $content = self::formatHtmlException($exception) . $content; | |
464 | } | |
465 | if ($config->userFramework == 'Joomla' && | |
466 | class_exists('JError') | |
467 | ) { | |
468 | JError::raiseError('CiviCRM-001', $content); | |
469 | } | |
470 | else { | |
471 | echo CRM_Utils_System::theme($content); | |
472 | } | |
473 | ||
474 | // fin | |
475 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
476 | } | |
477 | ||
478 | /** | |
479 | * outputs pre-formatted debug information. Flushes the buffers | |
480 | * so we can interrupt a potential POST/redirect | |
481 | * | |
482 | * @param string name of debug section | |
483 | * @param mixed reference to variables that we need a trace of | |
484 | * @param bool should we log or return the output | |
485 | * @param bool whether to generate a HTML-escaped output | |
90154ece DL |
486 | * @param bool should we check permissions before displaying output |
487 | * useful when we die during initialization and permissioning | |
488 | * subsystem is not initialized - CRM-13765 | |
6a488035 TO |
489 | * |
490 | * @return string the generated output | |
491 | * @access public | |
492 | * @static | |
493 | */ | |
90154ece | 494 | static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) { |
6a488035 TO |
495 | $error = self::singleton(); |
496 | ||
497 | if ($variable === NULL) { | |
498 | $variable = $name; | |
499 | $name = NULL; | |
500 | } | |
501 | ||
502 | $out = print_r($variable, TRUE); | |
503 | $prefix = NULL; | |
504 | if ($html) { | |
505 | $out = htmlspecialchars($out); | |
506 | if ($name) { | |
507 | $prefix = "<p>$name</p>"; | |
508 | } | |
509 | $out = "{$prefix}<p><pre>$out</pre></p><p></p>"; | |
510 | } | |
511 | else { | |
512 | if ($name) { | |
513 | $prefix = "$name:\n"; | |
514 | } | |
515 | $out = "{$prefix}$out\n"; | |
516 | } | |
90154ece DL |
517 | if ( |
518 | $log && | |
519 | (!$checkPermission || CRM_Core_Permission::check('view debug output')) | |
520 | ) { | |
6a488035 TO |
521 | echo $out; |
522 | } | |
523 | ||
524 | return $out; | |
525 | } | |
526 | ||
527 | /** | |
528 | * Similar to the function debug. Only difference is | |
529 | * in the formatting of the output. | |
530 | * | |
2a6da8d7 EM |
531 | * @param $variable_name |
532 | * @param $variable | |
533 | * @param bool $print | |
534 | * @param bool $log | |
535 | * @param string $comp variable name | |
536 | * | |
537 | * @internal param \reference $mixed to variables that we need a trace of | |
538 | * @internal param \should $bool we use print_r ? (else we use var_dump) | |
539 | * @internal param \should $bool we log or return the output | |
6a488035 TO |
540 | * |
541 | * @return string the generated output | |
542 | * | |
543 | * @access public | |
544 | * | |
545 | * @static | |
546 | * | |
547 | * @see CRM_Core_Error::debug() | |
548 | * @see CRM_Core_Error::debug_log_message() | |
549 | */ | |
550 | static function debug_var($variable_name, | |
551 | $variable, | |
552 | $print = TRUE, | |
553 | $log = TRUE, | |
554 | $comp = '' | |
555 | ) { | |
556 | // check if variable is set | |
557 | if (!isset($variable)) { | |
558 | $out = "\$$variable_name is not set"; | |
559 | } | |
560 | else { | |
561 | if ($print) { | |
562 | $out = print_r($variable, TRUE); | |
563 | $out = "\$$variable_name = $out"; | |
564 | } | |
565 | else { | |
566 | // use var_dump | |
567 | ob_start(); | |
568 | var_dump($variable); | |
569 | $dump = ob_get_contents(); | |
570 | ob_end_clean(); | |
571 | $out = "\n\$$variable_name = $dump"; | |
572 | } | |
573 | // reset if it is an array | |
574 | if (is_array($variable)) { | |
575 | reset($variable); | |
576 | } | |
577 | } | |
578 | return self::debug_log_message($out, FALSE, $comp); | |
579 | } | |
580 | ||
581 | /** | |
582 | * display the error message on terminal | |
583 | * | |
2a6da8d7 EM |
584 | * @param $message |
585 | * @param bool $out should we log or return the output | |
6a488035 | 586 | * |
2a6da8d7 | 587 | * @param string $comp message to be output |
6a488035 TO |
588 | * @return string format of the backtrace |
589 | * | |
590 | * @access public | |
591 | * | |
592 | * @static | |
593 | */ | |
594 | static function debug_log_message($message, $out = FALSE, $comp = '') { | |
595 | $config = CRM_Core_Config::singleton(); | |
596 | ||
597 | $file_log = self::createDebugLogger($comp); | |
598 | $file_log->log("$message\n"); | |
599 | $str = "<p/><code>$message</code>"; | |
600 | if ($out && CRM_Core_Permission::check('view debug output')) { | |
601 | echo $str; | |
602 | } | |
603 | $file_log->close(); | |
604 | ||
605 | if ($config->userFrameworkLogging) { | |
606 | if ($config->userSystem->is_drupal and function_exists('watchdog')) { | |
607 | watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG); | |
608 | } | |
609 | } | |
610 | ||
611 | return $str; | |
612 | } | |
613 | ||
614 | /** | |
615 | * Append to the query log (if enabled) | |
616 | */ | |
617 | static function debug_query($string) { | |
618 | if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) { | |
619 | if ( CIVICRM_DEBUG_LOG_QUERY == 'backtrace' ) { | |
620 | CRM_Core_Error::backtrace( $string, true ); | |
621 | } else if ( CIVICRM_DEBUG_LOG_QUERY ) { | |
622 | CRM_Core_Error::debug_var( 'Query', $string, false, true ); | |
623 | } | |
624 | } | |
625 | } | |
626 | ||
627 | /** | |
628 | * Obtain a reference to the error log | |
629 | * | |
77b97be7 EM |
630 | * @param string $comp |
631 | * | |
6a488035 TO |
632 | * @return Log |
633 | */ | |
634 | static function createDebugLogger($comp = '') { | |
635 | $config = CRM_Core_Config::singleton(); | |
636 | ||
637 | if ($comp) { | |
638 | $comp = $comp . '.'; | |
639 | } | |
640 | ||
641 | $fileName = "{$config->configAndLogDir}CiviCRM." . $comp . md5($config->dsn) . '.log'; | |
642 | ||
643 | // Roll log file monthly or if greater than 256M | |
644 | // note that PHP file functions have a limit of 2G and hence | |
645 | // the alternative was introduce | |
646 | if (file_exists($fileName)) { | |
647 | $fileTime = date("Ym", filemtime($fileName)); | |
648 | $fileSize = filesize($fileName); | |
649 | if (($fileTime < date('Ym')) || | |
650 | ($fileSize > 256 * 1024 * 1024) || | |
651 | ($fileSize < 0) | |
652 | ) { | |
653 | rename($fileName, | |
654 | $fileName . '.' . date('Ymdhs', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y"))) | |
655 | ); | |
656 | } | |
657 | } | |
658 | ||
659 | return Log::singleton('file', $fileName); | |
660 | } | |
661 | ||
a0ee3941 EM |
662 | /** |
663 | * @param string $msg | |
664 | * @param bool $log | |
665 | */ | |
6a488035 TO |
666 | static function backtrace($msg = 'backTrace', $log = FALSE) { |
667 | $backTrace = debug_backtrace(); | |
668 | $message = self::formatBacktrace($backTrace); | |
669 | if (!$log) { | |
670 | CRM_Core_Error::debug($msg, $message); | |
671 | } | |
672 | else { | |
673 | CRM_Core_Error::debug_var($msg, $message); | |
674 | } | |
675 | } | |
676 | ||
677 | /** | |
678 | * Render a backtrace array as a string | |
679 | * | |
680 | * @param array $backTrace array of stack frames | |
681 | * @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 | |
682 | * @param int $maxArgLen maximum number of characters to show from each argument string | |
683 | * @return string printable plain-text | |
6a488035 TO |
684 | */ |
685 | static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) { | |
686 | $message = ''; | |
34866662 CW |
687 | foreach (self::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) { |
688 | $message .= sprintf("#%s %s\n", $idx, $trace); | |
689 | } | |
690 | $message .= sprintf("#%s {main}\n", 1+$idx); | |
691 | return $message; | |
692 | } | |
693 | ||
694 | /** | |
695 | * Render a backtrace array as an array | |
696 | * | |
697 | * @param array $backTrace array of stack frames | |
698 | * @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 | |
699 | * @param int $maxArgLen maximum number of characters to show from each argument string | |
700 | * @return array | |
701 | * @see debug_backtrace | |
702 | * @see Exception::getTrace() | |
703 | */ | |
704 | static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) { | |
705 | $ret = array(); | |
706 | foreach ($backTrace as $trace) { | |
6a488035 TO |
707 | $args = array(); |
708 | $fnName = CRM_Utils_Array::value('function', $trace); | |
34866662 | 709 | $className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : ''; |
6a488035 TO |
710 | |
711 | // do now show args for a few password related functions | |
712 | $skipArgs = ($className == 'DB::' && $fnName == 'connect') ? TRUE : FALSE; | |
713 | ||
714 | foreach ($trace['args'] as $arg) { | |
715 | if (! $showArgs || $skipArgs) { | |
716 | $args[] = '(' . gettype($arg) . ')'; | |
717 | continue; | |
718 | } | |
719 | switch ($type = gettype($arg)) { | |
720 | case 'boolean': | |
721 | $args[] = $arg ? 'TRUE' : 'FALSE'; | |
722 | break; | |
723 | case 'integer': | |
724 | case 'double': | |
725 | $args[] = $arg; | |
726 | break; | |
727 | case 'string': | |
728 | $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"'; | |
729 | break; | |
730 | case 'array': | |
731 | $args[] = '(Array:'.count($arg).')'; | |
732 | break; | |
733 | case 'object': | |
734 | $args[] = 'Object(' . get_class($arg) . ')'; | |
735 | break; | |
736 | case 'resource': | |
737 | $args[] = 'Resource'; | |
738 | break; | |
739 | case 'NULL': | |
740 | $args[] = 'NULL'; | |
741 | break; | |
742 | default: | |
743 | $args[] = "($type)"; | |
744 | break; | |
745 | } | |
746 | } | |
747 | ||
34866662 CW |
748 | $ret[] = sprintf( |
749 | "%s(%s): %s%s(%s)", | |
6a488035 TO |
750 | CRM_Utils_Array::value('file', $trace, '[internal function]'), |
751 | CRM_Utils_Array::value('line', $trace, ''), | |
752 | $className, | |
753 | $fnName, | |
754 | implode(", ", $args) | |
755 | ); | |
756 | } | |
34866662 | 757 | return $ret; |
6a488035 TO |
758 | } |
759 | ||
760 | /** | |
761 | * Render an exception as HTML string | |
762 | * | |
763 | * @param Exception $e | |
764 | * @return string printable HTML text | |
765 | */ | |
766 | static function formatHtmlException(Exception $e) { | |
767 | $msg = ''; | |
768 | ||
769 | // Exception metadata | |
770 | ||
771 | // Exception backtrace | |
772 | if ($e instanceof PEAR_Exception) { | |
773 | $ei = $e; | |
774 | while (is_callable(array($ei, 'getCause'))) { | |
775 | if ($ei->getCause() instanceof PEAR_Error) { | |
776 | $msg .= '<table class="crm-db-error">'; | |
777 | $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value')); | |
778 | $msg .= '<tbody>'; | |
779 | foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) { | |
780 | $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f"))); | |
781 | } | |
782 | $msg .= '</tbody></table>'; | |
783 | } | |
784 | $ei = $ei->getCause(); | |
785 | } | |
786 | $msg .= $e->toHtml(); | |
787 | } else { | |
788 | $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>'; | |
789 | $msg .= '<pre>' . htmlentities(self::formatBacktrace($e->getTrace())) . '</pre>'; | |
790 | } | |
791 | return $msg; | |
792 | } | |
793 | ||
794 | /** | |
795 | * Write details of an exception to the log | |
796 | * | |
797 | * @param Exception $e | |
798 | * @return string printable plain text | |
799 | */ | |
800 | static function formatTextException(Exception $e) { | |
801 | $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n"; | |
802 | ||
803 | $ei = $e; | |
804 | while (is_callable(array($ei, 'getCause'))) { | |
805 | if ($ei->getCause() instanceof PEAR_Error) { | |
806 | foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) { | |
807 | $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f"))); | |
808 | } | |
809 | } | |
810 | $ei = $ei->getCause(); | |
811 | } | |
812 | $msg .= self::formatBacktrace($e->getTrace()); | |
813 | return $msg; | |
814 | } | |
815 | ||
a0ee3941 EM |
816 | /** |
817 | * @param $message | |
818 | * @param int $code | |
819 | * @param string $level | |
820 | * @param null $params | |
821 | * | |
822 | * @return object | |
823 | */ | |
6a488035 TO |
824 | static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) { |
825 | $error = CRM_Core_Error::singleton(); | |
826 | $error->push($code, $level, array($params), $message); | |
827 | return $error; | |
828 | } | |
829 | ||
830 | /** | |
831 | * Set a status message in the session, then bounce back to the referrer. | |
832 | * | |
2a6da8d7 | 833 | * @param string $status The status message to set |
6a488035 | 834 | * |
2a6da8d7 EM |
835 | * @param null $redirect |
836 | * @param string $title | |
6a488035 TO |
837 | * @return void |
838 | * @access public | |
839 | * @static | |
840 | */ | |
dcc4f6a7 | 841 | public static function statusBounce($status, $redirect = NULL, $title = '') { |
6a488035 TO |
842 | $session = CRM_Core_Session::singleton(); |
843 | if (!$redirect) { | |
844 | $redirect = $session->readUserContext(); | |
845 | } | |
dcc4f6a7 | 846 | $session->setStatus($status, $title); |
34866662 CW |
847 | if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) { |
848 | CRM_Core_Page_AJAX::returnJsonResponse(array('status' => 'error')); | |
849 | } | |
6a488035 TO |
850 | CRM_Utils_System::redirect($redirect); |
851 | } | |
852 | ||
853 | /** | |
854 | * Function to reset the error stack | |
855 | * | |
856 | * @access public | |
857 | * @static | |
858 | */ | |
859 | public static function reset() { | |
860 | $error = self::singleton(); | |
861 | $error->_errors = array(); | |
862 | $error->_errorsByLevel = array(); | |
863 | } | |
864 | ||
6a4257d4 | 865 | /** |
42c0daee TO |
866 | * PEAR error-handler which converts errors to exceptions |
867 | * | |
868 | * @param $pearError | |
869 | * @throws PEAR_Exception | |
6a4257d4 | 870 | */ |
6a488035 TO |
871 | public static function exceptionHandler($pearError) { |
872 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
873 | throw new PEAR_Exception($pearError->getMessage(), $pearError); | |
874 | } | |
875 | ||
876 | /** | |
42c0daee | 877 | * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport. |
6a488035 TO |
878 | * |
879 | * @param object $obj The PEAR_ERROR object | |
6a488035 TO |
880 | * @return object $obj |
881 | * @access public | |
882 | * @static | |
883 | */ | |
884 | public static function nullHandler($obj) { | |
885 | CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}"); | |
886 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
887 | return $obj; | |
888 | } | |
889 | ||
6a488035 TO |
890 | /* |
891 | * @deprecated | |
892 | * This function is no longer used by v3 api. | |
893 | * @fixme Some core files call it but it should be re-thought & renamed or removed | |
894 | */ | |
a0ee3941 EM |
895 | /** |
896 | * @param $msg | |
897 | * @param null $data | |
898 | * | |
899 | * @return array | |
900 | * @throws Exception | |
901 | */ | |
6a488035 TO |
902 | public static function &createAPIError($msg, $data = NULL) { |
903 | if (self::$modeException) { | |
904 | throw new Exception($msg, $data); | |
905 | } | |
906 | ||
907 | $values = array(); | |
908 | ||
909 | $values['is_error'] = 1; | |
910 | $values['error_message'] = $msg; | |
911 | if (isset($data)) { | |
912 | $values = array_merge($values, $data); | |
913 | } | |
914 | return $values; | |
915 | } | |
916 | ||
a0ee3941 EM |
917 | /** |
918 | * @param $file | |
919 | */ | |
6a488035 TO |
920 | public static function movedSiteError($file) { |
921 | $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend', | |
922 | 'reset=1', | |
923 | TRUE | |
924 | ); | |
925 | echo "We could not write $file. Have you moved your site directory or server?<p>"; | |
926 | echo "Please fix the setting by running the <a href=\"$url\">update config script</a>"; | |
927 | exit(); | |
928 | } | |
929 | ||
930 | /** | |
931 | * Terminate execution abnormally | |
932 | */ | |
933 | protected static function abend($code) { | |
934 | // do a hard rollback of any pending transactions | |
935 | // if we've come here, its because of some unexpected PEAR errors | |
936 | CRM_Core_Transaction::forceRollbackIfEnabled(); | |
937 | CRM_Utils_System::civiExit($code); | |
938 | } | |
939 | ||
a0ee3941 EM |
940 | /** |
941 | * @param $error | |
942 | * @param const $type | |
943 | * | |
944 | * @return bool | |
945 | */ | |
6a488035 | 946 | public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) { |
8cc574cf | 947 | if (is_array($error) && !empty($error['is_error'])) { |
6a488035 TO |
948 | $code = $error['error_message']['code']; |
949 | if ($code == $type) { | |
950 | return TRUE; | |
951 | } | |
952 | } | |
953 | return FALSE; | |
954 | } | |
955 | } | |
956 | ||
957 | $e = new PEAR_ErrorStack('CRM'); | |
958 | $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error'); |