INFRA-132 - CRM/Core - Misc
[civicrm-core.git] / CRM / Core / Error.php
index 55e2cbeaf0567c6b5a69b5a551dc16c5b58ed08c..a0a2d99409957f454d11353853148451f364aadf 100644 (file)
@@ -2,9 +2,9 @@
 
 /*
  +--------------------------------------------------------------------+
- | CiviCRM version 4.4                                                |
+ | CiviCRM version 4.6                                                |
  +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2013                                |
+ | Copyright CiviCRM LLC (c) 2004-2014                                |
  +--------------------------------------------------------------------+
  | This file is a part of CiviCRM.                                    |
  |                                                                    |
@@ -31,7 +31,7 @@
  * PEAR_ErrorStack and use that framework
  *
  * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2013
+ * @copyright CiviCRM LLC (c) 2004-2014
  * $Id$
  *
  */
@@ -41,23 +41,45 @@ require_once 'PEAR/Exception.php';
 require_once 'CRM/Core/Exception.php';
 
 require_once 'Log.php';
+
+/**
+ * Class CRM_Exception
+ */
 class CRM_Exception extends PEAR_Exception {
   // Redefine the exception so message isn't optional
+  /**
+   * Supported signatures:
+   *  - PEAR_Exception(string $message);
+   *  - PEAR_Exception(string $message, int $code);
+   *  - PEAR_Exception(string $message, Exception $cause);
+   *  - PEAR_Exception(string $message, Exception $cause, int $code);
+   *  - PEAR_Exception(string $message, PEAR_Error $cause);
+   *  - PEAR_Exception(string $message, PEAR_Error $cause, int $code);
+   *  - PEAR_Exception(string $message, array $causes);
+   *  - PEAR_Exception(string $message, array $causes, int $code);
+   *
+   * @param string exception message
+   * @param int $code
+   * @param Exception $previous
+   */
   public function __construct($message = NULL, $code = 0, Exception$previous = NULL) {
     parent::__construct($message, $code, $previous);
   }
 }
 
+/**
+ * Class CRM_Core_Error
+ */
 class CRM_Core_Error extends PEAR_ErrorStack {
 
   /**
-   * status code of various types of errors
+   * Status code of various types of errors
    * @var const
    */
-  CONST FATAL_ERROR = 2;
-  CONST DUPLICATE_CONTACT = 8001;
-  CONST DUPLICATE_CONTRIBUTION = 8002;
-  CONST DUPLICATE_PARTICIPANT = 8003;
+  const FATAL_ERROR = 2;
+  const DUPLICATE_CONTACT = 8001;
+  const DUPLICATE_CONTRIBUTION = 8002;
+  const DUPLICATE_PARTICIPANT = 8003;
 
   /**
    * We only need one instance of this object. So we use the singleton
@@ -81,12 +103,18 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   public static $modeException = NULL;
 
   /**
-   * singleton function used to manage this object.
+   * Singleton function used to manage this object.
+   *
+   * @param null $package
+   * @param bool $msgCallback
+   * @param bool $contextCallback
+   * @param bool $throwPEAR_Error
+   * @param string $stackClass
    *
    * @return object
    * @static
    */
-   static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
+  public static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
     if (self::$_singleton === NULL) {
       self::$_singleton = new CRM_Core_Error('CiviCRM');
     }
@@ -94,9 +122,9 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   }
 
   /**
-   * construcor
+   * Constructor
    */
