Merge pull request #2786 from ar-jan/CRM-13946
[civicrm-core.git] / api / v3 / Contribution.php
index 09542ddf2a082b75045e9089255800149a11cb68..cd9f8f79d317a59fce43b5878749053889b40660 100644 (file)
@@ -1,9 +1,8 @@
 <?php
-// $Id$
 
 /*
  +--------------------------------------------------------------------+
- | CiviCRM version 4.3                                                |
+ | CiviCRM version 4.4                                                |
  +--------------------------------------------------------------------+
  | Copyright CiviCRM LLC (c) 2004-2013                                |
  +--------------------------------------------------------------------+
  */
 function civicrm_api3_contribution_create(&$params) {
   $values = array();
-
-  _civicrm_api3_contribute_format_params($params, $values);
-
   _civicrm_api3_custom_format_params($params, $values, 'Contribution');
-  $values["contact_id"] = CRM_Utils_Array::value('contact_id', $params);
-  $values["source"] = CRM_Utils_Array::value('source', $params);
+  $params = array_merge($params, $values);
 
-  $ids = array();
-  if (CRM_Utils_Array::value('id', $params)) {
-    $ids['contribution'] = $params['id'];
-    // CRM-12498
-    if (CRM_Utils_Array::value('contribution_status_id', $params)) {
-      $error = array(); 
-      //throw error for invalid status change
-      CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
-      if (array_key_exists('contribution_status_id', $error)) {
-        return civicrm_api3_create_error($error['contribution_status_id']);
-      }
-    }
+  //legacy soft credit handling - recommended approach is chaining
+  if(!empty($params['soft_credit_to'])){
+    $params['soft_credit'] = array(array(
+      'contact_id' => $params['soft_credit_to'],
+      'amount' => $params['total_amount']));
   }
 
-  $contribution = CRM_Contribute_BAO_Contribution::create($values, $ids);
-
-  if (is_a($contribution, 'CRM_Core_Error')) {
-    return civicrm_api3_create_error($contribution->_errors[0]['message']);
+  if (CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('contribution_status_id', $params)) {
+    $error = array();
+    //throw error for invalid status change such as setting completed back to pending
+    //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
+    // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
+    CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
+    if (array_key_exists('contribution_status_id', $error)) {
+      throw new API_Exception($error['contribution_status_id']);
+    }
   }
-  _civicrm_api3_object_to_array($contribution, $contributeArray[$contribution->id]);
-
-  return civicrm_api3_create_success($contributeArray, $params, 'contribution', 'create', $contribution);
+  return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
 }
 
 /**
@@ -91,6 +82,8 @@ function civicrm_api3_contribution_create(&$params) {
 function _civicrm_api3_contribution_create_spec(&$params) {
   $params['contact_id']['api.required'] = 1;
   $params['total_amount']['api.required'] = 1;
+  $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
+  $params['receive_date']['api.default'] = 'now';
   $params['payment_processor'] = array(
     'name' => 'payment_processor',
     'title' => 'Payment Processor ID',
@@ -120,7 +113,7 @@ function _civicrm_api3_contribution_create_spec(&$params) {
   $params['skipRecentView'] = array(
     'name' => 'skipRecentView',
     'title' => 'Skip adding to recent view',
-    'type' => 1,
+    'type' => CRM_Utils_Type::T_BOOLEAN,
     'description' => 'Do not add to recent view (setting this improves performance)',
   );
   $params['skipLineItem'] = array(
@@ -130,6 +123,11 @@ function _civicrm_api3_contribution_create_spec(&$params) {
     'api.default' => 0,
     'description' => 'Do not add line items by default (if you wish to add your own)',
   );
+  $params['batch_id'] = array(
+    'title' => 'Batch',
+    'type' => 1,
+    'description' => 'Batch which relevant transactions should be added to',
+  );
 }
 
 /**
@@ -177,44 +175,37 @@ function _civicrm_api3_contribution_delete_spec(&$params) {
  */
 function civicrm_api3_contribution_get($params) {
 
-  $options          = _civicrm_api3_get_options_from_params($params, TRUE,'contribution','get');
-  $sort             = CRM_Utils_Array::value('sort', $options, NULL);
-  $offset           = CRM_Utils_Array::value('offset', $options);
-  $rowCount         = CRM_Utils_Array::value('limit', $options);
-  $smartGroupCache  = CRM_Utils_Array::value('smartGroupCache', $params);
-  $inputParams      = CRM_Utils_Array::value('input_params', $options, array());
-  $returnProperties = CRM_Utils_Array::value('return', $options, NULL);
-  require_once 'CRM/Contribute/BAO/Query.php';
-  require_once 'CRM/Contact/BAO/Query.php';
-  if (empty($returnProperties)) {
-    $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties(CRM_Contact_BAO_Query::MODE_CONTRIBUTE);
-  }
-
-  $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams);
-  $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
-    FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE
-  );
-  list($select, $from, $where, $having) = $query->query();
-
-  $sql = "$select $from $where $having";
-
-  if (!empty($sort)) {
-    $sql .= " ORDER BY $sort ";
-  }
-  $sql .= " LIMIT $offset, $rowCount ";
-  $dao = CRM_Core_DAO::executeQuery($sql);
+  $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
+  $entity = 'contribution';
+  list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, $entity);
 
   $contribution = array();
   while ($dao->fetch()) {
     //CRM-8662
-    $contribution_details = $query->store ( $dao );
-    $soft_params = array('contribution_id' => $dao->contribution_id);
-    $soft_contribution = CRM_Contribute_BAO_Contribution::getSoftContribution ( $soft_params , true);
-    $contribution [$dao->contribution_id] = array_merge($contribution_details, $soft_contribution);
+    $contribution_details = $query->store($dao);
+    $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id , TRUE);
+    $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution);
+    if(isset($contribution[$dao->contribution_id]['financial_type_id'])){
+      $contribution[$dao->contribution_id]['financial_type_id'] = $contribution[$dao->contribution_id]['financial_type_id'];
+    }
+    // format soft credit for backward compatibility
+    _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
   }
   return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao);
 }
 
