Commit | Line | Data |
---|---|---|
6a488035 | 1 | <?php |
6a488035 TO |
2 | /* |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
6a488035 | 5 | | | |
bc77d7c0 TO |
6 | | This work is published under the GNU AGPLv3 license with some | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
6a488035 | 9 | +--------------------------------------------------------------------+ |
d25dd0ee | 10 | */ |
6a488035 TO |
11 | |
12 | /** | |
13 | * Start of the Error framework. We should check out and inherit from | |
14 | * PEAR_ErrorStack and use that framework | |
15 | * | |
16 | * @package CRM | |
ca5cec67 | 17 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
6a488035 TO |
18 | */ |
19 | ||
20 | require_once 'PEAR/ErrorStack.php'; | |
21 | require_once 'PEAR/Exception.php'; | |
dcc4f6a7 | 22 | require_once 'CRM/Core/Exception.php'; |
6a488035 | 23 | |
df8de0eb SL |
24 | require_once 'Log.php'; |
25 | ||
a0ee3941 EM |
26 | /** |
27 | * Class CRM_Core_Error | |
28 | */ | |
6a488035 TO |
29 | class CRM_Core_Error extends PEAR_ErrorStack { |
30 | ||
31 | /** | |
0880a9d0 | 32 | * Status code of various types of errors. |
6a488035 | 33 | */ |
7da04cde TO |
34 | const FATAL_ERROR = 2; |
35 | const DUPLICATE_CONTACT = 8001; | |
36 | const DUPLICATE_CONTRIBUTION = 8002; | |
37 | const DUPLICATE_PARTICIPANT = 8003; | |
6a488035 TO |
38 | |
39 | /** | |
40 | * We only need one instance of this object. So we use the singleton | |
41 | * pattern and cache the instance in this variable | |
42 | * @var object | |
6a488035 TO |
43 | */ |
44 | private static $_singleton = NULL; | |
45 | ||
46 | /** | |
d09edf64 | 47 | * The logger object for this application. |
6a488035 | 48 | * @var object |
6a488035 TO |
49 | */ |
50 | private static $_log = NULL; | |
51 | ||
52 | /** | |
53 | * If modeException == true, errors are raised as exception instead of returning civicrm_errors | |
518fa0ee | 54 | * @var bool |
6a488035 TO |
55 | */ |
56 | public static $modeException = NULL; | |
57 | ||
58 | /** | |
100fef9d | 59 | * Singleton function used to manage this object. |
6a488035 | 60 | * |
dd244018 EM |
61 | * @param null $package |
62 | * @param bool $msgCallback | |
63 | * @param bool $contextCallback | |
64 | * @param bool $throwPEAR_Error | |
65 | * @param string $stackClass | |
66 | * | |
30208fab | 67 | * @return CRM_Core_Error |
6a488035 | 68 | */ |
2aa397bc | 69 | public static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') { |
6a488035 TO |
70 | if (self::$_singleton === NULL) { |
71 | self::$_singleton = new CRM_Core_Error('CiviCRM'); | |
72 | } | |
73 | return self::$_singleton; | |
74 | } | |
75 | ||
76 | /** | |
0880a9d0 | 77 | * Constructor. |
6a488035 | 78 | */ |
00be9182 | 79 | public function __construct() { |
6a488035 TO |
80 | parent::__construct('CiviCRM'); |
81 | ||
82 | $log = CRM_Core_Config::getLog(); | |
83 | $this->setLogger($log); | |
84 | ||
a6272a48 | 85 | // PEAR<=1.9.0 does not declare "static" properly. |
be2fb01f CW |
86 | if (!is_callable(['PEAR', '__callStatic'])) { |
87 | $this->setDefaultCallback([$this, 'handlePES']); | |
a6272a48 TO |
88 | } |
89 | else { | |
be2fb01f | 90 | PEAR_ErrorStack::setDefaultCallback([$this, 'handlePES']); |
a6272a48 | 91 | } |
6a488035 TO |
92 | } |
93 | ||
a0ee3941 EM |
94 | /** |
95 | * @param $error | |
96 | * @param string $separator | |
97 | * | |
98 | * @return array|null|string | |
99 | */ | |
518fa0ee | 100 | public static function getMessages(&$error, $separator = '<br />') { |
6a488035 TO |
101 | if (is_a($error, 'CRM_Core_Error')) { |
102 | $errors = $error->getErrors(); | |
be2fb01f | 103 | $message = []; |
6a488035 TO |
104 | foreach ($errors as $e) { |
105 | $message[] = $e['code'] . ': ' . $e['message']; | |
106 | } | |
107 | $message = implode($separator, $message); | |
108 | return $message; | |
109 | } | |
31176a73 SP |
110 | elseif (is_a($error, 'Civi\Payment\Exception\PaymentProcessorException')) { |
111 | return $error->getMessage(); | |
112 | } | |
6a488035 TO |
113 | return NULL; |
114 | } | |
115 | ||
dbddfb08 | 116 | /** |
0880a9d0 | 117 | * Status display function specific to payment processor errors. |
dbddfb08 EM |
118 | * @param $error |
119 | * @param string $separator | |
120 | */ | |
00be9182 | 121 | public static function displaySessionError(&$error, $separator = '<br />') { |
6a488035 TO |
122 | $message = self::getMessages($error, $separator); |
123 | if ($message) { | |
124 | $status = ts("Payment Processor Error message") . "{$separator} $message"; | |
125 | $session = CRM_Core_Session::singleton(); | |
126 | $session->setStatus($status); | |
127 | } | |
128 | } | |
129 | ||
130 | /** | |
100fef9d | 131 | * Create the main callback method. this method centralizes error processing. |
6a488035 TO |
132 | * |
133 | * the errors we expect are from the pear modules DB, DB_DataObject | |
134 | * which currently use PEAR::raiseError to notify of error messages. | |
135 | * | |
3bdca100 | 136 | * @param object $pearError PEAR_Error |
6a488035 TO |
137 | */ |
138 | public static function handle($pearError) { | |
2b2c4099 TO |
139 | if (defined('CIVICRM_TEST')) { |
140 | return self::simpleHandler($pearError); | |
141 | } | |
6a488035 TO |
142 | |
143 | // setup smarty with config, session and template location. | |
144 | $template = CRM_Core_Smarty::singleton(); | |
145 | $config = CRM_Core_Config::singleton(); | |
146 | ||
147 | if ($config->backtrace) { | |
148 | self::backtrace(); | |
149 | } | |
150 | ||
151 | // create the error array | |
ca8416c8 | 152 | $error = self::getErrorDetails($pearError); |
2e4ade96 TO |
153 | |
154 | // We access connection info via _DB_DATAOBJECT instead | |
155 | // of, e.g., calling getDatabaseConnection(), so that we | |
156 | // can avoid infinite loops. | |
157 | global $_DB_DATAOBJECT; | |
158 | ||
0828e4ad | 159 | if (isset($_DB_DATAOBJECT['CONFIG']['database'])) { |
6a488035 | 160 | $dao = new CRM_Core_DAO(); |
6a488035 TO |
161 | if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5])) { |
162 | $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5]; | |
6a488035 | 163 | |
0828e4ad TO |
164 | // FIXME: Polymorphism for the win. |
165 | if ($conn instanceof DB_mysqli) { | |
166 | $link = $conn->connection; | |
167 | if (mysqli_error($link)) { | |
168 | $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link); | |
518fa0ee SL |
169 | // execute a dummy query to clear error stack |
170 | mysqli_query($link, 'select 1'); | |
0828e4ad TO |
171 | } |
172 | } | |
173 | elseif ($conn instanceof DB_mysql) { | |
174 | if (mysql_error()) { | |
175 | $mysql_error = mysql_error() . ', ' . mysql_errno(); | |
518fa0ee SL |
176 | // execute a dummy query to clear error stack |
177 | mysql_query('select 1'); | |
0828e4ad TO |
178 | } |
179 | } | |
180 | else { | |
181 | $mysql_error = 'fixme-unknown-db-cxn'; | |
6a488035 | 182 | } |
0828e4ad | 183 | $template->assign_by_ref('mysql_code', $mysql_error); |
6a488035 TO |
184 | } |
185 | } | |
186 | ||
67bb87ed MW |
187 | // Use the custom fatalErrorHandler if defined |
188 | if ($config->fatalErrorHandler && function_exists($config->fatalErrorHandler)) { | |
189 | $name = $config->fatalErrorHandler; | |
190 | $vars = [ | |
191 | 'pearError' => $pearError, | |
192 | ]; | |
193 | $ret = $name($vars); | |
194 | if ($ret) { | |
195 | // the call has been successfully handled so we just exit | |
196 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
197 | } | |
198 | } | |
199 | ||
6a488035 TO |
200 | $template->assign_by_ref('error', $error); |
201 | $errorDetails = CRM_Core_Error::debug('', $error, FALSE); | |
202 | $template->assign_by_ref('errorDetails', $errorDetails); | |
203 | ||
120f8e64 | 204 | CRM_Core_Error::debug_var('Fatal Error Details', $error, TRUE, TRUE, '', PEAR_LOG_ERR); |
6a488035 TO |
205 | CRM_Core_Error::backtrace('backTrace', TRUE); |
206 | ||
b7760d30 | 207 | $exit = TRUE; |
6a488035 TO |
208 | if ($config->initialized) { |
209 | $content = $template->fetch('CRM/common/fatal.tpl'); | |
210 | echo CRM_Utils_System::theme($content); | |
8be79db7 | 211 | $exit = CRM_Utils_System::shouldExitAfterFatal(); |
6a488035 TO |
212 | } |
213 | else { | |
214 | echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>"; | |
215 | CRM_Core_Error::debug(NULL, $error); | |
216 | } | |
3a210ec0 E |
217 | static $runOnce = FALSE; |
218 | if ($runOnce) { | |
219 | exit; | |
220 | } | |
221 | $runOnce = TRUE; | |
8be79db7 BT |
222 | |
223 | if ($exit) { | |
224 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
225 | } | |
226 | else { | |
227 | self::inpageExceptionDisplay(CRM_Core_Error::FATAL_ERROR); | |
228 | } | |
6a488035 TO |
229 | } |
230 | ||
a0ee3941 | 231 | /** |
4f1f1f2a CW |
232 | * this function is used to trap and print errors |
233 | * during system initialization time. Hence the error | |
234 | * message is quite ugly | |
235 | * | |
a0ee3941 EM |
236 | * @param $pearError |
237 | */ | |
6a488035 TO |
238 | public static function simpleHandler($pearError) { |
239 | ||
ca8416c8 | 240 | $error = self::getErrorDetails($pearError); |
241 | ||
242 | // ensure that debug does not check permissions since we are in bootstrap | |
243 | // mode and need to print a decent message to help the user | |
244 | CRM_Core_Error::debug('Initialization Error', $error, TRUE, TRUE, FALSE); | |
245 | ||
246 | // always log the backtrace to a file | |
247 | self::backtrace('backTrace', TRUE); | |
248 | ||
249 | exit(0); | |
250 | } | |
251 | ||
252 | /** | |
3fd42bb5 | 253 | * This function is used to return error details |
ca8416c8 | 254 | * |
3fd42bb5 | 255 | * @param PEAR_Error $pearError |
ca8416c8 | 256 | * |
257 | * @return array $error | |
258 | */ | |
259 | public static function getErrorDetails($pearError) { | |
6a488035 | 260 | // create the error array |
be2fb01f | 261 | $error = []; |
353ffa53 TO |
262 | $error['callback'] = $pearError->getCallback(); |
263 | $error['code'] = $pearError->getCode(); | |
264 | $error['message'] = $pearError->getMessage(); | |
265 | $error['mode'] = $pearError->getMode(); | |
6a488035 | 266 | $error['debug_info'] = $pearError->getDebugInfo(); |
353ffa53 TO |
267 | $error['type'] = $pearError->getType(); |
268 | $error['user_info'] = $pearError->getUserInfo(); | |
269 | $error['to_string'] = $pearError->toString(); | |
6a488035 | 270 | |
ca8416c8 | 271 | return $error; |
6a488035 TO |
272 | } |
273 | ||
274 | /** | |
275 | * Handle errors raised using the PEAR Error Stack. | |
276 | * | |
277 | * currently the handler just requests the PES framework | |
278 | * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH). | |
279 | * | |
280 | * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE. | |
281 | * | |
282 | * Also, if we do not return any value the PEAR_ErrorStack::push() then does the | |
283 | * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen, | |
284 | * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog(); | |
ea3ddccf | 285 | * |
286 | * @param mixed $pearError | |
287 | * | |
288 | * @return int | |
6a488035 TO |
289 | */ |
290 | public static function handlePES($pearError) { | |
291 | return PEAR_ERRORSTACK_PUSH; | |
292 | } | |
293 | ||
294 | /** | |
0880a9d0 | 295 | * Display an error page with an error message describing what happened. |
6a488035 | 296 | * |
c6b9b29d CB |
297 | * @deprecated |
298 | * This is a really annoying function. We ❤ exceptions. Be exceptional! | |
299 | * | |
300 | * @see CRM-20181 | |
301 | * | |
6a0b768e TO |
302 | * @param string $message |
303 | * The error message. | |
304 | * @param string $code | |
305 | * The error code if any. | |
306 | * @param string $email | |
307 | * The email address to notify of this situation. | |
77b97be7 EM |
308 | * |
309 | * @throws Exception | |
6a488035 | 310 | */ |
00be9182 | 311 | public static function fatal($message = NULL, $code = NULL, $email = NULL) { |
33968e94 | 312 | CRM_Core_Error::deprecatedFunctionWarning('throw new CRM_Core_Exception or use CRM_Core_Error::statusBounce', 'CRM_Core_Error::fatal'); |
be2fb01f | 313 | $vars = [ |
84509850 | 314 | 'message' => $message, |
6a488035 | 315 | 'code' => $code, |
be2fb01f | 316 | ]; |
6a488035 TO |
317 | |
318 | if (self::$modeException) { | |
319 | // CRM-11043 | |
120f8e64 | 320 | CRM_Core_Error::debug_var('Fatal Error Details', $vars, TRUE, TRUE, '', PEAR_LOG_ERR); |
6a488035 TO |
321 | CRM_Core_Error::backtrace('backTrace', TRUE); |
322 | ||
323 | $details = 'A fatal error was triggered'; | |
324 | if ($message) { | |
325 | $details .= ': ' . $message; | |
2aa397bc | 326 | } |
6a488035 TO |
327 | throw new Exception($details, $code); |
328 | } | |
329 | ||
330 | if (!$message) { | |
be2fb01f | 331 | $message = ts('We experienced an unexpected error. You may have found a bug. For more information on how to provide a bug report, please read: %1', [1 => 'https://civicrm.org/bug-reporting']); |
6a488035 TO |
332 | } |
333 | ||
334 | if (php_sapi_name() == "cli") { | |
335 | print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n"); | |
0c4a3d8b | 336 | // Fix for CRM-16899 |
4c68cf7b | 337 | echo static::formatBacktrace(debug_backtrace()); |
6a488035 TO |
338 | die("\n"); |
339 | // FIXME: Why doesn't this call abend()? | |
340 | // Difference: abend() will cleanup transaction and (via civiExit) store session state | |
341 | // self::abend(CRM_Core_Error::FATAL_ERROR); | |
342 | } | |
343 | ||
344 | $config = CRM_Core_Config::singleton(); | |
345 | ||
346 | if ($config->fatalErrorHandler && | |
347 | function_exists($config->fatalErrorHandler) | |
348 | ) { | |
349 | $name = $config->fatalErrorHandler; | |
350 | $ret = $name($vars); | |
351 | if ($ret) { | |
352 | // the call has been successfully handled | |
353 | // so we just exit | |
354 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
355 | } | |
356 | } | |
357 | ||
25dc2153 PH |
358 | if ($config->backtrace) { |
359 | self::backtrace(); | |
360 | } | |
361 | ||
120f8e64 | 362 | CRM_Core_Error::debug_var('Fatal Error Details', $vars, TRUE, TRUE, '', PEAR_LOG_ERR); |
25dc2153 PH |
363 | CRM_Core_Error::backtrace('backTrace', TRUE); |
364 | ||
34866662 CW |
365 | // If we are in an ajax callback, format output appropriately |
366 | if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) { | |
be2fb01f | 367 | $out = [ |
34866662 | 368 | 'status' => 'fatal', |
34d6cec4 | 369 | 'content' => '<div class="messages status no-popup">' . CRM_Core_Page::crmIcon('fa-info-circle') . ' ' . ts('Sorry but we are not able to provide this at the moment.') . '</div>', |
be2fb01f | 370 | ]; |
34866662 CW |
371 | if ($config->backtrace && CRM_Core_Permission::check('view debug output')) { |
372 | $out['backtrace'] = self::parseBacktrace(debug_backtrace()); | |
373 | $message .= '<p><em>See console for backtrace</em></p>'; | |
374 | } | |
1528ac1d | 375 | CRM_Core_Session::setStatus($message, ts('Sorry an error occurred'), 'error'); |
34866662 CW |
376 | CRM_Core_Transaction::forceRollbackIfEnabled(); |
377 | CRM_Core_Page_AJAX::returnJsonResponse($out); | |
378 | } | |
379 | ||
6a488035 TO |
380 | $template = CRM_Core_Smarty::singleton(); |
381 | $template->assign($vars); | |
f431d51f | 382 | $config->userSystem->outputError($template->fetch('CRM/common/fatal.tpl')); |
6a488035 TO |
383 | |
384 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
385 | } | |
386 | ||
387 | /** | |
0880a9d0 | 388 | * Display an error page with an error message describing what happened. |
6a488035 TO |
389 | * |
390 | * This function is evil -- it largely replicates fatal(). Hopefully the | |
391 | * entire CRM_Core_Error system can be hollowed out and replaced with | |
392 | * something that follows a cleaner separation of concerns. | |
393 | * | |
394 | * @param Exception $exception | |
6a488035 | 395 | */ |
00be9182 | 396 | public static function handleUnhandledException($exception) { |
4b57bc9f EM |
397 | try { |
398 | CRM_Utils_Hook::unhandledException($exception); | |
0db6c3e1 TO |
399 | } |
400 | catch (Exception $other) { | |
4b57bc9f | 401 | // if the exception-handler generates an exception, then that sucks! oh, well. carry on. |
120f8e64 | 402 | CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other), TRUE, TRUE, '', PEAR_LOG_ERR); |
4b57bc9f | 403 | } |
6a488035 | 404 | $config = CRM_Core_Config::singleton(); |
be2fb01f | 405 | $vars = [ |
6a488035 TO |
406 | 'message' => $exception->getMessage(), |
407 | 'code' => NULL, | |
408 | 'exception' => $exception, | |
be2fb01f | 409 | ]; |
6a488035 | 410 | if (!$vars['message']) { |
be2fb01f | 411 | $vars['message'] = ts('We experienced an unexpected error. You may have found a bug. For more information on how to provide a bug report, please read: %1', [1 => 'https://civicrm.org/bug-reporting']); |
6a488035 TO |
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 | |
120f8e64 | 440 | CRM_Core_Error::debug_var('Fatal Error Details', $vars, FALSE, TRUE, '', PEAR_LOG_ERR); |
6a488035 TO |
441 | CRM_Core_Error::backtrace('backTrace', TRUE); |
442 | ||
443 | // print to screen | |
444 | $template = CRM_Core_Smarty::singleton(); | |
445 | $template->assign($vars); | |
f431d51f | 446 | $content = $template->fetch('CRM/common/fatal.tpl'); |
2dae8a18 | 447 | |
6a488035 TO |
448 | if ($config->backtrace) { |
449 | $content = self::formatHtmlException($exception) . $content; | |
450 | } | |
2dae8a18 AT |
451 | |
452 | echo CRM_Utils_System::theme($content); | |
8be79db7 | 453 | $exit = CRM_Utils_System::shouldExitAfterFatal(); |
6a488035 | 454 | |
8be79db7 BT |
455 | if ($exit) { |
456 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
457 | } | |
458 | else { | |
459 | self::inpageExceptionDisplay(CRM_Core_Error::FATAL_ERROR); | |
460 | } | |
6a488035 TO |
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 | * | |
3bdca100 | 467 | * @param string $name name of debug section |
a2f24340 | 468 | * @param mixed $variable reference to variables that we need a trace of |
3bdca100 | 469 | * @param bool $log should we log or return the output |
470 | * @param bool $html whether to generate a HTML-escaped output | |
471 | * @param bool $checkPermission should we check permissions before displaying output | |
90154ece DL |
472 | * useful when we die during initialization and permissioning |
473 | * subsystem is not initialized - CRM-13765 | |
6a488035 | 474 | * |
a6c01b45 CW |
475 | * @return string |
476 | * the generated output | |
6a488035 | 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 | 515 | * @param string $variable_name |
6b5c5203 | 516 | * Variable name. |
c490a46a | 517 | * @param mixed $variable |
6b5c5203 | 518 | * Variable value. |
6a0b768e | 519 | * @param bool $print |
6b5c5203 | 520 | * Use print_r (if true) or var_dump (if false). |
6a0b768e | 521 | * @param bool $log |
6b5c5203 CB |
522 | * Log or return the output? |
523 | * @param string $prefix | |
524 | * Prefix for output logfile. | |
120f8e64 | 525 | * @param int $priority |
526 | * The log priority level. | |
2a6da8d7 | 527 | * |
a6c01b45 | 528 | * @return string |
6b5c5203 | 529 | * The generated output |
6a488035 TO |
530 | * |
531 | * @see CRM_Core_Error::debug() | |
532 | * @see CRM_Core_Error::debug_log_message() | |
533 | */ | |
120f8e64 | 534 | public static function debug_var($variable_name, $variable, $print = TRUE, $log = TRUE, $prefix = '', $priority = NULL) { |
6a488035 TO |
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 { | |
10e59978 | 545 | // Use Symfony var-dumper to avoid circular references that exhaust |
546 | // memory when using var_dump(). | |
547 | // Use its CliDumper since if we use the simpler `dump()` then it | |
548 | // comes out as some overly decorated html which is hard to read. | |
549 | $dump = (new \Symfony\Component\VarDumper\Dumper\CliDumper('php://output')) | |
550 | ->dump( | |
551 | (new \Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($variable), | |
552 | TRUE); | |
6a488035 TO |
553 | $out = "\n\$$variable_name = $dump"; |
554 | } | |
555 | // reset if it is an array | |
556 | if (is_array($variable)) { | |
557 | reset($variable); | |
558 | } | |
559 | } | |
120f8e64 | 560 | return self::debug_log_message($out, FALSE, $prefix, $priority); |
6a488035 TO |
561 | } |
562 | ||
563 | /** | |
edc8adfc | 564 | * Display the error message on terminal and append it to the log file. |
565 | * | |
566 | * Provided the user has the 'view debug output' the output should be displayed. In all | |
567 | * cases it should be logged. | |
6a488035 | 568 | * |
ea3ddccf | 569 | * @param string $message |
6a0b768e TO |
570 | * @param bool $out |
571 | * Should we log or return the output. | |
6a488035 | 572 | * |
6b5c5203 CB |
573 | * @param string $prefix |
574 | * Message prefix. | |
ea3ddccf | 575 | * @param string $priority |
6a488035 | 576 | * |
ea3ddccf | 577 | * @return string |
578 | * Format of the backtrace | |
6a488035 | 579 | */ |
6b5c5203 | 580 | public static function debug_log_message($message, $out = FALSE, $prefix = '', $priority = NULL) { |
213a5f19 | 581 | $config = CRM_Core_Config::singleton(); |
6a488035 | 582 | |
6b5c5203 | 583 | $file_log = self::createDebugLogger($prefix); |
6e5ad5ee | 584 | $file_log->log("$message\n", $priority); |
0ac9fd52 | 585 | |
9726c118 | 586 | $str = '<p/><code>' . htmlspecialchars($message) . '</code>'; |
6a488035 TO |
587 | if ($out && CRM_Core_Permission::check('view debug output')) { |
588 | echo $str; | |
589 | } | |
590 | $file_log->close(); | |
591 | ||
21ce4627 | 592 | if (!isset(\Civi::$statics[__CLASS__]['userFrameworkLogging'])) { |
593 | // Set it to FALSE first & then try to set it. This is to prevent a loop as calling | |
594 | // $config->userFrameworkLogging can trigger DB queries & under log mode this | |
595 | // then gets called again. | |
596 | \Civi::$statics[__CLASS__]['userFrameworkLogging'] = FALSE; | |
597 | \Civi::$statics[__CLASS__]['userFrameworkLogging'] = $config->userFrameworkLogging; | |
598 | } | |
599 | ||
600 | if (!empty(\Civi::$statics[__CLASS__]['userFrameworkLogging'])) { | |
1fadd891 | 601 | // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why |
213a5f19 | 602 | if ($config->userSystem->is_drupal and function_exists('watchdog')) { |
2e1f50d6 | 603 | watchdog('civicrm', '%message', ['%message' => $message], $priority ?? WATCHDOG_DEBUG); |
213a5f19 | 604 | } |
6f12b344 | 605 | elseif ($config->userSystem->is_drupal and CIVICRM_UF == 'Drupal8') { |
75f08499 | 606 | \Drupal::logger('civicrm')->log($priority ?? \Drupal\Core\Logger\RfcLogLevel::DEBUG, '%message', ['%message' => $message]); |
b6cda82a | 607 | } |
213a5f19 | 608 | } |
6a488035 TO |
609 | |
610 | return $str; | |
611 | } | |
612 | ||
613 | /** | |
614 | * Append to the query log (if enabled) | |
ad37ac8e | 615 | * |
616 | * @param string $string | |
6a488035 | 617 | */ |
00be9182 | 618 | public static function debug_query($string) { |
f9920e29 | 619 | $debugLogQuery = CRM_Utils_Constant::value('CIVICRM_DEBUG_LOG_QUERY', FALSE); |
620 | if ($debugLogQuery === 'backtrace') { | |
fbebca7a | 621 | CRM_Core_Error::backtrace($string, TRUE); |
622 | } | |
f9920e29 | 623 | elseif ($debugLogQuery) { |
624 | CRM_Core_Error::debug_var('Query', $string, TRUE, TRUE, 'sql_log' . $debugLogQuery, PEAR_LOG_DEBUG); | |
6a488035 TO |
625 | } |
626 | } | |
627 | ||
d090b80b TO |
628 | /** |
629 | * Execute a query and log the results. | |
630 | * | |
631 | * @param string $query | |
632 | */ | |
00be9182 | 633 | public static function debug_query_result($query) { |
7d0b8a47 | 634 | $results = CRM_Core_DAO::executeQuery($query)->fetchAll(); |
120f8e64 | 635 | CRM_Core_Error::debug_var('dao result', ['query' => $query, 'results' => $results], TRUE, TRUE, '', PEAR_LOG_DEBUG); |
d090b80b TO |
636 | } |
637 | ||
6a488035 | 638 | /** |
0880a9d0 | 639 | * Obtain a reference to the error log. |
6a488035 | 640 | * |
edc8adfc | 641 | * @param string $prefix |
77b97be7 | 642 | * |
2aafb0fc | 643 | * @return Log_file |
6a488035 | 644 | */ |
edc8adfc | 645 | public static function createDebugLogger($prefix = '') { |
646 | self::generateLogFileName($prefix); | |
647 | return Log::singleton('file', \Civi::$statics[__CLASS__]['logger_file' . $prefix], ''); | |
648 | } | |
649 | ||
44c32d0a CB |
650 | /** |
651 | * Generate a hash for the logfile. | |
bf48aa29 | 652 | * |
44c32d0a | 653 | * CRM-13640. |
bf48aa29 | 654 | * |
655 | * @param CRM_Core_Config $config | |
656 | * | |
657 | * @return string | |
44c32d0a | 658 | */ |
f0f1e508 CB |
659 | public static function generateLogFileHash($config) { |
660 | // Use multiple (but stable) inputs for hash information. | |
be2fb01f | 661 | $md5inputs = [ |
262e9b08 | 662 | defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : 'NO_SITE_KEY', |
4bb7f51e | 663 | CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE), |
44c32d0a CB |
664 | md5($config->dsn), |
665 | $config->dsn, | |
be2fb01f | 666 | ]; |
262e9b08 CB |
667 | // Trim 8 chars off the string, make it slightly easier to find |
668 | // but reveals less information from the hash. | |
315ca480 | 669 | return substr(md5(var_export($md5inputs, 1)), 8); |
44c32d0a CB |
670 | } |
671 | ||
edc8adfc | 672 | /** |
673 | * Generate the name of the logfile to use and store it as a static. | |
674 | * | |
e047612e CB |
675 | * This function includes simplistic log rotation and a check as to whether |
676 | * the file exists. | |
edc8adfc | 677 | * |
678 | * @param string $prefix | |
679 | */ | |
680 | protected static function generateLogFileName($prefix) { | |
681 | if (!isset(\Civi::$statics[__CLASS__]['logger_file' . $prefix])) { | |
931ba0f3 | 682 | $config = CRM_Core_Config::singleton(); |
6a488035 | 683 | |
edc8adfc | 684 | $prefixString = $prefix ? ($prefix . '.') : ''; |
6a488035 | 685 | |
9e618bf2 DH |
686 | if (CRM_Utils_Constant::value('CIVICRM_LOG_HASH', TRUE)) { |
687 | $hash = self::generateLogFileHash($config) . '.'; | |
688 | } | |
689 | else { | |
690 | $hash = ''; | |
691 | } | |
692 | $fileName = $config->configAndLogDir . 'CiviCRM.' . $prefixString . $hash . 'log'; | |
931ba0f3 | 693 | |
9e618bf2 | 694 | // Roll log file monthly or if greater than our threshold. |
e047612e CB |
695 | // Size-based rotation introduced in response to filesize limits on |
696 | // certain OS/PHP combos. | |
9e618bf2 DH |
697 | $maxBytes = CRM_Utils_Constant::value('CIVICRM_LOG_ROTATESIZE', 256 * 1024 * 1024); |
698 | if ($maxBytes) { | |
699 | if (file_exists($fileName)) { | |
700 | $fileTime = date("Ym", filemtime($fileName)); | |
701 | $fileSize = filesize($fileName); | |
702 | if (($fileTime < date('Ym')) || | |
703 | ($fileSize > $maxBytes) || | |
704 | ($fileSize < 0) | |
705 | ) { | |
706 | rename($fileName, | |
707 | $fileName . '.' . date('YmdHi') | |
708 | ); | |
709 | } | |
931ba0f3 | 710 | } |
711 | } | |
edc8adfc | 712 | \Civi::$statics[__CLASS__]['logger_file' . $prefix] = $fileName; |
931ba0f3 | 713 | } |
6a488035 TO |
714 | } |
715 | ||
a0ee3941 EM |
716 | /** |
717 | * @param string $msg | |
718 | * @param bool $log | |
719 | */ | |
00be9182 | 720 | public static function backtrace($msg = 'backTrace', $log = FALSE) { |
6a488035 TO |
721 | $backTrace = debug_backtrace(); |
722 | $message = self::formatBacktrace($backTrace); | |
723 | if (!$log) { | |
724 | CRM_Core_Error::debug($msg, $message); | |
725 | } | |
726 | else { | |
120f8e64 | 727 | CRM_Core_Error::debug_var($msg, $message, TRUE, TRUE, '', PEAR_LOG_DEBUG); |
6a488035 TO |
728 | } |
729 | } | |
730 | ||
731 | /** | |
0880a9d0 | 732 | * Render a backtrace array as a string. |
6a488035 | 733 | * |
6a0b768e TO |
734 | * @param array $backTrace |
735 | * Array of stack frames. | |
736 | * @param bool $showArgs | |
737 | * 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. | |
738 | * @param int $maxArgLen | |
739 | * Maximum number of characters to show from each argument string. | |
a6c01b45 CW |
740 | * @return string |
741 | * printable plain-text | |
6a488035 | 742 | */ |
00be9182 | 743 | public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) { |
6a488035 | 744 | $message = ''; |
34866662 CW |
745 | foreach (self::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) { |
746 | $message .= sprintf("#%s %s\n", $idx, $trace); | |
747 | } | |
2aa397bc | 748 | $message .= sprintf("#%s {main}\n", 1 + $idx); |
34866662 CW |
749 | return $message; |
750 | } | |
751 | ||
752 | /** | |
0880a9d0 | 753 | * Render a backtrace array as an array. |
34866662 | 754 | * |
6a0b768e TO |
755 | * @param array $backTrace |
756 | * Array of stack frames. | |
757 | * @param bool $showArgs | |
758 | * 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. | |
759 | * @param int $maxArgLen | |
760 | * Maximum number of characters to show from each argument string. | |
34866662 CW |
761 | * @return array |
762 | * @see debug_backtrace | |
763 | * @see Exception::getTrace() | |
764 | */ | |
00be9182 | 765 | public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) { |
be2fb01f | 766 | $ret = []; |
34866662 | 767 | foreach ($backTrace as $trace) { |
be2fb01f | 768 | $args = []; |
9c1bc317 | 769 | $fnName = $trace['function'] ?? NULL; |
34866662 | 770 | $className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : ''; |
6a488035 | 771 | |
83e7cba6 | 772 | // Do not show args for a few password related functions |
63d76404 | 773 | $skipArgs = $className == 'DB::' && $fnName == 'connect'; |
6a488035 | 774 | |
83e7cba6 CB |
775 | if (!empty($trace['args'])) { |
776 | foreach ($trace['args'] as $arg) { | |
353ffa53 | 777 | if (!$showArgs || $skipArgs) { |
83e7cba6 CB |
778 | $args[] = '(' . gettype($arg) . ')'; |
779 | continue; | |
780 | } | |
781 | switch ($type = gettype($arg)) { | |
782 | case 'boolean': | |
783 | $args[] = $arg ? 'TRUE' : 'FALSE'; | |
784 | break; | |
2aa397bc | 785 | |
83e7cba6 CB |
786 | case 'integer': |
787 | case 'double': | |
788 | $args[] = $arg; | |
789 | break; | |
2aa397bc | 790 | |
83e7cba6 | 791 | case 'string': |
86bfa4f6 | 792 | $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen) . '"'; |
83e7cba6 | 793 | break; |
2aa397bc | 794 | |
83e7cba6 | 795 | case 'array': |
92fcb95f | 796 | $args[] = '(Array:' . count($arg) . ')'; |
83e7cba6 | 797 | break; |
2aa397bc | 798 | |
83e7cba6 CB |
799 | case 'object': |
800 | $args[] = 'Object(' . get_class($arg) . ')'; | |
801 | break; | |
2aa397bc | 802 | |
83e7cba6 CB |
803 | case 'resource': |
804 | $args[] = 'Resource'; | |
805 | break; | |
2aa397bc | 806 | |
83e7cba6 CB |
807 | case 'NULL': |
808 | $args[] = 'NULL'; | |
809 | break; | |
2aa397bc | 810 | |
83e7cba6 CB |
811 | default: |
812 | $args[] = "($type)"; | |
813 | break; | |
814 | } | |
6a488035 TO |
815 | } |
816 | } | |
817 | ||
34866662 CW |
818 | $ret[] = sprintf( |
819 | "%s(%s): %s%s(%s)", | |
6a488035 TO |
820 | CRM_Utils_Array::value('file', $trace, '[internal function]'), |
821 | CRM_Utils_Array::value('line', $trace, ''), | |
822 | $className, | |
823 | $fnName, | |
824 | implode(", ", $args) | |
825 | ); | |
826 | } | |
34866662 | 827 | return $ret; |
6a488035 TO |
828 | } |
829 | ||
830 | /** | |
0880a9d0 | 831 | * Render an exception as HTML string. |
6a488035 | 832 | * |
614fcec4 | 833 | * @param Throwable $e |
a6c01b45 CW |
834 | * @return string |
835 | * printable HTML text | |
6a488035 | 836 | */ |
614fcec4 | 837 | public static function formatHtmlException(Throwable $e) { |
6a488035 TO |
838 | $msg = ''; |
839 | ||
840 | // Exception metadata | |
841 | ||
842 | // Exception backtrace | |
843 | if ($e instanceof PEAR_Exception) { | |
844 | $ei = $e; | |
ca5b3d14 | 845 | if (is_callable([$ei, 'getCause'])) { |
d216dc24 SL |
846 | // DB_ERROR doesn't have a getCause but does have a __call function which tricks is_callable. |
847 | if (!$ei instanceof DB_Error) { | |
848 | if ($ei->getCause() instanceof PEAR_Error) { | |
849 | $msg .= '<table class="crm-db-error">'; | |
850 | $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value')); | |
851 | $msg .= '<tbody>'; | |
852 | foreach (['Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo'] as $f) { | |
853 | $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func([$ei->getCause(), "get$f"])); | |
854 | } | |
855 | $msg .= '</tbody></table>'; | |
2aa397bc | 856 | } |
d216dc24 | 857 | $ei = $ei->getCause(); |
2aa397bc | 858 | } |
2aa397bc | 859 | } |
6a488035 | 860 | $msg .= $e->toHtml(); |
0db6c3e1 TO |
861 | } |
862 | else { | |
6a488035 TO |
863 | $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>'; |
864 | $msg .= '<pre>' . htmlentities(self::formatBacktrace($e->getTrace())) . '</pre>'; | |
865 | } | |
866 | return $msg; | |
867 | } | |
868 | ||
869 | /** | |
0880a9d0 | 870 | * Write details of an exception to the log. |
6a488035 | 871 | * |
614fcec4 | 872 | * @param Throwable $e |
a6c01b45 CW |
873 | * @return string |
874 | * printable plain text | |
6a488035 | 875 | */ |
614fcec4 | 876 | public static function formatTextException(Throwable $e) { |
6a488035 TO |
877 | $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n"; |
878 | ||
879 | $ei = $e; | |
be2fb01f | 880 | while (is_callable([$ei, 'getCause'])) { |
d216dc24 SL |
881 | // DB_ERROR doesn't have a getCause but does have a __call function which tricks is_callable. |
882 | if (!$ei instanceof DB_Error) { | |
883 | if ($ei->getCause() instanceof PEAR_Error) { | |
884 | foreach (['Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo'] as $f) { | |
885 | $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func([$ei->getCause(), "get$f"])); | |
886 | } | |
6a488035 | 887 | } |
d216dc24 SL |
888 | $ei = $ei->getCause(); |
889 | } | |
890 | // if we have reached a DB_Error assume that is the end of the road. | |
891 | else { | |
892 | $ei = NULL; | |
6a488035 | 893 | } |
6a488035 TO |
894 | } |
895 | $msg .= self::formatBacktrace($e->getTrace()); | |
896 | return $msg; | |
897 | } | |
898 | ||
a0ee3941 EM |
899 | /** |
900 | * @param $message | |
901 | * @param int $code | |
902 | * @param string $level | |
100fef9d | 903 | * @param array $params |
a0ee3941 EM |
904 | * |
905 | * @return object | |
906 | */ | |
00be9182 | 907 | public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) { |
6a488035 | 908 | $error = CRM_Core_Error::singleton(); |
be2fb01f | 909 | $error->push($code, $level, [$params], $message); |
6a488035 TO |
910 | return $error; |
911 | } | |
912 | ||
913 | /** | |
914 | * Set a status message in the session, then bounce back to the referrer. | |
915 | * | |
6a0b768e TO |
916 | * @param string $status |
917 | * The status message to set. | |
3fd42bb5 BT |
918 | * @param string|null $redirect |
919 | * @param string|null $title | |
6a488035 | 920 | */ |
50ecd413 | 921 | public static function statusBounce($status, $redirect = NULL, $title = NULL) { |
6a488035 TO |
922 | $session = CRM_Core_Session::singleton(); |
923 | if (!$redirect) { | |
924 | $redirect = $session->readUserContext(); | |
925 | } | |
50ecd413 CW |
926 | if ($title === NULL) { |
927 | $title = ts('Error'); | |
928 | } | |
be2fb01f | 929 | $session->setStatus($status, $title, 'alert', ['expires' => 0]); |
34866662 | 930 | if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) { |
be2fb01f | 931 | CRM_Core_Page_AJAX::returnJsonResponse(['status' => 'error']); |
34866662 | 932 | } |
6a488035 TO |
933 | CRM_Utils_System::redirect($redirect); |
934 | } | |
935 | ||
936 | /** | |
0880a9d0 | 937 | * Reset the error stack. |
6a488035 | 938 | * |
6a488035 TO |
939 | */ |
940 | public static function reset() { | |
941 | $error = self::singleton(); | |
be2fb01f CW |
942 | $error->_errors = []; |
943 | $error->_errorsByLevel = []; | |
6a488035 TO |
944 | } |
945 | ||
6a4257d4 | 946 | /** |
42c0daee TO |
947 | * PEAR error-handler which converts errors to exceptions |
948 | * | |
3fd42bb5 | 949 | * @param PEAR_Error $pearError |
42c0daee | 950 | * @throws PEAR_Exception |
6a4257d4 | 951 | */ |
6a488035 | 952 | public static function exceptionHandler($pearError) { |
120f8e64 | 953 | CRM_Core_Error::debug_var('Fatal Error Details', self::getErrorDetails($pearError), TRUE, TRUE, '', PEAR_LOG_ERR); |
6a488035 TO |
954 | CRM_Core_Error::backtrace('backTrace', TRUE); |
955 | throw new PEAR_Exception($pearError->getMessage(), $pearError); | |
956 | } | |
957 | ||
958 | /** | |
42c0daee | 959 | * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport. |
6a488035 | 960 | * |
6a0b768e TO |
961 | * @param object $obj |
962 | * The PEAR_ERROR object. | |
a6c01b45 CW |
963 | * @return object |
964 | * $obj | |
6a488035 TO |
965 | */ |
966 | public static function nullHandler($obj) { | |
120f8e64 | 967 | CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}", FALSE, '', PEAR_LOG_ERR); |
6a488035 TO |
968 | CRM_Core_Error::backtrace('backTrace', TRUE); |
969 | return $obj; | |
970 | } | |
971 | ||
d424ffde | 972 | /** |
6a488035 TO |
973 | * @deprecated |
974 | * This function is no longer used by v3 api. | |
975 | * @fixme Some core files call it but it should be re-thought & renamed or removed | |
d424ffde | 976 | * |
a0ee3941 EM |
977 | * @param $msg |
978 | * @param null $data | |
979 | * | |
980 | * @return array | |
981 | * @throws Exception | |
982 | */ | |
6a488035 TO |
983 | public static function &createAPIError($msg, $data = NULL) { |
984 | if (self::$modeException) { | |
985 | throw new Exception($msg, $data); | |
986 | } | |
987 | ||
be2fb01f | 988 | $values = []; |
6a488035 TO |
989 | |
990 | $values['is_error'] = 1; | |
991 | $values['error_message'] = $msg; | |
992 | if (isset($data)) { | |
993 | $values = array_merge($values, $data); | |
994 | } | |
995 | return $values; | |
996 | } | |
997 | ||
a0ee3941 EM |
998 | /** |
999 | * @param $file | |
1000 | */ | |
6a488035 TO |
1001 | public static function movedSiteError($file) { |
1002 | $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend', | |
1003 | 'reset=1', | |
1004 | TRUE | |
1005 | ); | |
1006 | echo "We could not write $file. Have you moved your site directory or server?<p>"; | |
1007 | echo "Please fix the setting by running the <a href=\"$url\">update config script</a>"; | |
1008 | exit(); | |
1009 | } | |
1010 | ||
1011 | /** | |
0880a9d0 | 1012 | * Terminate execution abnormally. |
ad37ac8e | 1013 | * |
8be79db7 BT |
1014 | * @param int $code |
1015 | */ | |
1016 | protected static function abend($code) { | |
1017 | // do a hard rollback of any pending transactions | |
1018 | // if we've come here, its because of some unexpected PEAR errors | |
1019 | CRM_Core_Transaction::forceRollbackIfEnabled(); | |
1020 | CRM_Utils_System::civiExit($code); | |
1021 | } | |
1022 | ||
1023 | /** | |
1024 | * Show in-page exception | |
1025 | * For situations where where calling abend will block the ability for a branded error screen | |
1026 | * | |
1027 | * Although the host page will run past this point, CiviCRM should not, | |
1028 | * therefore we trigger the civi.exit events | |
1029 | * | |
ad37ac8e | 1030 | * @param string $code |
6a488035 | 1031 | */ |
8be79db7 | 1032 | protected static function inpageExceptionDisplay($code) { |
6a488035 TO |
1033 | // do a hard rollback of any pending transactions |
1034 | // if we've come here, its because of some unexpected PEAR errors | |
1035 | CRM_Core_Transaction::forceRollbackIfEnabled(); | |
8be79db7 BT |
1036 | |
1037 | if ($code > 0 && !headers_sent()) { | |
1038 | http_response_code(500); | |
1039 | } | |
1040 | ||
1041 | // move things to CiviCRM cache as needed | |
1042 | CRM_Core_Session::storeSessionObjects(); | |
1043 | ||
1044 | if (Civi\Core\Container::isContainerBooted()) { | |
1045 | Civi::dispatcher()->dispatch('civi.core.exit'); | |
1046 | } | |
1047 | ||
1048 | $userSystem = CRM_Core_Config::singleton()->userSystem; | |
1049 | if (is_callable([$userSystem, 'onCiviExit'])) { | |
1050 | $userSystem->onCiviExit(); | |
b7760d30 | 1051 | } |
6a488035 TO |
1052 | } |
1053 | ||
a0ee3941 | 1054 | /** |
3ab5efa9 EM |
1055 | * @param array $error |
1056 | * @param int $type | |
a0ee3941 EM |
1057 | * |
1058 | * @return bool | |
1059 | */ | |
6a488035 | 1060 | public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) { |
8cc574cf | 1061 | if (is_array($error) && !empty($error['is_error'])) { |
6a488035 TO |
1062 | $code = $error['error_message']['code']; |
1063 | if ($code == $type) { | |
1064 | return TRUE; | |
1065 | } | |
1066 | } | |
1067 | return FALSE; | |
1068 | } | |
96025800 | 1069 | |
496320c3 | 1070 | /** |
233240fc EM |
1071 | * Output a deprecated function warning to log file. |
1072 | * | |
1073 | * Deprecated class:function is automatically generated from calling function. | |
496320c3 | 1074 | * |
5a0aaa1e | 1075 | * @param string $newMethod |
496320c3 | 1076 | * description of new method (eg. "buildOptions() method in the appropriate BAO object"). |
233240fc | 1077 | * @param string|null $oldMethod |
5a0aaa1e | 1078 | * optional description of old method (if not the calling method). eg. CRM_MyClass::myOldMethodToGetTheOptions() |
496320c3 | 1079 | */ |
233240fc EM |
1080 | public static function deprecatedFunctionWarning(string $newMethod, ?string $oldMethod = NULL): void { |
1081 | $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 4); | |
5a0aaa1e | 1082 | if (!$oldMethod) { |
233240fc EM |
1083 | $callerFunction = $backtrace[1]['function'] ?? NULL; |
1084 | $callerClass = $backtrace[1]['class'] ?? NULL; | |
5a0aaa1e MW |
1085 | $oldMethod = "{$callerClass}::{$callerFunction}"; |
1086 | } | |
ee2c6cde | 1087 | $message = "Deprecated function $oldMethod, use $newMethod."; |
233240fc EM |
1088 | // Add a mini backtrace. Just the function is too little to be meaningful but people are |
1089 | // saying they can't track down where the deprecated calls are coming from. | |
1090 | $miniBacktrace = []; | |
1091 | foreach ($backtrace as $backtraceLine) { | |
57cde481 | 1092 | $miniBacktrace[] = ($backtraceLine['class'] ?? '') . '::' . ($backtraceLine['function'] ?? ''); |
233240fc | 1093 | } |
c0a09cdc | 1094 | Civi::log()->warning($message . "\n" . implode("\n", $miniBacktrace), ['civi.tag' => 'deprecated']); |
ee2c6cde | 1095 | trigger_error($message, E_USER_DEPRECATED); |
e9dc5230 SL |
1096 | } |
1097 | ||
1098 | /** | |
1099 | * Output a deprecated notice about a deprecated call path, rather than deprecating a whole function. | |
ee2c6cde | 1100 | * |
e9dc5230 SL |
1101 | * @param string $message |
1102 | */ | |
1103 | public static function deprecatedWarning($message) { | |
160aed81 | 1104 | // Even though the tag is no longer used within the log() function, |
1105 | // \Civi\API\LogObserver instances may still be monitoring it. | |
ee2c6cde MW |
1106 | $dbt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3); |
1107 | $callerFunction = $dbt[2]['function'] ?? NULL; | |
1108 | $callerClass = $dbt[2]['class'] ?? NULL; | |
1109 | $message .= " Caller: {$callerClass}::{$callerFunction}"; | |
e9dc5230 | 1110 | Civi::log()->warning($message, ['civi.tag' => 'deprecated']); |
160aed81 | 1111 | trigger_error($message, E_USER_DEPRECATED); |
496320c3 MW |
1112 | } |
1113 | ||
6a488035 TO |
1114 | } |
1115 | ||
1116 | $e = new PEAR_ErrorStack('CRM'); | |
1117 | $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error'); |