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