4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.4 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2013 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
30 * File for the CiviCRM APIv3 Contribution functions
32 * @package CiviCRM_APIv3
33 * @subpackage API_Contribute
35 * @copyright CiviCRM LLC (c) 2004-2013
36 * @version $Id: Contribution.php 30486 2010-11-02 16:12:09Z shot $
41 * Add or update a contribution
43 * @param array $params (reference ) input parameters
45 * @return array Api result array
48 * @example ContributionCreate.php
49 * {@getfields Contribution_create}
51 function civicrm_api3_contribution_create(&$params) {
53 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
54 $params = array_merge($params, $values);
56 //legacy soft credit handling - recommended approach is chaining
57 if(!empty($params['soft_credit_to'])){
58 $params['soft_credit'] = array(array(
59 'contact_id' => $params['soft_credit_to'],
60 'amount' => $params['total_amount']));
63 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
65 //throw error for invalid status change such as setting completed back to pending
66 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
67 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
68 CRM_Contribute_BAO_Contribution
::checkStatusValidation(NULL, $params, $error);
69 if (array_key_exists('contribution_status_id', $error)) {
70 throw new API_Exception($error['contribution_status_id']);
73 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__
), $params, 'Contribution');
77 * Adjust Metadata for Create action
79 * The metadata is used for setting defaults, documentation & validation
80 * @param array $params array or parameters determined by getfields
82 function _civicrm_api3_contribution_create_spec(&$params) {
83 $params['contact_id']['api.required'] = 1;
84 $params['total_amount']['api.required'] = 1;
85 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
86 $params['receive_date']['api.default'] = 'now';
87 $params['payment_processor'] = array(
88 'name' => 'payment_processor',
89 'title' => 'Payment Processor ID',
90 'description' => 'ID of payment processor used for this contribution',
91 // field is called payment processor - not payment processor id but can only be one id so
92 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
93 'api.aliases' => array('payment_processor_id'),
95 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
96 $params['financial_type_id']['api.required'] = 1;
97 $params['note'] = array(
99 'uniqueName' => 'contribution_note',
102 'description' => 'Associated Note in the notes table',
104 $params['soft_credit_to'] = array(
105 'name' => 'soft_credit_to',
106 'title' => 'Soft Credit contact ID',
108 'description' => 'ID of Contact to be Soft credited to',
109 'FKClassName' => 'CRM_Contact_DAO_Contact',
111 // note this is a recommended option but not adding as a default to avoid
112 // creating unecessary changes for the dev
113 $params['skipRecentView'] = array(
114 'name' => 'skipRecentView',
115 'title' => 'Skip adding to recent view',
116 'type' => CRM_Utils_Type
::T_BOOLEAN
,
117 'description' => 'Do not add to recent view (setting this improves performance)',
119 $params['skipLineItem'] = array(
120 'name' => 'skipLineItem',
121 'title' => 'Skip adding line items',
124 'description' => 'Do not add line items by default (if you wish to add your own)',
126 $params['batch_id'] = array(
129 'description' => 'Batch which relevant transactions should be added to',
134 * Delete a contribution
136 * @param array $params (reference ) input parameters
138 * @return boolean true if success, else false
141 * {@getfields Contribution_delete}
142 * @example ContributionDelete.php
144 function civicrm_api3_contribution_delete($params) {
146 $contributionID = !empty($params['contribution_id']) ?
$params['contribution_id'] : $params['id'];
147 if (CRM_Contribute_BAO_Contribution
::deleteContribution($contributionID)) {
148 return civicrm_api3_create_success(array($contributionID => 1));
151 return civicrm_api3_create_error('Could not delete contribution');
156 * modify metadata. Legacy support for contribution_id
158 function _civicrm_api3_contribution_delete_spec(&$params) {
159 $params['id']['api.aliases'] = array('contribution_id');
163 * Retrieve a set of contributions, given a set of input params
165 * @param array $params (reference ) input parameters
166 * @param array $returnProperties Which properties should be included in the
167 * returned Contribution object. If NULL, the default
168 * set of properties will be included.
170 * @return array (reference ) array of contributions, if error an array with an error id and error message
173 * {@getfields Contribution_get}
174 * @example ContributionGet.php
176 function civicrm_api3_contribution_get($params) {
178 $options = _civicrm_api3_get_options_from_params($params, TRUE,'contribution','get');
179 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
180 $offset = CRM_Utils_Array
::value('offset', $options);
181 $rowCount = CRM_Utils_Array
::value('limit', $options);
182 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
183 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
184 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
185 if (empty($returnProperties)) {
186 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties(CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
);
189 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
190 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
191 FALSE, FALSE, CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
193 list($select, $from, $where, $having) = $query->query();
195 $sql = "$select $from $where $having";
198 $sql .= " ORDER BY $sort ";
200 $sql .= " LIMIT $offset, $rowCount ";
201 $dao = CRM_Core_DAO
::executeQuery($sql);
203 $contribution = array();
204 while ($dao->fetch()) {
206 $contribution_details = $query->store($dao);
207 $softContribution = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($dao->contribution_id
, TRUE);
208 $contribution[$dao->contribution_id
] = array_merge($contribution_details, $softContribution);
209 if(isset($contribution[$dao->contribution_id
]['financial_type_id'])){
210 $contribution[$dao->contribution_id
]['financial_type_id'] = $contribution[$dao->contribution_id
]['financial_type_id'];
212 // format soft credit for backward compatibility
213 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id
]);
215 return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao);
219 * This function is used to format the soft credit for backward compatibility
220 * as of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
221 * but we still return first soft credit as a part of contribution array
223 function _civicrm_api3_format_soft_credit(&$contribution) {
224 if (!empty($contribution['soft_credit'])) {
225 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
226 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
231 * Adjust Metadata for Get action
233 * The metadata is used for setting defaults, documentation & validation
234 * @param array $params array or parameters determined by getfields
236 function _civicrm_api3_contribution_get_spec(&$params) {
237 $params['contribution_test']['api.default'] = 0;
238 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
239 $params['contact_id'] = $params['contribution_contact_id'];
240 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
241 unset($params['contribution_contact_id']);
245 * take the input parameter list as specified in the data model and
246 * convert it into the same format that we use in QF and BAO object
248 * @param array $params Associative array of property name/value
249 * pairs to insert in new contact.
250 * @param array $values The reformatted properties that we can use internally
253 * @return array|CRM_Error
256 function _civicrm_api3_contribute_format_params($params, &$values, $create = FALSE) {
257 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
258 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
263 * Adjust Metadata for Transact action
265 * The metadata is used for setting defaults, documentation & validation
266 * @param array $params array or parameters determined by getfields
268 function _civicrm_api3_contribution_transact_spec(&$params) {
269 // This function calls create, so should inherit create spec
270 _civicrm_api3_contribution_create_spec($params);
271 $params['receive_date']['api.default'] = 'now';
275 * Process a transaction and record it against the contact.
277 * @param array $params (reference ) input parameters
279 * @return array (reference ) contribution of created or updated record (or a civicrm error)
284 function civicrm_api3_contribution_transact($params) {
285 // Set some params specific to payment processing
286 $params['payment_processor_mode'] = empty($params['is_test']) ?
'live' : 'test';
287 $params['amount'] = $params['total_amount'];
288 if (!isset($params['net_amount'])) {
289 $params['net_amount'] = $params['amount'];
291 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
292 $params['invoiceID'] = $params['invoice_id'];
295 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($params['payment_processor'], $params['payment_processor_mode']);
296 if (civicrm_error($paymentProcessor)) {
297 return $paymentProcessor;
300 $payment = CRM_Core_Payment
::singleton($params['payment_processor_mode'], $paymentProcessor);
301 if (civicrm_error($payment)) {
305 $transaction = $payment->doDirectPayment($params);
306 if (civicrm_error($transaction)) {
310 // but actually, $payment->doDirectPayment() doesn't return a
311 // CRM_Core_Error by itself
312 if (is_object($transaction) && get_class($transaction) == 'CRM_Core_Error') {
313 $errs = $transaction->getErrors();
315 $last_error = array_shift($errs);
316 return CRM_Core_Error
::createApiError($last_error['message']);
320 return civicrm_api('contribution', 'create', $params);
323 * Send a contribution confirmation (receipt or invoice)
324 * The appropriate online template will be used (the existence of related objects
325 * (e.g. memberships ) will affect this selection
326 * @param array $params input parameters
327 * {@getfields Contribution_sendconfirmation}
328 * @return array Api result array
333 function civicrm_api3_contribution_sendconfirmation($params) {
334 $contribution = new CRM_Contribute_BAO_Contribution();
335 $contribution->id
= $params['id'];
336 if (! $contribution->find(TRUE)) {
337 throw new Exception('Contribution does not exist');
339 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
340 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
341 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
345 * Adjust Metadata for sendconfirmation action
347 * The metadata is used for setting defaults, documentation & validation
348 * @param array $params array or parameters determined by getfields
350 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
351 $params['id'] = array(
353 'title' => 'Contribution ID'
355 $params['receipt_from_email'] = array(
357 'title' => 'From Email address (string) required until someone provides a patch :-)',
359 $params['receipt_from_name'] = array(
360 'title' => 'From Name (string)',
362 $params['cc_receipt'] = array(
363 'title' => 'CC Email address (string)',
365 $params['bcc_receipt'] = array(
366 'title' => 'BCC Email address (string)',
368 $params['receipt_text'] = array(
369 'title' => 'Message (string)',
374 * Complete an existing (pending) transaction, updating related entities (participant, membership, pledge etc)
375 * and taking any complete actions from the contribution page (e.g. send receipt)
377 * @todo - most of this should live in the BAO layer but as we want it to be an addition
378 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
380 * @param array $params input parameters
381 * {@getfields Contribution_completetransaction}
382 * @return array Api result array
387 function civicrm_api3_contribution_completetransaction(&$params) {
389 $input = $ids = array();
390 $contribution = new CRM_Contribute_BAO_Contribution();
391 $contribution->id
= $params['id'];
392 $contribution->find(TRUE);
393 if(!$contribution->id
== $params['id']){
394 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
397 if(!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)){
398 throw new API_Exception('failed to load related objects');
400 $objects = $contribution->_relatedObjects
;
401 $objects['contribution'] = &$contribution;
402 $input['component'] = $contribution->_component
;
403 $input['is_test'] = $contribution->is_test
;
404 $input['trxn_id']= $contribution->trxn_id
;
405 $input['amount'] = $contribution->total_amount
;
406 if(isset($params['is_email_receipt'])){
407 $input['is_email_receipt'] = $params['is_email_receipt'];
409 // @todo required for base ipn but problematic as api layer handles this
410 $transaction = new CRM_Core_Transaction();
411 $ipn = new CRM_Core_Payment_BaseIPN();
412 $ipn->completeTransaction($input, $ids, $objects, $transaction);
414 catch(Exception
$e) {
415 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
419 function _civicrm_api3_contribution_completetransaction(&$params) {