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