+/**
+ * This function is used to format the soft credit for backward compatibility
+ * as of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
+ * but we still return first soft credit as a part of contribution array
+ */
+function _civicrm_api3_format_soft_credit(&$contribution) {
+  if (!empty($contribution['soft_credit'])) {
+    $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
+    $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
+  }
+}
+
 /**
  * Adjust Metadata for Get action
  *
@@ -243,44 +234,22 @@ function _civicrm_api3_contribution_get_spec(&$params) {
  */
 function _civicrm_api3_contribute_format_params($params, &$values, $create = FALSE) {
 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
-    require_once 'api/v3/utils.php';
   _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
-
-  foreach ($params as $key => $value) {
-    // ignore empty values or empty arrays etc
-    if (CRM_Utils_System::isNull($value)) {
-      continue;
-    }
-    // note that this is legacy handling - these should be handled at the api layer
-    switch ($key) {
-      case 'financial_type' :// should be dealt with either api pseudoconstant in validate_integer fn
-        $contributionTypeId = CRM_Utils_Array::key ( ucfirst ( $value ), CRM_Contribute_PseudoConstant::financialType() );
-        if ($contributionTypeId) {
-          if (CRM_Utils_Array::value('financial_type_id', $values) && $contributionTypeId != $values['financial_type_id']) {
-            throw new Exception("Mismatched Financial Type and Financial Type Id");
-          }
-          $values ['financial_type_id'] = $contributionTypeId;
-        }
-        else {
-          throw new Exception("Invalid Financial Type");
-        }
-        break;
-
-      case 'soft_credit_to':// should be dealt with by validate integer
-        if (!CRM_Utils_Rule::integer($value)) {
-          return civicrm_api3_create_error("$key not a valid Id: $value");
-        }
-        $values['soft_credit_to'] = $value;
-        break;
-
-      default:
-        break;
-    }
-  }
-
   return array();
 }
 
+/**
+ * Adjust Metadata for Transact action
+ *
+ * The metadata is used for setting defaults, documentation & validation
+ * @param array $params array or parameters determined by getfields
+ */
+function _civicrm_api3_contribution_transact_spec(&$params) {
+  // This function calls create, so should inherit create spec
+  _civicrm_api3_contribution_create_spec($params);
+  $params['receive_date']['api.default'] = 'now';
+}
+
 /**
  * Process a transaction and record it against the contact.
  *
@@ -292,42 +261,22 @@ function _civicrm_api3_contribute_format_params($params, &$values, $create = FAL
  *
  */
 function civicrm_api3_contribution_transact($params) {
-  $required = array('amount');
-  foreach ($required as $key) {
-    if (!isset($params[$key])) {
-      return civicrm_api3_create_error("Missing parameter $key: civicrm_contribute_transact() requires a parameter '$key'.");
-    }
-  }
-
-  // allow people to omit some values for convenience
-  // 'payment_processor_id' => NULL /* we could retrieve the default processor here, but only if it's missing to avoid an extra lookup */
-  $defaults = array(
-    'payment_processor_mode' => 'live',
-  );
-  $params = array_merge($defaults, $params);
-
-  // clean up / adjust some values which
-  if (!isset($params['total_amount'])) {
-    $params['total_amount'] = $params['amount'];
-  }
+  // Set some params specific to payment processing
+  $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
+  $params['amount'] = $params['total_amount'];
   if (!isset($params['net_amount'])) {
     $params['net_amount'] = $params['amount'];
   }
-  if (!isset($params['receive_date'])) {
-    $params['receive_date'] = date('Y-m-d');
-  }
   if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
     $params['invoiceID'] = $params['invoice_id'];
   }
 
