Merge pull request #6127 from colemanw/CRM-16426
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * This api exposes CiviCRM Contribution records.
30 *
31 * @package CiviCRM_APIv3
32 */
33
34 /**
35 * Add or update a Contribution.
36 *
37 * @param array $params
38 * Input parameters.
39 *
40 * @throws API_Exception
41 * @return array
42 * Api result array
43 */
44 function civicrm_api3_contribution_create(&$params) {
45 $values = array();
46 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
47 $params = array_merge($params, $values);
48
49 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
50 $error = array();
51 //throw error for invalid status change such as setting completed back to pending
52 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
53 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
54 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
55 if (array_key_exists('contribution_status_id', $error)) {
56 throw new API_Exception($error['contribution_status_id']);
57 }
58 }
59 if (!empty($params['id']) && !empty($params['financial_type_id'])) {
60 $error = array();
61 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
62 if (array_key_exists('financial_type_id', $error)) {
63 throw new API_Exception($error['financial_type_id']);
64 }
65 }
66 _civicrm_api3_contribution_create_legacy_support_45($params);
67
68 // Make sure tax calculation is handled via api.
69 $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
70
71 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
72 }
73
74 /**
75 * Adjust Metadata for Create action.
76 *
77 * The metadata is used for setting defaults, documentation & validation.
78 *
79 * @param array $params
80 * Array of parameters determined by getfields.
81 */
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'),
94 'type' => CRM_Utils_Type::T_INT,
95 );
96 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
97 $params['financial_type_id']['api.required'] = 1;
98 $params['note'] = array(
99 'name' => 'note',
100 'uniqueName' => 'contribution_note',
101 'title' => 'note',
102 'type' => 2,
103 'description' => 'Associated Note in the notes table',
104 );
105 $params['soft_credit_to'] = array(
106 'name' => 'soft_credit_to',
107 'title' => 'Soft Credit contact ID (legacy)',
108 'type' => 1,
109 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
110 'FKClassName' => 'CRM_Contact_DAO_Contact',
111 );
112 $params['honor_contact_id'] = array(
113 'name' => 'honor_contact_id',
114 'title' => 'Honoree contact ID (legacy)',
115 'type' => 1,
116 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
117 'FKClassName' => 'CRM_Contact_DAO_Contact',
118 );
119 $params['honor_type_id'] = array(
120 'name' => 'honor_type_id',
121 'title' => 'Honoree Type (legacy)',
122 'type' => 1,
123 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
124 'pseudoconstant' => TRUE,
125 );
126 // note this is a recommended option but not adding as a default to avoid
127 // creating unnecessary changes for the dev
128 $params['skipRecentView'] = array(
129 'name' => 'skipRecentView',
130 'title' => 'Skip adding to recent view',
131 'type' => CRM_Utils_Type::T_BOOLEAN,
132 'description' => 'Do not add to recent view (setting this improves performance)',
133 );
134 $params['skipLineItem'] = array(
135 'name' => 'skipLineItem',
136 'title' => 'Skip adding line items',
137 'type' => 1,
138 'api.default' => 0,
139 'description' => 'Do not add line items by default (if you wish to add your own)',
140 );
141 $params['batch_id'] = array(
142 'title' => 'Batch',
143 'type' => 1,
144 'description' => 'Batch which relevant transactions should be added to',
145 );
146 }
147
148 /**
149 * Support for schema changes made in 4.5.
150 *
151 * The main purpose of the API is to provide integrators a level of stability not provided by
152 * the core code or schema - this means we have to provide support for api calls (where possible)
153 * across schema changes.
154 *
155 * @param array $params
156 */
157 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
158 //legacy soft credit handling - recommended approach is chaining
159 if (!empty($params['soft_credit_to'])) {
160 $params['soft_credit'][] = array(
161 'contact_id' => $params['soft_credit_to'],
162 'amount' => $params['total_amount'],
163 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
164 );
165 }
166 if (!empty($params['honor_contact_id'])) {
167 $params['soft_credit'][] = array(
168 'contact_id' => $params['honor_contact_id'],
169 'amount' => $params['total_amount'],
170 'soft_credit_type_id' => CRM_Utils_Array::value('honor_type_id', $params, CRM_Core_OptionGroup::getValue('soft_credit_type', 'in_honor_of', 'name')),
171 );
172 }
173 }
174
175 /**
176 * Delete a Contribution.
177 *
178 * @param array $params
179 * Input parameters.
180 *
181 * @return array
182 */
183 function civicrm_api3_contribution_delete($params) {
184
185 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
186 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
187 return civicrm_api3_create_success(array($contributionID => 1));
188 }
189 else {
190 return civicrm_api3_create_error('Could not delete contribution');
191 }
192 }
193
194 /**
195 * Modify metadata for delete action.
196 *
197 * Legacy support for contribution_id.
198 *
199 * @param array $params
200 */
201 function _civicrm_api3_contribution_delete_spec(&$params) {
202 $params['id']['api.aliases'] = array('contribution_id');
203 }
204
205 /**
206 * Retrieve a set of contributions.
207 *
208 * @param array $params
209 * Input parameters.
210 *
211 * @return array
212 * Array of contributions, if error an array with an error id and error message
213 */
214 function civicrm_api3_contribution_get($params) {
215
216 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
217 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Contribution');
218
219 $contribution = array();
220 while ($dao->fetch()) {
221 //CRM-8662
222 $contribution_details = $query->store($dao);
223 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id, TRUE);
224 $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution);
225 // format soft credit for backward compatibility
226 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
227 }
228 return civicrm_api3_create_success($contribution, $params, 'Contribution', 'get', $dao);
229 }
230
231 /**
232 * This function is used to format the soft credit for backward compatibility.
233 *
234 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
235 * but we still return first soft credit as a part of contribution array
236 *
237 * @param $contribution
238 */
239 function _civicrm_api3_format_soft_credit(&$contribution) {
240 if (!empty($contribution['soft_credit'])) {
241 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
242 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
243 }
244 }
245
246 /**
247 * Adjust Metadata for Get action.
248 *
249 * The metadata is used for setting defaults, documentation & validation.
250 *
251 * @param array $params
252 * Array of parameters determined by getfields.
253 */
254 function _civicrm_api3_contribution_get_spec(&$params) {
255 $params['contribution_test'] = array(
256 'api.default' => 0,
257 'type' => CRM_Utils_Type::T_BOOLEAN,
258 'title' => 'Get Test Contributions?',
259 'api.aliases' => array('is_test'),
260 );
261
262 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
263 $params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
264 $params['contact_id'] = $params['contribution_contact_id'];
265 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
266 unset($params['contribution_contact_id']);
267 }
268
269 /**
270 * Legacy handling for contribution parameters.
271 *
272 * Take the input parameter list as specified in the data model and
273 * convert it into the same format that we use in QF and BAO object.
274 *
275 * @param array $params
276 * property name/value pairs to insert in new contact.
277 * @param array $values
278 * The reformatted properties that we can use internally.
279 *
280 * @return array
281 */
282 function _civicrm_api3_contribute_format_params($params, &$values) {
283 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
284 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
285 return array();
286 }
287
288 /**
289 * Adjust Metadata for Transact action.
290 *
291 * The metadata is used for setting defaults, documentation & validation.
292 *
293 * @param array $params
294 * Array of parameters determined by getfields.
295 */
296 function _civicrm_api3_contribution_transact_spec(&$params) {
297 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
298 $params = array_merge($params, $fields['values']);
299 $params['receive_date']['api.default'] = 'now';
300 }
301
302 /**
303 * Process a transaction and record it against the contact.
304 *
305 * @param array $params
306 * Input parameters.
307 *
308 * @return array
309 * contribution of created or updated record (or a civicrm error)
310 */
311 function civicrm_api3_contribution_transact($params) {
312 // Set some params specific to payment processing
313 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
314 // 'is_error' set
315 // also trxn_id is not saved.
316 // but since there is no test it's not desirable to jump in & make the obvious changes.
317 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
318 $params['amount'] = $params['total_amount'];
319 if (!isset($params['net_amount'])) {
320 $params['net_amount'] = $params['amount'];
321 }
322 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
323 $params['invoiceID'] = $params['invoice_id'];
324 }
325
326 // Some payment processors expect a unique invoice_id - generate one if not supplied
327 $params['invoice_id'] = CRM_Utils_Array::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
328
329 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
330 if (civicrm_error($paymentProcessor)) {
331 return $paymentProcessor;
332 }
333
334 $payment = CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
335 if (civicrm_error($payment)) {
336 return $payment;
337 }
338
339 $transaction = $payment->doPayment($params);
340
341 $params['payment_instrument_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ? 'Credit Card' : 'Debit Card';
342 return civicrm_api('Contribution', 'create', $params);
343 }
344
345 /**
346 * Send a contribution confirmation (receipt or invoice).
347 *
348 * The appropriate online template will be used (the existence of related objects
349 * (e.g. memberships ) will affect this selection
350 *
351 * @param array $params
352 * Input parameters.
353 *
354 * @throws Exception
355 */
356 function civicrm_api3_contribution_sendconfirmation($params) {
357 $contribution = new CRM_Contribute_BAO_Contribution();
358 $contribution->id = $params['id'];
359 if (!$contribution->find(TRUE)) {
360 throw new Exception('Contribution does not exist');
361 }
362 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
363 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
364 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
365 }
366
367 /**
368 * Adjust Metadata for sendconfirmation action.
369 *
370 * The metadata is used for setting defaults, documentation & validation.
371 *
372 * @param array $params
373 * Array of parameters determined by getfields.
374 */
375 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
376 $params['id'] = array(
377 'api.required' => 1,
378 'title' => 'Contribution ID',
379 'type' => CRM_Utils_Type::T_INT,
380 );
381 $params['receipt_from_email'] = array(
382 'api.required' => 1,
383 'title' => 'From Email address (string) required until someone provides a patch :-)',
384 'type' => CRM_Utils_Type::T_STRING,
385 );
386 $params['receipt_from_name'] = array(
387 'title' => 'From Name (string)',
388 'type' => CRM_Utils_Type::T_STRING,
389 );
390 $params['cc_receipt'] = array(
391 'title' => 'CC Email address (string)',
392 'type' => CRM_Utils_Type::T_STRING,
393 );
394 $params['bcc_receipt'] = array(
395 'title' => 'BCC Email address (string)',
396 'type' => CRM_Utils_Type::T_STRING,
397 );
398 $params['receipt_text'] = array(
399 'title' => 'Message (string)',
400 'type' => CRM_Utils_Type::T_STRING,
401 );
402 }
403
404 /**
405 * Complete an existing (pending) transaction.
406 *
407 * This will update related entities (participant, membership, pledge etc)
408 * and take any complete actions from the contribution page (e.g. send receipt).
409 *
410 * @todo - most of this should live in the BAO layer but as we want it to be an addition
411 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
412 *
413 * @param array $params
414 * Input parameters.
415 *
416 * @throws API_Exception
417 * Api result array.
418 */
419 function civicrm_api3_contribution_completetransaction(&$params) {
420
421 $input = $ids = array();
422 $contribution = new CRM_Contribute_BAO_Contribution();
423 $contribution->id = $params['id'];
424 $contribution->find(TRUE);
425 if (!$contribution->id == $params['id']) {
426 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
427 }
428 try {
429 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
430 throw new API_Exception('failed to load related objects');
431 }
432 elseif ($contribution->contribution_status_id == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
433 throw new API_Exception(ts('Contribution already completed'));
434 }
435 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
436 $params = _ipn_process_transaction($params, $contribution, $input, $ids);
437 }
438 catch(Exception $e) {
439 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
440 }
441 }
442
443 /**
444 * Provide function metadata.
445 *
446 * @param array $params
447 */
448 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
449 $params['id'] = array(
450 'title' => 'Contribution ID',
451 'type' => CRM_Utils_Type::T_INT,
452 'api.required' => TRUE,
453 );
454 $params['trxn_id'] = array(
455 'title' => 'Transaction ID',
456 'type' => CRM_Utils_Type::T_STRING,
457 );
458 $params['is_email_receipt'] = array(
459 'title' => 'Send email Receipt?',
460 'type' => CRM_Utils_Type::T_BOOLEAN,
461 );
462 $params['receipt_from_email'] = array(
463 'title' => 'Email to send receipt from.',
464 'description' => 'If not provided this will default to being based on domain mail or contribution page',
465 'type' => CRM_Utils_Type::T_EMAIL,
466 );
467 $params['receipt_from_name'] = array(
468 'title' => 'Name to send receipt from',
469 'description' => '. If not provided this will default to domain mail or contribution page',
470 'type' => CRM_Utils_Type::T_STRING,
471 );
472 }
473
474 /**
475 * Complete an existing (pending) transaction.
476 *
477 * This will update related entities (participant, membership, pledge etc)
478 * and take any complete actions from the contribution page (e.g. send receipt).
479 *
480 * @todo - most of this should live in the BAO layer but as we want it to be an addition
481 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
482 *
483 * @param array $params
484 * Input parameters.
485 *
486 * @throws API_Exception
487 * Api result array.
488 */
489 function civicrm_api3_contribution_repeattransaction(&$params) {
490 $input = $ids = array();
491 $contribution = new CRM_Contribute_BAO_Contribution();
492 $contribution->id = $params['original_contribution_id'];
493 if (!$contribution->find(TRUE)) {
494 throw new API_Exception(
495 'A valid original contribution ID is required', 'invalid_data');
496 }
497 $original_contribution = clone $contribution;
498 try {
499 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
500 throw new API_Exception('failed to load related objects');
501 }
502
503 unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
504 $contribution->contribution_status_id = $params['contribution_status_id'];
505 $contribution->receive_date = $params['receive_date'];
506
507 $passThroughParams = array('trxn_id', 'total_amount', 'campaign_id', 'fee_amount');
508 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
509
510 $params = _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
511 }
512 catch(Exception $e) {
513 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
514 }
515 }
516
517 /**
518 * Calls IPN complete transaction for completing or repeating a transaction.
519 *
520 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
521 * when separating them in the api layer.
522 *
523 * @param array $params
524 * @param CRM_Contribute_BAO_Contribution $contribution
525 * @param array $input
526 *
527 * @param array $ids
528 *
529 * @param CRM_Contribute_BAO_Contribution $firstContribution
530 *
531 * @return mixed
532 */
533 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
534 $objects = $contribution->_relatedObjects;
535 $objects['contribution'] = &$contribution;
536
537 if ($firstContribution) {
538 $objects['first_contribution'] = $firstContribution;
539 }
540 $input['component'] = $contribution->_component;
541 $input['is_test'] = $contribution->is_test;
542 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
543
544 if (isset($params['is_email_receipt'])) {
545 $input['is_email_receipt'] = $params['is_email_receipt'];
546 }
547 if (empty($contribution->contribution_page_id)) {
548 static $domainFromName;
549 static $domainFromEmail;
550 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
551 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
552 }
553 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
554 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
555 }
556 // @todo required for base ipn but problematic as api layer handles this
557 $transaction = new CRM_Core_Transaction();
558 $ipn = new CRM_Core_Payment_BaseIPN();
559 $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id));
560 return $params;
561 }
562
563 /**
564 * Provide function metadata.
565 *
566 * @param array $params
567 */
568 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
569 $params['original_contribution_id'] = array(
570 'title' => 'Original Contribution ID',
571 'type' => CRM_Utils_Type::T_INT,
572 'api.required' => TRUE,
573 );
574 $params['trxn_id'] = array(
575 'title' => 'Transaction ID',
576 'type' => CRM_Utils_Type::T_STRING,
577 );
578 $params['is_email_receipt'] = array(
579 'title' => 'Send email Receipt?',
580 'type' => CRM_Utils_Type::T_BOOLEAN,
581 );
582 $params['contribution_status_id'] = array(
583 'title' => 'Contribution Status ID',
584 'name' => 'contribution_status_id',
585 'type' => CRM_Utils_Type::T_INT,
586 'pseudoconstant' => array(
587 'optionGroupName' => 'contribution_status',
588 ),
589 'api.required' => TRUE,
590 );
591 $params['receive_date'] = array(
592 'title' => 'Contribution Receive Date',
593 'name' => 'receive_date',
594 'type' => CRM_Utils_Type::T_DATE,
595 'api.default' => 'now',
596 );
597 $params['trxn_id'] = array(
598 'title' => 'Transaction ID',
599 'name' => 'trxn_id',
600 'type' => CRM_Utils_Type::T_STRING,
601 );
602 $params['payment_processor_id'] = array(
603 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
604 'title' => 'Payment processor ID',
605 'name' => 'payment_processor_id',
606 'type' => CRM_Utils_Type::T_INT,
607 );
608 }