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