-  function __construct() {
+  public function __construct() {
     parent::__construct('CiviCRM');
 
     $log = CRM_Core_Config::getLog();
@@ -106,6 +134,12 @@ class CRM_Core_Error extends PEAR_ErrorStack {
     $this->setDefaultCallback(array($this, 'handlePES'));
   }
 
+  /**
+   * @param $error
+   * @param string $separator
+   *
+   * @return array|null|string
+   */
   static public function getMessages(&$error, $separator = '<br />') {
     if (is_a($error, 'CRM_Core_Error')) {
       $errors = $error->getErrors();
@@ -119,7 +153,12 @@ class CRM_Core_Error extends PEAR_ErrorStack {
     return NULL;
   }
 
-  function displaySessionError(&$error, $separator = '<br />') {
+  /**
+   * Status display function specific to payment processor errors
+   * @param $error
+   * @param string $separator
+   */
+  public static function displaySessionError(&$error, $separator = '<br />') {
     $message = self::getMessages($error, $separator);
     if ($message) {
       $status = ts("Payment Processor Error message") . "{$separator} $message";
@@ -129,7 +168,7 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   }
 
   /**
-   * create the main callback method. this method centralizes error processing.
+   * Create the main callback method. this method centralizes error processing.
    *
    * the errors we expect are from the pear modules DB, DB_DataObject
    * which currently use PEAR::raiseError to notify of error messages.
@@ -137,7 +176,6 @@ class CRM_Core_Error extends PEAR_ErrorStack {
    * @param object PEAR_Error
    *
    * @return void
-   * @access public
    */
   public static function handle($pearError) {
 
@@ -215,6 +253,9 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   // this function is used to trap and print errors
   // during system initialization time. Hence the error
   // message is quite ugly
+  /**
+   * @param $pearError
+   */
   public static function simpleHandler($pearError) {
 
     // create the error array
@@ -256,17 +297,21 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   }
 
   /**
-   * display an error page with an error message describing what happened
+   * Display an error page with an error message describing what happened
    *
-   * @param string message  the error message
-   * @param string code     the error code if any
-   * @param string email    the email address to notify of this situation
+   * @param string $message
+   *   The error message.
+   * @param string $code
+   *   The error code if any.
+   * @param string $email
+   *   The email address to notify of this situation.
+   *
+   * @throws Exception
    *
    * @return void
    * @static
-   * @acess public
    */
-  static function fatal($message = NULL, $code = NULL, $email = NULL) {
+  public static function fatal($message = NULL, $code = NULL, $email = NULL) {
     $vars = array(
       'message' => $message,
       'code' => $code,
@@ -280,7 +325,7 @@ class CRM_Core_Error extends PEAR_ErrorStack {
       $details = 'A fatal error was triggered';
       if ($message) {
         $details .= ': ' . $message;
-    }
+      }
       throw new Exception($details, $code);
     }
 
@@ -311,6 +356,13 @@ class CRM_Core_Error extends PEAR_ErrorStack {
       }
     }
 
+    if ($config->backtrace) {
+      self::backtrace();
+    }
+
+    CRM_Core_Error::debug_var('Fatal Error Details', $vars);
+    CRM_Core_Error::backtrace('backTrace', TRUE);
+
     // If we are in an ajax callback, format output appropriately
     if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
       $out = array(
@@ -326,34 +378,16 @@ class CRM_Core_Error extends PEAR_ErrorStack {
       CRM_Core_Page_AJAX::returnJsonResponse($out);
     }
 
-    if ($config->backtrace) {
-      self::backtrace();
-    }
-
     $template = CRM_Core_Smarty::singleton();
     $template->assign($vars);
 
-    CRM_Core_Error::debug_var('Fatal Error Details', $vars);
-    CRM_Core_Error::backtrace('backTrace', TRUE);
-    $content = $template->fetch($config->fatalErrorTemplate);
-    // JErrorPage exists only in 3.x and not 2.x
-    // CRM-13714
-    if ($config->userFramework == 'Joomla' && class_exists('JErrorPage')) {
-      $error = new Exception($content);
-      JErrorPage::render($error);
-    }
-    else if ($config->userFramework == 'Joomla' && class_exists('JError')) {
-      JError::raiseError('CiviCRM-001', $content);
-    }
-    else {
-      echo CRM_Utils_System::theme($content);
-    }
+    $config->userSystem->outputError($template->fetch($config->fatalErrorTemplate));
 
     self::abend(CRM_Core_Error::FATAL_ERROR);
   }
 
   /**
-   * display an error page with an error message describing what happened
+   * Display an error page with an error message describing what happened
    *
    * This function is evil -- it largely replicates fatal(). Hopefully the
    * entire CRM_Core_Error system can be hollowed out and replaced with
@@ -363,9 +397,14 @@ class CRM_Core_Error extends PEAR_ErrorStack {
    *
    * @return void
    * @static
-   * @acess public
    */
-  static function handleUnhandledException($exception) {
+  public static function handleUnhandledException($exception) {
+    try {
+      CRM_Utils_Hook::unhandledException($exception);
+    } catch (Exception $other) {
+      // if the exception-handler generates an exception, then that sucks! oh, well. carry on.
+      CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other));
+    }
     $config = CRM_Core_Config::singleton();
     $vars = array(
       'message' => $exception->getMessage(),
@@ -426,22 +465,21 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   }
 
   /**
-   * outputs pre-formatted debug information. Flushes the buffers
+   * Outputs pre-formatted debug information. Flushes the buffers
    * so we can interrupt a potential POST/redirect
    *
-   * @param  string name of debug section
-   * @param  mixed  reference to variables that we need a trace of
-   * @param  bool   should we log or return the output
-   * @param  bool   whether to generate a HTML-escaped output
-   * @param  bool   should we check permissions before displaying output
+   * @param string name of debug section
+   * @param mixed reference to variables that we need a trace of
+   * @param bool should we log or return the output
+   * @param bool whether to generate a HTML-escaped output
+   * @param bool should we check permissions before displaying output
    *                useful when we die during initialization and permissioning
    *                subsystem is not initialized - CRM-13765
    *
    * @return string the generated output
-   * @access public
    * @static
    */
-  static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
+  public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
     $error = self::singleton();
 
     if ($variable === NULL) {
@@ -478,25 +516,29 @@ class CRM_Core_Error extends PEAR_ErrorStack {
    * Similar to the function debug. Only difference is
    * in the formatting of the output.
    *
-   * @param  string variable name
-   * @param  mixed  reference to variables that we need a trace of
-   * @param  bool   should we use print_r ? (else we use var_dump)
-   * @param  bool   should we log or return the output
+   * @param string $variable_name
+   * @param mixed $variable
+   * @param bool $print
+   *   Should we use print_r ? (else we use var_dump).
+   * @param bool $log
+   *   Should we log or return the output.
+   * @param string $comp
+   *   Variable name.
    *
    * @return string the generated output
    *
-   * @access public
    *
    * @static
    *
    * @see CRM_Core_Error::debug()
    * @see CRM_Core_Error::debug_log_message()
    */
-  static function debug_var($variable_name,
+  static function debug_var(
+    $variable_name,
     $variable,
     $print = TRUE,
-    $log   = TRUE,
-    $comp  = ''
+    $log = TRUE,
+    $comp = ''
   ) {
     // check if variable is set
     if (!isset($variable)) {
@@ -524,18 +566,20 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   }
 
   /**
-   * display the error message on terminal
+   * Display the error message on terminal
    *
-   * @param  string message to be output
-   * @param  bool   should we log or return the output
+   * @param $message
+   * @param bool $out
+   *   Should we log or return the output.
    *
+   * @param string $comp
+   *   Message to be output.
    * @return string format of the backtrace
    *
-   * @access public
    *
    * @static
    */
-  static function debug_log_message($message, $out = FALSE, $comp = '') {
+  public static function debug_log_message($message, $out = FALSE, $comp = '') {
     $config = CRM_Core_Config::singleton();
 
     $file_log = self::createDebugLogger($comp);
@@ -547,6 +591,7 @@ class CRM_Core_Error extends PEAR_ErrorStack {
     $file_log->close();
 
     if ($config->userFrameworkLogging) {
+      // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
       if ($config->userSystem->is_drupal and function_exists('watchdog')) {
         watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG);
       }
@@ -558,22 +603,38 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   /**
    * Append to the query log (if enabled)
    */
-  static function debug_query($string) {
+  public static function debug_query($string) {
     if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) {
       if ( CIVICRM_DEBUG_LOG_QUERY == 'backtrace' ) {
-        CRM_Core_Error::backtrace( $string, true );
+        CRM_Core_Error::backtrace( $string, TRUE );
       } else if ( CIVICRM_DEBUG_LOG_QUERY ) {
-        CRM_Core_Error::debug_var( 'Query', $string, false, true );
+        CRM_Core_Error::debug_var( 'Query', $string, FALSE, TRUE );
       }
     }
   }
 
+  /**
+   * Execute a query and log the results.
+   *
+   * @param string $query
+   */
+  public static function debug_query_result($query) {
+    $dao = CRM_Core_DAO::executeQuery($query);
+    $results = array();
+    while ($dao->fetch()) {
+      $results[] = (array) $dao;
+    }
+    CRM_Core_Error::debug_var('dao result', array('query' => $query, 'results' => $results));
+  }
+
   /**
    * Obtain a reference to the error log
    *
+   * @param string $comp
+   *
    * @return Log
    */
-  static function createDebugLogger($comp = '') {
+  public static function createDebugLogger($comp = '') {
     $config = CRM_Core_Config::singleton();
 
     if ($comp) {
@@ -601,7 +662,11 @@ class CRM_Core_Error extends PEAR_ErrorStack {
     return Log::singleton('file', $fileName);
   }
 
-  static function backtrace($msg = 'backTrace', $log = FALSE) {
+  /**
+   * @param string $msg
+   * @param bool $log
+   */
+  public static function backtrace($msg = 'backTrace', $log = FALSE) {
     $backTrace = debug_backtrace();
     $message = self::formatBacktrace($backTrace);
     if (!$log) {
@@ -615,71 +680,86 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   /**
    * Render a backtrace array as a string
    *
-   * @param array $backTrace array of stack frames
-   * @param boolean $showArgs 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
-   * @param int $maxArgLen maximum number of characters to show from each argument string
+   * @param array $backTrace
+   *   Array of stack frames.
+   * @param bool $showArgs
+   *   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.
+   * @param int $maxArgLen
+   *   Maximum number of characters to show from each argument string.
    * @return string printable plain-text
    */
-  static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
+  public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
     $message = '';
     foreach (self::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
       $message .= sprintf("#%s %s\n", $idx, $trace);
     }
-    $message .= sprintf("#%s {main}\n", 1+$idx);
+    $message .= sprintf("#%s {main}\n", 1 + $idx);
     return $message;
   }
 
   /**
    * Render a backtrace array as an array
    *
-   * @param array $backTrace array of stack frames
-   * @param boolean $showArgs 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
-   * @param int $maxArgLen maximum number of characters to show from each argument string
+   * @param array $backTrace
+   *   Array of stack frames.
+   * @param bool $showArgs
+   *   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.
+   * @param int $maxArgLen
+   *   Maximum number of characters to show from each argument string.
    * @return array
    * @see debug_backtrace
    * @see Exception::getTrace()
    */
-  static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
+  public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
     $ret = array();
     foreach ($backTrace as $trace) {
       $args = array();
       $fnName = CRM_Utils_Array::value('function', $trace);
       $className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : '';
 
-      // do now show args for a few password related functions
+      // Do not show args for a few password related functions
       $skipArgs = ($className == 'DB::' && $fnName == 'connect') ? TRUE : FALSE;
 
-      foreach ($trace['args'] as $arg) {
-        if (! $showArgs || $skipArgs) {
-          $args[] = '(' . gettype($arg) . ')';
-          continue;
-        }
-        switch ($type = gettype($arg)) {
-          case 'boolean':
-            $args[] = $arg ? 'TRUE' : 'FALSE';
-            break;
-          case 'integer':
-          case 'double':
-            $args[] = $arg;
-            break;
-          case 'string':
-            $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
-            break;
-          case 'array':
-            $args[] = '(Array:'.count($arg).')';
-            break;
-          case 'object':
-            $args[] = 'Object(' . get_class($arg) . ')';
-            break;
-          case 'resource':
-            $args[] = 'Resource';
-            break;
-          case 'NULL':
-            $args[] = 'NULL';
-            break;
-          default:
-            $args[] = "($type)";
-            break;
+      if (!empty($trace['args'])) {
+        foreach ($trace['args'] as $arg) {
+          if (! $showArgs || $skipArgs) {
+            $args[] = '(' . gettype($arg) . ')';
+            continue;
+          }
+          switch ($type = gettype($arg)) {
+            case 'boolean':
+              $args[] = $arg ? 'TRUE' : 'FALSE';
+              break;
+
+            case 'integer':
+            case 'double':
+              $args[] = $arg;
+              break;
+
+            case 'string':
+              $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
+              break;
+
+            case 'array':
+              $args[] = '(Array:'.count($arg).')';
+              break;
+
+            case 'object':
+              $args[] = 'Object(' . get_class($arg) . ')';
+              break;
+
+            case 'resource':
+              $args[] = 'Resource';
+              break;
+
+            case 'NULL':
+              $args[] = 'NULL';
+              break;
+
+            default:
+              $args[] = "($type)";
+              break;
+          }
         }
       }
 
@@ -701,7 +781,7 @@ class CRM_Core_Error extends PEAR_ErrorStack {
    * @param Exception $e
    * @return string printable HTML text
    */
-  static function formatHtmlException(Exception $e) {
+  public static function formatHtmlException(Exception $e) {
     $msg = '';
 
     // Exception metadata
@@ -716,11 +796,11 @@ class CRM_Core_Error extends PEAR_ErrorStack {
           $msg .= '<tbody>';
           foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
             $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
-    }
+          }
           $msg .= '</tbody></table>';
-    }
+        }
         $ei = $ei->getCause();
-  }
+      }
       $msg .= $e->toHtml();
     } else {
       $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
@@ -735,7 +815,7 @@ class CRM_Core_Error extends PEAR_ErrorStack {
    * @param Exception $e
    * @return string printable plain text
    */
-  static function formatTextException(Exception $e) {
+  public static function formatTextException(Exception $e) {
     $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
 
     $ei = $e;
@@ -751,7 +831,15 @@ class CRM_Core_Error extends PEAR_ErrorStack {
     return $msg;
   }
 
-  static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
+  /**
+   * @param $message
+   * @param int $code
+   * @param string $level
+   * @param array $params
+   *
+   * @return object
+   */
+  public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
     $error = CRM_Core_Error::singleton();
     $error->push($code, $level, array($params), $message);
     return $error;
@@ -760,18 +848,23 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   /**
    * Set a status message in the session, then bounce back to the referrer.
    *
-   * @param string $status        The status message to set
+   * @param string $status
+   *   The status message to set.
    *
+   * @param null $redirect
+   * @param string $title
    * @return void
-   * @access public
    * @static
    */
-  public static function statusBounce($status, $redirect = NULL, $title = '') {
+  public static function statusBounce($status, $redirect = NULL, $title = NULL) {
     $session = CRM_Core_Session::singleton();
     if (!$redirect) {
       $redirect = $session->readUserContext();
     }
-    $session->setStatus($status, $title);
+    if ($title === NULL) {
+      $title = ts('Error');
+    }
+    $session->setStatus($status, $title, 'alert', array('expires' => 0));
     if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
       CRM_Core_Page_AJAX::returnJsonResponse(array('status' => 'error'));
     }
@@ -779,9 +872,8 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   }
 
   /**
-   * Function to reset the error stack
+   * Reset the error stack
    *
-   * @access public
    * @static
    */
   public static function reset() {
@@ -804,9 +896,9 @@ class CRM_Core_Error extends PEAR_ErrorStack {
   /**
    * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
    *
-   * @param object $obj       The PEAR_ERROR object
+   * @param object $obj
+   *   The PEAR_ERROR object.
    * @return object $obj
-   * @access public
    * @static
    */
   public static function nullHandler($obj) {
@@ -820,6 +912,13 @@ class CRM_Core_Error extends PEAR_ErrorStack {
    * This function is no longer used by v3 api.
    * @fixme Some core files call it but it should be re-thought & renamed or removed
    */
+  /**
+   * @param $msg
+   * @param null $data
+   *
+   * @return array
+   * @throws Exception
+   */
   public static function &createAPIError($msg, $data = NULL) {
     if (self::$modeException) {
       throw new Exception($msg, $data);
@@ -835,6 +934,9 @@ class CRM_Core_Error extends PEAR_ErrorStack {
     return $values;
   }
 
+  /**
+   * @param $file
+   */
   public static function movedSiteError($file) {
     $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend',
       'reset=1',
@@ -855,6 +957,12 @@ class CRM_Core_Error extends PEAR_ErrorStack {
     CRM_Utils_System::civiExit($code);
   }
 
+  /**
+   * @param $error
+   * @param const $type
+   *
+   * @return bool
+   */
   public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) {
     if (is_array($error) && !empty($error['is_error'])) {
       $code = $error['error_message']['code'];