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