Merge pull request #5035 from TeNNoX/master
[civicrm-core.git] / api / v3 / Contribution.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
731a0992 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 * File for the CiviCRM APIv3 Contribution functions
30 *
31 * @package CiviCRM_APIv3
32 * @subpackage API_Contribute
33 *
731a0992 34 * @copyright CiviCRM LLC (c) 2004-2014
6a488035 35 * @version $Id: Contribution.php 30486 2010-11-02 16:12:09Z shot $
6a488035
TO
36 */
37
38/**
9d32e6f7 39 * Add or update a contribution.
6a488035 40 *
cf470720 41 * @param array $params
9d32e6f7 42 * Input parameters.
6a488035 43 *
69dbd1ba 44 * @throws API_Exception
a6c01b45 45 * @return array
72b3a70c 46 * Api result array
6a488035
TO
47 */
48function civicrm_api3_contribution_create(&$params) {
49 $values = array();
6a488035 50 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
504a78f6 51 $params = array_merge($params, $values);
52
8cc574cf 53 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
504a78f6 54 $error = array();
55 //throw error for invalid status change such as setting completed back to pending
56 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
57 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
58 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
59 if (array_key_exists('contribution_status_id', $error)) {
60 throw new API_Exception($error['contribution_status_id']);
61 }
6a488035 62 }
6a516bd6
DG
63
64 _civicrm_api3_contribution_create_legacy_support_45($params);
65
9d32e6f7 66 // Make sure tax calculation is handled via api.
b5935203 67 $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
ebf2b57b 68
504a78f6 69 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
6a488035 70}
11e09c59
TO
71
72/**
0aa0303c
EM
73 * Adjust Metadata for Create action.
74 *
75 * The metadata is used for setting defaults, documentation & validation.
6a488035 76 *
cf470720
TO
77 * @param array $params
78 * Array or parameters determined by getfields.
6a488035
TO
79 */
80function _civicrm_api3_contribution_create_spec(&$params) {
81 $params['contact_id']['api.required'] = 1;
82 $params['total_amount']['api.required'] = 1;
53191813 83 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
8757a378 84 $params['receive_date']['api.default'] = 'now';
6a488035
TO
85 $params['payment_processor'] = array(
86 'name' => 'payment_processor',
87 'title' => 'Payment Processor ID',
88 'description' => 'ID of payment processor used for this contribution',
89 // field is called payment processor - not payment processor id but can only be one id so
90 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
91 'api.aliases' => array('payment_processor_id'),
92 );
93 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
94 $params['financial_type_id']['api.required'] = 1;
95 $params['note'] = array(
96 'name' => 'note',
97 'uniqueName' => 'contribution_note',
98 'title' => 'note',
99 'type' => 2,
100 'description' => 'Associated Note in the notes table',
101 );
102 $params['soft_credit_to'] = array(
103 'name' => 'soft_credit_to',
33a429d4 104 'title' => 'Soft Credit contact ID (legacy)',
6a488035 105 'type' => 1,
33a429d4 106 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
6a488035
TO
107 'FKClassName' => 'CRM_Contact_DAO_Contact',
108 );
6a516bd6
DG
109 $params['honor_contact_id'] = array(
110 'name' => 'honor_contact_id',
33a429d4 111 'title' => 'Honoree contact ID (legacy)',
6a516bd6 112 'type' => 1,
33a429d4 113 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
6a516bd6
DG
114 'FKClassName' => 'CRM_Contact_DAO_Contact',
115 );
33a429d4
CW
116 $params['honor_type_id'] = array(
117 'name' => 'honor_type_id',
118 'title' => 'Honoree Type (legacy)',
119 'type' => 1,
120 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
121 'pseudoconstant' => TRUE,
122 );
6a488035 123 // note this is a recommended option but not adding as a default to avoid
c206647d 124 // creating unnecessary changes for the dev
6a488035
TO
125 $params['skipRecentView'] = array(
126 'name' => 'skipRecentView',
127 'title' => 'Skip adding to recent view',
0900b21e 128 'type' => CRM_Utils_Type::T_BOOLEAN,
6a488035
TO
129 'description' => 'Do not add to recent view (setting this improves performance)',
130 );
131 $params['skipLineItem'] = array(
132 'name' => 'skipLineItem',
133 'title' => 'Skip adding line items',
134 'type' => 1,
135 'api.default' => 0,
136 'description' => 'Do not add line items by default (if you wish to add your own)',
137 );
599c61ac
E
138 $params['batch_id'] = array(
139 'title' => 'Batch',
140 'type' => 1,
141 'description' => 'Batch which relevant transactions should be added to',
142 );
6a488035
TO
143}
144
6a516bd6 145/**
9d32e6f7
EM
146 * Support for schema changes made in 4.5.
147 *
35671d00
TO
148 * The main purpose of the API is to provide integrators a level of stability not provided by
149 * the core code or schema - this means we have to provide support for api calls (where possible)
150 * across schema changes.
dc64d047 151 *
d0997921 152 * @param array $params
35671d00 153 */
9b873358 154function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
6a516bd6 155 //legacy soft credit handling - recommended approach is chaining
9b873358 156 if (!empty($params['soft_credit_to'])) {
33a429d4 157 $params['soft_credit'][] = array(
6a516bd6
DG
158 'contact_id' => $params['soft_credit_to'],
159 'amount' => $params['total_amount'],
21dfd5f5 160 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
33a429d4 161 );
6a516bd6 162 }
9b873358 163 if (!empty($params['honor_contact_id'])) {
33a429d4 164 $params['soft_credit'][] = array(
6a516bd6
DG
165 'contact_id' => $params['honor_contact_id'],
166 'amount' => $params['total_amount'],
21dfd5f5 167 'soft_credit_type_id' => CRM_Utils_Array::value('honor_type_id', $params, CRM_Core_OptionGroup::getValue('soft_credit_type', 'in_honor_of', 'name')),
33a429d4 168 );
6a516bd6
DG
169 }
170}
171
6a488035 172/**
9d32e6f7 173 * Delete a contribution.
6a488035 174 *
cf470720 175 * @param array $params
9d32e6f7 176 * Input parameters.
6a488035 177 *
9d32e6f7 178 * @return array
6a488035
TO
179 */
180function civicrm_api3_contribution_delete($params) {
181
0d8afee2 182 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
6a488035
TO
183 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
184 return civicrm_api3_create_success(array($contributionID => 1));
185 }
186 else {
187 return civicrm_api3_create_error('Could not delete contribution');
188 }
189}
11e09c59
TO
190
191/**
9d32e6f7
EM
192 * Modify metadata for delete action.
193 *
194 * Legacy support for contribution_id.
195 *
d0997921 196 * @param array $params
6a488035
TO
197 */
198function _civicrm_api3_contribution_delete_spec(&$params) {
199 $params['id']['api.aliases'] = array('contribution_id');
200}
201
202/**
35823763 203 * Retrieve a set of contributions.
6a488035 204 *
cf470720 205 * @param array $params
35823763 206 * Input parameters.
69dbd1ba 207 *
a6c01b45 208 * @return array
16b10e64 209 * Array of contributions, if error an array with an error id and error message
6a488035
TO
210 */
211function civicrm_api3_contribution_get($params) {
212
82f7d8b2
EM
213 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
214 $entity = 'contribution';
215 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, $entity);
6a488035
TO
216
217 $contribution = array();
218 while ($dao->fetch()) {
219 //CRM-8662
76ca3345 220 $contribution_details = $query->store($dao);
35671d00 221 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id, TRUE);
76ca3345 222 $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution);
76ca3345
KJ
223 // format soft credit for backward compatibility
224 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
6a488035
TO
225 }
226 return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao);
227}
11e09c59 228
76ca3345 229/**
1747ab99
EM
230 * This function is used to format the soft credit for backward compatibility.
231 *
232 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
76ca3345 233 * but we still return first soft credit as a part of contribution array
dc64d047 234 *
645ee340 235 * @param $contribution
76ca3345
KJ
236 */
237function _civicrm_api3_format_soft_credit(&$contribution) {
238 if (!empty($contribution['soft_credit'])) {
239 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
240 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
241 }
242}
243
11e09c59 244/**
1747ab99 245 * Adjust Metadata for Get action.
6a488035 246 *
0aa0303c
EM
247 * The metadata is used for setting defaults, documentation & validation.
248 *
cf470720
TO
249 * @param array $params
250 * Array or parameters determined by getfields.
6a488035
TO
251 */
252function _civicrm_api3_contribution_get_spec(&$params) {
253 $params['contribution_test']['api.default'] = 0;
4c41ecb2 254 $params['contribution_test']['title'] = 'Get Test Contributions?';
6a488035
TO
255 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
256 $params['contact_id'] = $params['contribution_contact_id'];
257 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
258 unset($params['contribution_contact_id']);
259}
260
261/**
1747ab99
EM
262 * Legacy handling for contribution parameters.
263 *
264 * Take the input parameter list as specified in the data model and
265 * convert it into the same format that we use in QF and BAO object.
6a488035 266 *
cf470720 267 * @param array $params
c23f45d3 268 * property name/value pairs to insert in new contact.
cf470720
TO
269 * @param array $values
270 * The reformatted properties that we can use internally.
6a488035 271 *
c23f45d3 272 * @return array
6a488035 273 */
c23f45d3 274function _civicrm_api3_contribute_format_params($params, &$values) {
35671d00 275 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
6a488035 276 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
6a488035
TO
277 return array();
278}
279
16c0ec8d 280/**
1747ab99 281 * Adjust Metadata for Transact action.
16c0ec8d 282 *
0aa0303c
EM
283 * The metadata is used for setting defaults, documentation & validation.
284 *
cf470720
TO
285 * @param array $params
286 * Array or parameters determined by getfields.
16c0ec8d
CW
287 */
288function _civicrm_api3_contribution_transact_spec(&$params) {
4c41ecb2
EM
289 $fields = civicrm_api3('contribution', 'getfields', array('action' => 'create'));
290 $params = array_merge($params, $fields['values']);
16c0ec8d
CW
291 $params['receive_date']['api.default'] = 'now';
292}
293
6a488035
TO
294/**
295 * Process a transaction and record it against the contact.
296 *
cf470720 297 * @param array $params
1747ab99 298 * Input parameters.
6a488035 299 *
a6c01b45 300 * @return array
c23f45d3 301 * contribution of created or updated record (or a civicrm error)
6a488035
TO
302 */
303function civicrm_api3_contribution_transact($params) {
16c0ec8d 304 // Set some params specific to payment processing
8319cf11
EM
305 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
306 // 'is_error' set
307 // also trxn_id is not saved.
308 // but since there is no test it's not desirable to jump in & make the obvious changes.
16c0ec8d
CW
309 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
310 $params['amount'] = $params['total_amount'];
6a488035
TO
311 if (!isset($params['net_amount'])) {
312 $params['net_amount'] = $params['amount'];
313 }
6a488035
TO
314 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
315 $params['invoiceID'] = $params['invoice_id'];
316 }
317
be06e507
CW
318 // Some payment processors expect a unique invoice_id - generate one if not supplied
319 $params['invoice_id'] = CRM_Utils_Array::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
320
16c0ec8d 321 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
6a488035
TO
322 if (civicrm_error($paymentProcessor)) {
323 return $paymentProcessor;
324 }
325
16c0ec8d 326 $payment = CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
6a488035
TO
327 if (civicrm_error($payment)) {
328 return $payment;
329 }
330
8319cf11 331 $transaction = $payment->doPayment($params);
6a488035 332
26ad2b72 333 $params['payment_instrument_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ? 'Credit Card' : 'Debit Card';
16c0ec8d 334 return civicrm_api('contribution', 'create', $params);
6a488035 335}
69dbd1ba 336
6a488035 337/**
1747ab99
EM
338 * Send a contribution confirmation (receipt or invoice).
339 *
6a488035
TO
340 * The appropriate online template will be used (the existence of related objects
341 * (e.g. memberships ) will affect this selection
69dbd1ba 342 *
cf470720
TO
343 * @param array $params
344 * Input parameters.
69dbd1ba
EM
345 *
346 * @throws Exception
6a488035
TO
347 */
348function civicrm_api3_contribution_sendconfirmation($params) {
349 $contribution = new CRM_Contribute_BAO_Contribution();
350 $contribution->id = $params['id'];
acb1052e 351 if (!$contribution->find(TRUE)) {
6a488035 352 throw new Exception('Contribution does not exist');
35671d00 353 }
6a488035 354 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
76ca3345
KJ
355 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
356 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
6a488035
TO
357}
358
11e09c59 359/**
1747ab99 360 * Adjust Metadata for sendconfirmation action.
6a488035 361 *
0aa0303c
EM
362 * The metadata is used for setting defaults, documentation & validation.
363 *
cf470720
TO
364 * @param array $params
365 * Array or parameters determined by getfields.
6a488035
TO
366 */
367function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
368 $params['id'] = array(
369 'api.required' => 1,
21dfd5f5 370 'title' => 'Contribution ID',
6a488035
TO
371 );
372 $params['receipt_from_email'] = array(
35671d00 373 'api.required' => 1,
6a0cf2c6
CW
374 'title' => 'From Email address (string) required until someone provides a patch :-)',
375 );
376 $params['receipt_from_name'] = array(
377 'title' => 'From Name (string)',
378 );
379 $params['cc_receipt'] = array(
380 'title' => 'CC Email address (string)',
381 );
382 $params['bcc_receipt'] = array(
383 'title' => 'BCC Email address (string)',
384 );
385 $params['receipt_text'] = array(
386 'title' => 'Message (string)',
6a488035
TO
387 );
388}
0efa8efe 389
390/**
1747ab99
EM
391 * Complete an existing (pending) transaction.
392 *
393 * This will update related entities (participant, membership, pledge etc)
394 * and take any complete actions from the contribution page (e.g. send receipt).
0efa8efe 395 *
396 * @todo - most of this should live in the BAO layer but as we want it to be an addition
397 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
398 *
cf470720
TO
399 * @param array $params
400 * Input parameters.
69dbd1ba
EM
401 *
402 * @throws API_Exception
acb1052e 403 * Api result array.
0efa8efe 404 */
405function civicrm_api3_contribution_completetransaction(&$params) {
406
407 $input = $ids = array();
408 $contribution = new CRM_Contribute_BAO_Contribution();
409 $contribution->id = $params['id'];
410 $contribution->find(TRUE);
9b873358 411 if (!$contribution->id == $params['id']) {
0efa8efe 412 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
413 }
414 try {
9b873358 415 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
0efa8efe 416 throw new API_Exception('failed to load related objects');
417 }
1ba809f7 418 elseif ($contribution->contribution_status_id == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
9e2ee07b
EM
419 throw new API_Exception(ts('Contribution already completed'));
420 }
0efa8efe 421 $objects = $contribution->_relatedObjects;
422 $objects['contribution'] = &$contribution;
423 $input['component'] = $contribution->_component;
424 $input['is_test'] = $contribution->is_test;
35671d00 425 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
0efa8efe 426 $input['amount'] = $contribution->total_amount;
9b873358 427 if (isset($params['is_email_receipt'])) {
0efa8efe 428 $input['is_email_receipt'] = $params['is_email_receipt'];
429 }
430 // @todo required for base ipn but problematic as api layer handles this
431 $transaction = new CRM_Core_Transaction();
432 $ipn = new CRM_Core_Payment_BaseIPN();
f6780fb8 433 $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id));
0efa8efe 434 }
0e37ad72 435 catch(Exception $e) {
0efa8efe 436 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
437 }
438}
439
aa1b1481 440/**
9d32e6f7
EM
441 * Provide function metadata.
442 *
c490a46a 443 * @param array $params
aa1b1481 444 */
3dfbdece 445function _civicrm_api3_contribution_completetransaction_spec(&$params) {
eac25df2
EM
446 $params['id'] = array(
447 'title' => 'Contribution ID',
448 'type' => CRM_Utils_Type::T_INT,
449 'api.required' => TRUE,
450 );
451 $params['trxn_id'] = array(
452 'title' => 'Transaction ID',
453 'type' => CRM_Utils_Type::T_STRING,
454 );
455 $params['is_email_receipt'] = array(
456 'title' => 'Send email Receipt?',
457 'type' => CRM_Utils_Type::T_BOOLEAN,
458 );
0efa8efe 459}