-  require_once 'CRM/Financial/BAO/PaymentProcessor.php';
-  $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor_id'], $params['payment_processor_mode']);
+  $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
   if (civicrm_error($paymentProcessor)) {
     return $paymentProcessor;
   }
 
-  require_once 'CRM/Core/Payment.php';
-  $payment = &CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
+  $payment = CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
   if (civicrm_error($payment)) {
     return $payment;
   }
@@ -339,7 +288,7 @@ function civicrm_api3_contribution_transact($params) {
 
   // but actually, $payment->doDirectPayment() doesn't return a
   // CRM_Core_Error by itself
-  if (get_class($transaction) == 'CRM_Core_Error') {
+  if (is_object($transaction) && get_class($transaction) == 'CRM_Core_Error') {
     $errs = $transaction->getErrors();
     if (!empty($errs)) {
       $last_error = array_shift($errs);
@@ -347,8 +296,7 @@ function civicrm_api3_contribution_transact($params) {
     }
   }
 
-  $contribution = civicrm_api('contribution', 'create', $params);
-  return $contribution['values'];
+  return civicrm_api('contribution', 'create', $params);
 }
 /**
  * Send a contribution confirmation (receipt or invoice)
@@ -364,16 +312,16 @@ function civicrm_api3_contribution_transact($params) {
 function civicrm_api3_contribution_sendconfirmation($params) {
   $contribution = new CRM_Contribute_BAO_Contribution();
   $contribution->id = $params['id'];
-  if (! $contribution->find(true)) {
+  if (! $contribution->find(TRUE)) {
     throw new Exception('Contribution does not exist');
 }
   $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
-  $contribution->loadRelatedObjects($input, $ids, FALSE, true);
-  $contribution->composeMessageArray($input, $ids, $cvalues, false, false);
+  $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
+  $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
 }
 
 /**
- * Adjust Metadata for Create action
+ * Adjust Metadata for sendconfirmation action
  *
  * The metadata is used for setting defaults, documentation & validation
  * @param array $params array or parameters determined by getfields
@@ -385,8 +333,19 @@ function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
   );
   $params['receipt_from_email'] = array(
     'api.required' =>1,
-    'title' => 'From Email (required until someone provides a patch :-)',
-
+    'title' => 'From Email address (string) required until someone provides a patch :-)',
+  );
+  $params['receipt_from_name'] = array(
+    'title' => 'From Name (string)',
+  );
+  $params['cc_receipt'] = array(
+    'title' => 'CC Email address (string)',
+  );
+  $params['bcc_receipt'] = array(
+    'title' => 'BCC Email address (string)',
+  );
+  $params['receipt_text'] = array(
+    'title' => 'Message (string)',
   );
 }
 
@@ -421,7 +380,7 @@ function civicrm_api3_contribution_completetransaction(&$params) {
     $objects['contribution'] = &$contribution;
     $input['component'] = $contribution->_component;
     $input['is_test'] = $contribution->is_test;
-    $input['trxn_id']= $contribution->trxn_id;
+    $input['trxn_id']= !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
     $input['amount'] = $contribution->total_amount;
     if(isset($params['is_email_receipt'])){
       $input['is_email_receipt'] = $params['is_email_receipt'];
@@ -431,11 +390,23 @@ function civicrm_api3_contribution_completetransaction(&$params) {
     $ipn = new CRM_Core_Payment_BaseIPN();
     $ipn->completeTransaction($input, $ids, $objects, $transaction);
   }
-  catch(Exception$e) {
+  catch(Exception $e) {
     throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
   }
 }
 
 function _civicrm_api3_contribution_completetransaction(&$params) {
-
+  $params['id'] = array(
+    'title' => 'Contribution ID',
+    'type' => CRM_Utils_Type::T_INT,
+    'api.required' => TRUE,
+  );
+  $params['trxn_id'] = array(
+    'title' => 'Transaction ID',
+    'type' => CRM_Utils_Type::T_STRING,
+  );
+  $params['is_email_receipt'] = array(
+    'title' => 'Send email Receipt?',
+    'type' => CRM_Utils_Type::T_BOOLEAN,
+  );
 }