Commit | Line | Data |
---|---|---|
6a488035 | 1 | <?php |
6a488035 TO |
2 | /* |
3 | +--------------------------------------------------------------------+ | |
7e9e8871 | 4 | | CiviCRM version 4.7 | |
6a488035 | 5 | +--------------------------------------------------------------------+ |
e7112fa7 | 6 | | Copyright CiviCRM LLC (c) 2004-2015 | |
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 | |
e7112fa7 | 33 | * @copyright CiviCRM LLC (c) 2004-2015 |
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 | ||
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 | 150 | /** |
0880a9d0 | 151 | * Status display function specific to payment processor errors. |
dbddfb08 EM |
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 | * | |
3bdca100 | 170 | * @param object $pearError PEAR_Error |
6a488035 TO |
171 | */ |
172 | public static function handle($pearError) { | |
173 | ||
174 | // setup smarty with config, session and template location. | |
175 | $template = CRM_Core_Smarty::singleton(); | |
176 | $config = CRM_Core_Config::singleton(); | |
177 | ||
178 | if ($config->backtrace) { | |
179 | self::backtrace(); | |
180 | } | |
181 | ||
182 | // create the error array | |
353ffa53 TO |
183 | $error = array(); |
184 | $error['callback'] = $pearError->getCallback(); | |
185 | $error['code'] = $pearError->getCode(); | |
186 | $error['message'] = $pearError->getMessage(); | |
187 | $error['mode'] = $pearError->getMode(); | |
6a488035 | 188 | $error['debug_info'] = $pearError->getDebugInfo(); |
353ffa53 TO |
189 | $error['type'] = $pearError->getType(); |
190 | $error['user_info'] = $pearError->getUserInfo(); | |
191 | $error['to_string'] = $pearError->toString(); | |
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 | ||
198 | if (!isset($_DB_DATAOBJECT['CONFIG']['database'])) { | |
199 | // we haven't setup sql, so it's not our sql error... | |
200 | } | |
201 | elseif (preg_match('/^mysql:/', $_DB_DATAOBJECT['CONFIG']['database']) && | |
6a488035 TO |
202 | mysql_error() |
203 | ) { | |
204 | $mysql_error = mysql_error() . ', ' . mysql_errno(); | |
205 | $template->assign_by_ref('mysql_code', $mysql_error); | |
206 | ||
207 | // execute a dummy query to clear error stack | |
208 | mysql_query('select 1'); | |
209 | } | |
2e4ade96 | 210 | elseif (preg_match('/^mysqli:/', $_DB_DATAOBJECT['CONFIG']['database'])) { |
6a488035 TO |
211 | $dao = new CRM_Core_DAO(); |
212 | ||
6a488035 TO |
213 | if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5])) { |
214 | $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5]; | |
215 | $link = $conn->connection; | |
216 | ||
217 | if (mysqli_error($link)) { | |
218 | $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link); | |
219 | $template->assign_by_ref('mysql_code', $mysql_error); | |
220 | ||
221 | // execute a dummy query to clear error stack | |
222 | mysqli_query($link, 'select 1'); | |
223 | } | |
224 | } | |
225 | } | |
226 | ||
227 | $template->assign_by_ref('error', $error); | |
228 | $errorDetails = CRM_Core_Error::debug('', $error, FALSE); | |
229 | $template->assign_by_ref('errorDetails', $errorDetails); | |
230 | ||
231 | CRM_Core_Error::debug_var('Fatal Error Details', $error); | |
232 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
233 | ||
234 | if ($config->initialized) { | |
235 | $content = $template->fetch('CRM/common/fatal.tpl'); | |
236 | echo CRM_Utils_System::theme($content); | |
237 | } | |
238 | else { | |
239 | echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>"; | |
240 | CRM_Core_Error::debug(NULL, $error); | |
241 | } | |
3a210ec0 E |
242 | static $runOnce = FALSE; |
243 | if ($runOnce) { | |
244 | exit; | |
245 | } | |
246 | $runOnce = TRUE; | |
6a488035 TO |
247 | self::abend(1); |
248 | } | |
249 | ||
a0ee3941 | 250 | /** |
4f1f1f2a CW |
251 | * this function is used to trap and print errors |
252 | * during system initialization time. Hence the error | |
253 | * message is quite ugly | |
254 | * | |
a0ee3941 EM |
255 | * @param $pearError |
256 | */ | |
6a488035 TO |
257 | public static function simpleHandler($pearError) { |
258 | ||
259 | // create the error array | |
353ffa53 TO |
260 | $error = array(); |
261 | $error['callback'] = $pearError->getCallback(); | |
262 | $error['code'] = $pearError->getCode(); | |
263 | $error['message'] = $pearError->getMessage(); | |
264 | $error['mode'] = $pearError->getMode(); | |
6a488035 | 265 | $error['debug_info'] = $pearError->getDebugInfo(); |
353ffa53 TO |
266 | $error['type'] = $pearError->getType(); |
267 | $error['user_info'] = $pearError->getUserInfo(); | |
268 | $error['to_string'] = $pearError->toString(); | |
6a488035 | 269 | |
005db542 DL |
270 | // ensure that debug does not check permissions since we are in bootstrap |
271 | // mode and need to print a decent message to help the user | |
90154ece | 272 | CRM_Core_Error::debug('Initialization Error', $error, TRUE, TRUE, FALSE); |
6a488035 TO |
273 | |
274 | // always log the backtrace to a file | |
275 | self::backtrace('backTrace', TRUE); | |
276 | ||
277 | exit(0); | |
278 | } | |
279 | ||
280 | /** | |
281 | * Handle errors raised using the PEAR Error Stack. | |
282 | * | |
283 | * currently the handler just requests the PES framework | |
284 | * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH). | |
285 | * | |
286 | * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE. | |
287 | * | |
288 | * Also, if we do not return any value the PEAR_ErrorStack::push() then does the | |
289 | * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen, | |
290 | * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog(); | |
6a488035 TO |
291 | */ |
292 | public static function handlePES($pearError) { | |
293 | return PEAR_ERRORSTACK_PUSH; | |
294 | } | |
295 | ||
296 | /** | |
0880a9d0 | 297 | * Display an error page with an error message describing what happened. |
6a488035 | 298 | * |
6a0b768e TO |
299 | * @param string $message |
300 | * The error message. | |
301 | * @param string $code | |
302 | * The error code if any. | |
303 | * @param string $email | |
304 | * The email address to notify of this situation. | |
77b97be7 EM |
305 | * |
306 | * @throws Exception | |
6a488035 | 307 | */ |
00be9182 | 308 | public static function fatal($message = NULL, $code = NULL, $email = NULL) { |
6a488035 | 309 | $vars = array( |
0ac9fd52 | 310 | 'message' => htmlspecialchars($message), |
6a488035 TO |
311 | 'code' => $code, |
312 | ); | |
313 | ||
314 | if (self::$modeException) { | |
315 | // CRM-11043 | |
316 | CRM_Core_Error::debug_var('Fatal Error Details', $vars); | |
317 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
318 | ||
319 | $details = 'A fatal error was triggered'; | |
320 | if ($message) { | |
321 | $details .= ': ' . $message; | |
2aa397bc | 322 | } |
6a488035 TO |
323 | throw new Exception($details, $code); |
324 | } | |
325 | ||
326 | if (!$message) { | |
327 | $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/')); | |
328 | } | |
329 | ||
330 | if (php_sapi_name() == "cli") { | |
331 | print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n"); | |
0c4a3d8b | 332 | // Fix for CRM-16899 |
4c68cf7b | 333 | echo static::formatBacktrace(debug_backtrace()); |
6a488035 TO |
334 | die("\n"); |
335 | // FIXME: Why doesn't this call abend()? | |
336 | // Difference: abend() will cleanup transaction and (via civiExit) store session state | |
337 | // self::abend(CRM_Core_Error::FATAL_ERROR); | |
338 | } | |
339 | ||
340 | $config = CRM_Core_Config::singleton(); | |
341 | ||
342 | if ($config->fatalErrorHandler && | |
343 | function_exists($config->fatalErrorHandler) | |
344 | ) { | |
345 | $name = $config->fatalErrorHandler; | |
346 | $ret = $name($vars); | |
347 | if ($ret) { | |
348 | // the call has been successfully handled | |
349 | // so we just exit | |
350 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
351 | } | |
352 | } | |
353 | ||
25dc2153 PH |
354 | if ($config->backtrace) { |
355 | self::backtrace(); | |
356 | } | |
357 | ||
358 | CRM_Core_Error::debug_var('Fatal Error Details', $vars); | |
359 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
360 | ||
34866662 CW |
361 | // If we are in an ajax callback, format output appropriately |
362 | if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) { | |
363 | $out = array( | |
364 | 'status' => 'fatal', | |
365 | '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>', | |
366 | ); | |
367 | if ($config->backtrace && CRM_Core_Permission::check('view debug output')) { | |
368 | $out['backtrace'] = self::parseBacktrace(debug_backtrace()); | |
369 | $message .= '<p><em>See console for backtrace</em></p>'; | |
370 | } | |
1528ac1d | 371 | CRM_Core_Session::setStatus($message, ts('Sorry an error occurred'), 'error'); |
34866662 CW |
372 | CRM_Core_Transaction::forceRollbackIfEnabled(); |
373 | CRM_Core_Page_AJAX::returnJsonResponse($out); | |
374 | } | |
375 | ||
6a488035 TO |
376 | $template = CRM_Core_Smarty::singleton(); |
377 | $template->assign($vars); | |
f431d51f | 378 | $config->userSystem->outputError($template->fetch('CRM/common/fatal.tpl')); |
6a488035 TO |
379 | |
380 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
381 | } | |
382 | ||
383 | /** | |
0880a9d0 | 384 | * Display an error page with an error message describing what happened. |
6a488035 TO |
385 | * |
386 | * This function is evil -- it largely replicates fatal(). Hopefully the | |
387 | * entire CRM_Core_Error system can be hollowed out and replaced with | |
388 | * something that follows a cleaner separation of concerns. | |
389 | * | |
390 | * @param Exception $exception | |
6a488035 | 391 | */ |
00be9182 | 392 | public static function handleUnhandledException($exception) { |
4b57bc9f EM |
393 | try { |
394 | CRM_Utils_Hook::unhandledException($exception); | |
0db6c3e1 TO |
395 | } |
396 | catch (Exception $other) { | |
4b57bc9f | 397 | // if the exception-handler generates an exception, then that sucks! oh, well. carry on. |
4fd5f07e | 398 | CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other)); |
4b57bc9f | 399 | } |
6a488035 TO |
400 | $config = CRM_Core_Config::singleton(); |
401 | $vars = array( | |
402 | 'message' => $exception->getMessage(), | |
403 | 'code' => NULL, | |
404 | 'exception' => $exception, | |
405 | ); | |
406 | if (!$vars['message']) { | |
407 | $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/')); | |
408 | } | |
409 | ||
410 | // Case A: CLI | |
411 | if (php_sapi_name() == "cli") { | |
412 | printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']); | |
413 | print self::formatTextException($exception); | |
414 | die("\n"); | |
415 | // FIXME: Why doesn't this call abend()? | |
416 | // Difference: abend() will cleanup transaction and (via civiExit) store session state | |
417 | // self::abend(CRM_Core_Error::FATAL_ERROR); | |
418 | } | |
419 | ||
420 | // Case B: Custom error handler | |
421 | if ($config->fatalErrorHandler && | |
422 | function_exists($config->fatalErrorHandler) | |
423 | ) { | |
424 | $name = $config->fatalErrorHandler; | |
425 | $ret = $name($vars); | |
426 | if ($ret) { | |
427 | // the call has been successfully handled | |
428 | // so we just exit | |
429 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
430 | } | |
431 | } | |
432 | ||
433 | // Case C: Default error handler | |
434 | ||
435 | // log to file | |
436 | CRM_Core_Error::debug_var('Fatal Error Details', $vars); | |
437 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
438 | ||
439 | // print to screen | |
440 | $template = CRM_Core_Smarty::singleton(); | |
441 | $template->assign($vars); | |
f431d51f | 442 | $content = $template->fetch('CRM/common/fatal.tpl'); |
6a488035 TO |
443 | if ($config->backtrace) { |
444 | $content = self::formatHtmlException($exception) . $content; | |
445 | } | |
446 | if ($config->userFramework == 'Joomla' && | |
447 | class_exists('JError') | |
448 | ) { | |
449 | JError::raiseError('CiviCRM-001', $content); | |
450 | } | |
451 | else { | |
452 | echo CRM_Utils_System::theme($content); | |
453 | } | |
454 | ||
455 | // fin | |
456 | self::abend(CRM_Core_Error::FATAL_ERROR); | |
457 | } | |
458 | ||
459 | /** | |
100fef9d | 460 | * Outputs pre-formatted debug information. Flushes the buffers |
6a488035 TO |
461 | * so we can interrupt a potential POST/redirect |
462 | * | |
3bdca100 | 463 | * @param string $name name of debug section |
464 | * @param $variable mixed reference to variables that we need a trace of | |
465 | * @param bool $log should we log or return the output | |
466 | * @param bool $html whether to generate a HTML-escaped output | |
467 | * @param bool $checkPermission should we check permissions before displaying output | |
90154ece DL |
468 | * useful when we die during initialization and permissioning |
469 | * subsystem is not initialized - CRM-13765 | |
6a488035 | 470 | * |
a6c01b45 CW |
471 | * @return string |
472 | * the generated output | |
6a488035 | 473 | */ |
00be9182 | 474 | public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) { |
6a488035 TO |
475 | $error = self::singleton(); |
476 | ||
477 | if ($variable === NULL) { | |
478 | $variable = $name; | |
479 | $name = NULL; | |
480 | } | |
481 | ||
482 | $out = print_r($variable, TRUE); | |
483 | $prefix = NULL; | |
484 | if ($html) { | |
485 | $out = htmlspecialchars($out); | |
486 | if ($name) { | |
487 | $prefix = "<p>$name</p>"; | |
488 | } | |
489 | $out = "{$prefix}<p><pre>$out</pre></p><p></p>"; | |
490 | } | |
491 | else { | |
492 | if ($name) { | |
493 | $prefix = "$name:\n"; | |
494 | } | |
495 | $out = "{$prefix}$out\n"; | |
496 | } | |
90154ece DL |
497 | if ( |
498 | $log && | |
499 | (!$checkPermission || CRM_Core_Permission::check('view debug output')) | |
500 | ) { | |
6a488035 TO |
501 | echo $out; |
502 | } | |
503 | ||
504 | return $out; | |
505 | } | |
506 | ||
507 | /** | |
508 | * Similar to the function debug. Only difference is | |
509 | * in the formatting of the output. | |
510 | * | |
c490a46a CW |
511 | * @param string $variable_name |
512 | * @param mixed $variable | |
6a0b768e TO |
513 | * @param bool $print |
514 | * Should we use print_r ? (else we use var_dump). | |
515 | * @param bool $log | |
516 | * Should we log or return the output. | |
517 | * @param string $comp | |
518 | * Variable name. | |
2a6da8d7 | 519 | * |
a6c01b45 CW |
520 | * @return string |
521 | * the generated output | |
6a488035 | 522 | * |
6a488035 | 523 | * |
6a488035 TO |
524 | * |
525 | * @see CRM_Core_Error::debug() | |
526 | * @see CRM_Core_Error::debug_log_message() | |
527 | */ | |
3bdca100 | 528 | public static function debug_var( |
f9f40af3 | 529 | $variable_name, |
6a488035 TO |
530 | $variable, |
531 | $print = TRUE, | |
2aa397bc TO |
532 | $log = TRUE, |
533 | $comp = '' | |
6a488035 TO |
534 | ) { |
535 | // check if variable is set | |
536 | if (!isset($variable)) { | |
537 | $out = "\$$variable_name is not set"; | |
538 | } | |
539 | else { | |
540 | if ($print) { | |
541 | $out = print_r($variable, TRUE); | |
542 | $out = "\$$variable_name = $out"; | |
543 | } | |
544 | else { | |
545 | // use var_dump | |
546 | ob_start(); | |
547 | var_dump($variable); | |
548 | $dump = ob_get_contents(); | |
549 | ob_end_clean(); | |
550 | $out = "\n\$$variable_name = $dump"; | |
551 | } | |
552 | // reset if it is an array | |
553 | if (is_array($variable)) { | |
554 | reset($variable); | |
555 | } | |
556 | } | |
557 | return self::debug_log_message($out, FALSE, $comp); | |
558 | } | |
559 | ||
560 | /** | |
0880a9d0 | 561 | * Display the error message on terminal. |
6a488035 | 562 | * |
2a6da8d7 | 563 | * @param $message |
6a0b768e TO |
564 | * @param bool $out |
565 | * Should we log or return the output. | |
6a488035 | 566 | * |
6a0b768e TO |
567 | * @param string $comp |
568 | * Message to be output. | |
a6c01b45 CW |
569 | * @return string |
570 | * format of the backtrace | |
6a488035 | 571 | * |
6a488035 | 572 | * |
6a488035 | 573 | */ |
00be9182 | 574 | public static function debug_log_message($message, $out = FALSE, $comp = '') { |
213a5f19 | 575 | $config = CRM_Core_Config::singleton(); |
6a488035 TO |
576 | |
577 | $file_log = self::createDebugLogger($comp); | |
578 | $file_log->log("$message\n"); | |
0ac9fd52 CB |
579 | |
580 | $str = '<p/><code>' . htmlspecialchars($message) . '</code>'; | |
6a488035 TO |
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 | 588 | if ($config->userSystem->is_drupal and function_exists('watchdog')) { |
eb9dd128 | 589 | watchdog('civicrm', '%message', array('%message' => $message), WATCHDOG_DEBUG); |
213a5f19 EM |
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 | 624 | /** |
0880a9d0 | 625 | * Obtain a reference to the error log. |
6a488035 | 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, | |
dafad154 | 651 | $fileName . '.' . date('YmdHi') |
6a488035 TO |
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 | /** | |
0880a9d0 | 675 | * Render a backtrace array as a string. |
6a488035 | 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 | /** | |
0880a9d0 | 696 | * Render a backtrace array as an array. |
34866662 | 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 | /** | |
0880a9d0 | 774 | * Render an exception as HTML string. |
6a488035 TO |
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 | /** | |
0880a9d0 | 810 | * Write details of an exception to the log. |
6a488035 TO |
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 | */ |
50ecd413 | 855 | public static function statusBounce($status, $redirect = NULL, $title = NULL) { |
6a488035 TO |
856 | $session = CRM_Core_Session::singleton(); |
857 | if (!$redirect) { | |
858 | $redirect = $session->readUserContext(); | |
859 | } | |
50ecd413 CW |
860 | if ($title === NULL) { |
861 | $title = ts('Error'); | |
862 | } | |
863 | $session->setStatus($status, $title, 'alert', array('expires' => 0)); | |
34866662 CW |
864 | if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) { |
865 | CRM_Core_Page_AJAX::returnJsonResponse(array('status' => 'error')); | |
866 | } | |
6a488035 TO |
867 | CRM_Utils_System::redirect($redirect); |
868 | } | |
869 | ||
870 | /** | |
0880a9d0 | 871 | * Reset the error stack. |
6a488035 | 872 | * |
6a488035 TO |
873 | */ |
874 | public static function reset() { | |
875 | $error = self::singleton(); | |
876 | $error->_errors = array(); | |
877 | $error->_errorsByLevel = array(); | |
878 | } | |
879 | ||
6a4257d4 | 880 | /** |
42c0daee TO |
881 | * PEAR error-handler which converts errors to exceptions |
882 | * | |
883 | * @param $pearError | |
884 | * @throws PEAR_Exception | |
6a4257d4 | 885 | */ |
6a488035 TO |
886 | public static function exceptionHandler($pearError) { |
887 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
888 | throw new PEAR_Exception($pearError->getMessage(), $pearError); | |
889 | } | |
890 | ||
891 | /** | |
42c0daee | 892 | * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport. |
6a488035 | 893 | * |
6a0b768e TO |
894 | * @param object $obj |
895 | * The PEAR_ERROR object. | |
a6c01b45 CW |
896 | * @return object |
897 | * $obj | |
6a488035 TO |
898 | */ |
899 | public static function nullHandler($obj) { | |
900 | CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}"); | |
901 | CRM_Core_Error::backtrace('backTrace', TRUE); | |
902 | return $obj; | |
903 | } | |
904 | ||
d424ffde | 905 | /** |
6a488035 TO |
906 | * @deprecated |
907 | * This function is no longer used by v3 api. | |
908 | * @fixme Some core files call it but it should be re-thought & renamed or removed | |
d424ffde | 909 | * |
a0ee3941 EM |
910 | * @param $msg |
911 | * @param null $data | |
912 | * | |
913 | * @return array | |
914 | * @throws Exception | |
915 | */ | |
6a488035 TO |
916 | public static function &createAPIError($msg, $data = NULL) { |
917 | if (self::$modeException) { | |
918 | throw new Exception($msg, $data); | |
919 | } | |
920 | ||
921 | $values = array(); | |
922 | ||
923 | $values['is_error'] = 1; | |
924 | $values['error_message'] = $msg; | |
925 | if (isset($data)) { | |
926 | $values = array_merge($values, $data); | |
927 | } | |
928 | return $values; | |
929 | } | |
930 | ||
a0ee3941 EM |
931 | /** |
932 | * @param $file | |
933 | */ | |
6a488035 TO |
934 | public static function movedSiteError($file) { |
935 | $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend', | |
936 | 'reset=1', | |
937 | TRUE | |
938 | ); | |
939 | echo "We could not write $file. Have you moved your site directory or server?<p>"; | |
940 | echo "Please fix the setting by running the <a href=\"$url\">update config script</a>"; | |
941 | exit(); | |
942 | } | |
943 | ||
944 | /** | |
0880a9d0 | 945 | * Terminate execution abnormally. |
6a488035 TO |
946 | */ |
947 | protected static function abend($code) { | |
948 | // do a hard rollback of any pending transactions | |
949 | // if we've come here, its because of some unexpected PEAR errors | |
950 | CRM_Core_Transaction::forceRollbackIfEnabled(); | |
951 | CRM_Utils_System::civiExit($code); | |
952 | } | |
953 | ||
a0ee3941 | 954 | /** |
3ab5efa9 EM |
955 | * @param array $error |
956 | * @param int $type | |
a0ee3941 EM |
957 | * |
958 | * @return bool | |
959 | */ | |
6a488035 | 960 | public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) { |
8cc574cf | 961 | if (is_array($error) && !empty($error['is_error'])) { |
6a488035 TO |
962 | $code = $error['error_message']['code']; |
963 | if ($code == $type) { | |
964 | return TRUE; | |
965 | } | |
966 | } | |
967 | return FALSE; | |
968 | } | |
96025800 | 969 | |
6a488035 TO |
970 | } |
971 | ||
972 | $e = new PEAR_ErrorStack('CRM'); | |
973 | $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error'); |