Merge pull request #5901 from colemanw/CRM-16557
[civicrm-core.git] / api / v3 / Contribution.php
index 7f3265b3e21983603b58eabe5a6ef1529dc8e42c..b19302837e08137739c1af25341a03fa272f1b6f 100644 (file)
@@ -3,7 +3,7 @@
  +--------------------------------------------------------------------+
  | CiviCRM version 4.6                                                |
  +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2014                                |
+ | Copyright CiviCRM LLC (c) 2004-2015                                |
  +--------------------------------------------------------------------+
  | This file is a part of CiviCRM.                                    |
  |                                                                    |
  */
 
 /**
- * File for the CiviCRM APIv3 Contribution functions
+ * This api exposes CiviCRM Contribution records.
  *
  * @package CiviCRM_APIv3
- * @subpackage API_Contribute
- *
- * @copyright CiviCRM LLC (c) 2004-2014
- * @version $Id: Contribution.php 30486 2010-11-02 16:12:09Z shot $
- *
  */
 
 /**
- * Add or update a contribution
+ * Add or update a Contribution.
  *
  * @param array $params
- *   (reference ) input parameters.
+ *   Input parameters.
  *
  * @throws API_Exception
  * @return array
@@ -61,10 +56,16 @@ function civicrm_api3_contribution_create(&$params) {
       throw new API_Exception($error['contribution_status_id']);
     }
   }
-
+  if (!empty($params['id']) && !empty($params['financial_type_id'])) {
+    $error = array();
+    CRM_Contribute_BAO_Contribution::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
+    if (array_key_exists('financial_type_id', $error)) {
+      throw new API_Exception($error['financial_type_id']);
+    }
+  }
   _civicrm_api3_contribution_create_legacy_support_45($params);
 
-  // make sure tax calculation is handled via api
+  // Make sure tax calculation is handled via api.
   $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
 
   return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
@@ -76,7 +77,7 @@ function civicrm_api3_contribution_create(&$params) {
  * The metadata is used for setting defaults, documentation & validation.
  *
  * @param array $params
- *   Array or parameters determined by getfields.
+ *   Array of parameters determined by getfields.
  */
 function _civicrm_api3_contribution_create_spec(&$params) {
   $params['contact_id']['api.required'] = 1;
@@ -90,6 +91,7 @@ function _civicrm_api3_contribution_create_spec(&$params) {
     // field is called payment processor - not payment processor id but can only be one id so
     // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
     'api.aliases' => array('payment_processor_id'),
+    'type' => CRM_Utils_Type::T_INT,
   );
   $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
   $params['financial_type_id']['api.required'] = 1;
@@ -144,10 +146,12 @@ function _civicrm_api3_contribution_create_spec(&$params) {
 }
 
 /**
- * Support for schema changes made in 4.5
+ * Support for schema changes made in 4.5.
+ *
  * The main purpose of the API is to provide integrators a level of stability not provided by
  * the core code or schema - this means we have to provide support for api calls (where possible)
  * across schema changes.
+ *
  * @param array $params
  */
 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
@@ -169,13 +173,12 @@ function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
 }
 
 /**
- * Delete a contribution
+ * Delete a Contribution.
  *
  * @param array $params
- *   (reference ) input parameters.
+ *   Input parameters.
  *
- * @return bool
- *   true if success, else false
+ * @return array
  */
 function civicrm_api3_contribution_delete($params) {
 
@@ -189,7 +192,10 @@ function civicrm_api3_contribution_delete($params) {
 }
 
 /**
- * modify metadata. Legacy support for contribution_id
+ * Modify metadata for delete action.
+ *
+ * Legacy support for contribution_id.
+ *
  * @param array $params
  */
 function _civicrm_api3_contribution_delete_spec(&$params) {
@@ -208,8 +214,7 @@ function _civicrm_api3_contribution_delete_spec(&$params) {
 function civicrm_api3_contribution_get($params) {
 
   $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
-  $entity = 'contribution';
-  list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, $entity);
+  list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Contribution');
 
   $contribution = array();
   while ($dao->fetch()) {
@@ -220,13 +225,15 @@ function civicrm_api3_contribution_get($params) {
     // 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);
+  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
+ * 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
+ *
  * @param $contribution
  */
 function _civicrm_api3_format_soft_credit(&$contribution) {
@@ -237,25 +244,31 @@ function _civicrm_api3_format_soft_credit(&$contribution) {
 }
 
 /**
- * Adjust Metadata for Get action
+ * Adjust Metadata for Get action.
  *
  * The metadata is used for setting defaults, documentation & validation.
  *
  * @param array $params
- *   Array or parameters determined by getfields.
+ *   Array of parameters determined by getfields.
  */
 function _civicrm_api3_contribution_get_spec(&$params) {
-  $params['contribution_test']['api.default'] = 0;
-  $params['contribution_test']['title'] = 'Get Test Contributions?';
+  $params['contribution_test'] = array(
+    'api.default' => 0,
+    'type' => CRM_Utils_Type::T_BOOLEAN,
+    'title' => 'Get Test Contributions?',
+  );
   $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
+  $params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
   $params['contact_id'] = $params['contribution_contact_id'];
   $params['contact_id']['api.aliases'] = array('contribution_contact_id');
   unset($params['contribution_contact_id']);
 }
 
 /**
- * take the input parameter list as specified in the data model and
- * convert it into the same format that we use in QF and BAO object
+ * Legacy handling for contribution parameters.
+ *
+ * Take the input parameter list as specified in the data model and
+ * convert it into the same format that we use in QF and BAO object.
  *
  * @param array $params
  *   property name/value  pairs to insert in new contact.
@@ -271,15 +284,15 @@ function _civicrm_api3_contribute_format_params($params, &$values) {
 }
 
 /**
- * Adjust Metadata for Transact action
+ * Adjust Metadata for Transact action.
  *
  * The metadata is used for setting defaults, documentation & validation.
  *
  * @param array $params
- *   Array or parameters determined by getfields.
+ *   Array of parameters determined by getfields.
  */
 function _civicrm_api3_contribution_transact_spec(&$params) {
-  $fields = civicrm_api3('contribution', 'getfields', array('action' => 'create'));
+  $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
   $params = array_merge($params, $fields['values']);
   $params['receive_date']['api.default'] = 'now';
 }
@@ -288,7 +301,7 @@ function _civicrm_api3_contribution_transact_spec(&$params) {
  * Process a transaction and record it against the contact.
  *
  * @param array $params
- *   (reference ) input parameters.
+ *   Input parameters.
  *
  * @return array
  *   contribution of created or updated record (or a civicrm error)
@@ -324,11 +337,12 @@ function civicrm_api3_contribution_transact($params) {
   $transaction = $payment->doPayment($params);
 
   $params['payment_instrument_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ? 'Credit Card' : 'Debit Card';
-  return civicrm_api('contribution', 'create', $params);
+  return civicrm_api('Contribution', 'create', $params);
 }
 
 /**
- * Send a contribution confirmation (receipt or invoice)
+ * Send a contribution confirmation (receipt or invoice).
+ *
  * The appropriate online template will be used (the existence of related objects
  * (e.g. memberships ) will affect this selection
  *
@@ -336,7 +350,6 @@ function civicrm_api3_contribution_transact($params) {
  *   Input parameters.
  *
  * @throws Exception
- *   Api result array.
  */
 function civicrm_api3_contribution_sendconfirmation($params) {
   $contribution = new CRM_Contribute_BAO_Contribution();
@@ -350,46 +363,53 @@ function civicrm_api3_contribution_sendconfirmation($params) {
 }
 
 /**
- * Adjust Metadata for sendconfirmation action
+ * Adjust Metadata for sendconfirmation action.
  *
  * The metadata is used for setting defaults, documentation & validation.
  *
  * @param array $params
- *   Array or parameters determined by getfields.
+ *   Array of parameters determined by getfields.
  */
 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
   $params['id'] = array(
     'api.required' => 1,
     'title' => 'Contribution ID',
+    'type' => CRM_Utils_Type::T_INT,
   );
   $params['receipt_from_email'] = array(
     'api.required' => 1,
     'title' => 'From Email address (string) required until someone provides a patch :-)',
+    'type' => CRM_Utils_Type::T_STRING,
   );
   $params['receipt_from_name'] = array(
     'title' => 'From Name (string)',
+    'type' => CRM_Utils_Type::T_STRING,
   );
   $params['cc_receipt'] = array(
     'title' => 'CC Email address (string)',
+    'type' => CRM_Utils_Type::T_STRING,
   );
   $params['bcc_receipt'] = array(
     'title' => 'BCC Email address (string)',
+    'type' => CRM_Utils_Type::T_STRING,
   );
   $params['receipt_text'] = array(
     'title' => 'Message (string)',
+    'type' => CRM_Utils_Type::T_STRING,
   );
 }
 
 /**
- * Complete an existing (pending) transaction, updating related entities (participant, membership, pledge etc)
- * and taking any complete actions from the contribution page (e.g. send receipt)
+ * Complete an existing (pending) transaction.
+ *
+ * This will update related entities (participant, membership, pledge etc)
+ * and take any complete actions from the contribution page (e.g. send receipt).
  *
  * @todo - most of this should live in the BAO layer but as we want it to be an addition
  * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
  *
  * @param array $params
  *   Input parameters.
- * {@getfields Contribution_completetransaction}
  *
  * @throws API_Exception
  *   Api result array.
@@ -410,19 +430,8 @@ function civicrm_api3_contribution_completetransaction(&$params) {
     elseif ($contribution->contribution_status_id == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
       throw new API_Exception(ts('Contribution already completed'));
     }
-    $objects = $contribution->_relatedObjects;
-    $objects['contribution'] = &$contribution;
-    $input['component'] = $contribution->_component;
-    $input['is_test'] = $contribution->is_test;
     $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'];
-    }
-    // @todo required for base ipn but problematic as api layer handles this
-    $transaction = new CRM_Core_Transaction();
-    $ipn = new CRM_Core_Payment_BaseIPN();
-    $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id));
+    $params = _ipn_process_transaction($params, $contribution, $input, $ids);
   }
   catch(Exception $e) {
     throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
@@ -430,7 +439,8 @@ function civicrm_api3_contribution_completetransaction(&$params) {
 }
 
 /**
- * provide function metadata
+ * Provide function metadata.
+ *
  * @param array $params
  */
 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
@@ -447,4 +457,150 @@ function _civicrm_api3_contribution_completetransaction_spec(&$params) {
     'title' => 'Send email Receipt?',
     'type' => CRM_Utils_Type::T_BOOLEAN,
   );
+  $params['receipt_from_email'] = array(
+    'title' => 'Email to send receipt from.',
+    'description' => 'If not provided this will default to being based on domain mail or contribution page',
+    'type' => CRM_Utils_Type::T_EMAIL,
+  );
+  $params['receipt_from_name'] = array(
+    'title' => 'Name to send receipt from',
+    'description' => '. If not provided this will default to domain mail or contribution page',
+    'type' => CRM_Utils_Type::T_STRING,
+  );
+}
+
+/**
+ * Complete an existing (pending) transaction.
+ *
+ * This will update related entities (participant, membership, pledge etc)
+ * and take any complete actions from the contribution page (e.g. send receipt).
+ *
+ * @todo - most of this should live in the BAO layer but as we want it to be an addition
+ * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
+ *
+ * @param array $params
+ *   Input parameters.
+ *
+ * @throws API_Exception
+ *   Api result array.
+ */
+function civicrm_api3_contribution_repeattransaction(&$params) {
+  $input = $ids = array();
+  $contribution = new CRM_Contribute_BAO_Contribution();
+  $contribution->id = $params['original_contribution_id'];
+  if (!$contribution->find(TRUE)) {
+    throw new API_Exception(
+      'A valid original contribution ID is required', 'invalid_data');
+  }
+  $original_contribution = clone $contribution;
+  try {
+    if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
+      throw new API_Exception('failed to load related objects');
+    }
+
+    unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
+    $contribution->contribution_status_id = $params['contribution_status_id'];
+    $contribution->receive_date = $params['receive_date'];
+
+    $passThroughParams = array('trxn_id', 'total_amount', 'campaign_id', 'fee_amount');
+    $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
+
+    $params = _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
+  }
+  catch(Exception $e) {
+    throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
+  }
+}
+
+/**
+ * Calls IPN complete transaction for completing or repeating a transaction.
+ *
+ * The IPN function is overloaded with two purposes - this is simply a wrapper for that
+ * when separating them in the api layer.
+ *
+ * @param array $params
+ * @param CRM_Contribute_BAO_Contribution $contribution
+ * @param array $input
+ *
+ * @param array $ids
+ *
+ * @param CRM_Contribute_BAO_Contribution $firstContribution
+ *
+ * @return mixed
+ */
+function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
+  $objects = $contribution->_relatedObjects;
+  $objects['contribution'] = &$contribution;
+
+  if ($firstContribution) {
+    $objects['first_contribution'] = $firstContribution;
+  }
+  $input['component'] = $contribution->_component;
+  $input['is_test'] = $contribution->is_test;
+  $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
+
+  if (isset($params['is_email_receipt'])) {
+    $input['is_email_receipt'] = $params['is_email_receipt'];
+  }
+  if (empty($contribution->contribution_page_id)) {
+    static $domainFromName;
+    static $domainFromEmail;
+    if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
+      list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
+    }
+    $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
+    $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
+  }
+  // @todo required for base ipn but problematic as api layer handles this
+  $transaction = new CRM_Core_Transaction();
+  $ipn = new CRM_Core_Payment_BaseIPN();
+  $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id));
+  return $params;
+}
+
+/**
+ * Provide function metadata.
+ *
+ * @param array $params
+ */
+function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
+  $params['original_contribution_id'] = array(
+    'title' => 'Original 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,
+  );
+  $params['contribution_status_id'] = array(
+    'title' => 'Contribution Status ID',
+    'name' => 'contribution_status_id',
+    'type' => CRM_Utils_Type::T_INT,
+    'pseudoconstant' => array(
+      'optionGroupName' => 'contribution_status',
+    ),
+    'api.required' => TRUE,
+  );
+  $params['receive_date'] = array(
+    'title' => 'Contribution Receive Date',
+    'name' => 'receive_date',
+    'type' => CRM_Utils_Type::T_DATE,
+    'api.default' => 'now',
+  );
+  $params['trxn_id'] = array(
+    'title' => 'Transaction ID',
+    'name' => 'trxn_id',
+    'type' => CRM_Utils_Type::T_STRING,
+  );
+  $params['payment_processor_id'] = array(
+    'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
+    'title' => 'Payment processor ID',
+    'name' => 'payment_processor_id',
+    'type' => CRM_Utils_Type::T_INT,
+  );
 }