Merge pull request #10988 from jmcclelland/CRM-21194
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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 // The BAO should not clean money - it should be done in the form layer & api wrapper
49 // (although arguably the api should expect pre-cleaned it seems to do some cleaning.)
50 if (empty($params['skipCleanMoney'])) {
51 foreach (['total_amount', 'net_amount', 'fee_amount'] as $field) {
52 if (isset($params[$field])) {
53 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
54 }
55 }
56 }
57 $params['skipCleanMoney'] = TRUE;
58
59 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
60 if (empty($params['id'])) {
61 $op = CRM_Core_Action::ADD;
62 }
63 else {
64 if (empty($params['financial_type_id'])) {
65 $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $params['id'], 'financial_type_id');
66 }
67 $op = CRM_Core_Action::UPDATE;
68 }
69 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types, $op);
70 if (!in_array($params['financial_type_id'], array_keys($types))) {
71 return civicrm_api3_create_error('You do not have permission to create this contribution');
72 }
73 }
74 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
75 $error = array();
76 //throw error for invalid status change such as setting completed back to pending
77 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
78 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
79 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
80 if (array_key_exists('contribution_status_id', $error)) {
81 throw new API_Exception($error['contribution_status_id']);
82 }
83 }
84 if (!empty($params['id']) && !empty($params['financial_type_id'])) {
85 $error = array();
86 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
87 if (array_key_exists('financial_type_id', $error)) {
88 throw new API_Exception($error['financial_type_id']);
89 }
90 }
91 _civicrm_api3_contribution_create_legacy_support_45($params);
92
93 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
94 }
95
96 /**
97 * Adjust Metadata for Create action.
98 *
99 * The metadata is used for setting defaults, documentation & validation.
100 *
101 * @param array $params
102 * Array of parameters determined by getfields.
103 */
104 function _civicrm_api3_contribution_create_spec(&$params) {
105 $params['contact_id']['api.required'] = 1;
106 $params['total_amount']['api.required'] = 1;
107 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
108 $params['receive_date']['api.default'] = 'now';
109 $params['payment_processor'] = array(
110 'name' => 'payment_processor',
111 'title' => 'Payment Processor ID',
112 'description' => 'ID of payment processor used for this contribution',
113 // field is called payment processor - not payment processor id but can only be one id so
114 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
115 'api.aliases' => array('payment_processor_id'),
116 'type' => CRM_Utils_Type::T_INT,
117 );
118 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
119 $params['financial_type_id']['api.required'] = 1;
120 $params['note'] = array(
121 'name' => 'note',
122 'uniqueName' => 'contribution_note',
123 'title' => 'note',
124 'type' => 2,
125 'description' => 'Associated Note in the notes table',
126 );
127 $params['soft_credit_to'] = array(
128 'name' => 'soft_credit_to',
129 'title' => 'Soft Credit contact ID (legacy)',
130 'type' => CRM_Utils_Type::T_INT,
131 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
132 'FKClassName' => 'CRM_Contact_DAO_Contact',
133 );
134 $params['honor_contact_id'] = array(
135 'name' => 'honor_contact_id',
136 'title' => 'Honoree contact ID (legacy)',
137 'type' => CRM_Utils_Type::T_INT,
138 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
139 'FKClassName' => 'CRM_Contact_DAO_Contact',
140 );
141 $params['honor_type_id'] = array(
142 'name' => 'honor_type_id',
143 'title' => 'Honoree Type (legacy)',
144 'type' => CRM_Utils_Type::T_INT,
145 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
146 'pseudoconstant' => TRUE,
147 );
148 // note this is a recommended option but not adding as a default to avoid
149 // creating unnecessary changes for the dev
150 $params['skipRecentView'] = array(
151 'name' => 'skipRecentView',
152 'title' => 'Skip adding to recent view',
153 'type' => CRM_Utils_Type::T_BOOLEAN,
154 'description' => 'Do not add to recent view (setting this improves performance)',
155 );
156 $params['skipLineItem'] = array(
157 'name' => 'skipLineItem',
158 'title' => 'Skip adding line items',
159 'type' => CRM_Utils_Type::T_BOOLEAN,
160 'api.default' => 0,
161 'description' => 'Do not add line items by default (if you wish to add your own)',
162 );
163 $params['batch_id'] = array(
164 'title' => 'Batch',
165 'type' => CRM_Utils_Type::T_INT,
166 'description' => 'Batch which relevant transactions should be added to',
167 );
168 $params['refund_trxn_id'] = array(
169 'title' => 'Refund Transaction ID',
170 'type' => CRM_Utils_Type::T_STRING,
171 'description' => 'Transaction ID specific to the refund taking place',
172 );
173 $params['card_type_id'] = array(
174 'title' => 'Card Type ID',
175 'description' => 'Providing Credit Card Type ID',
176 'type' => CRM_Utils_Type::T_INT,
177 'pseudoconstant' => array(
178 'optionGroupName' => 'accept_creditcard',
179 ),
180 );
181 }
182
183 /**
184 * Support for schema changes made in 4.5.
185 *
186 * The main purpose of the API is to provide integrators a level of stability not provided by
187 * the core code or schema - this means we have to provide support for api calls (where possible)
188 * across schema changes.
189 *
190 * @param array $params
191 */
192 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
193 //legacy soft credit handling - recommended approach is chaining
194 if (!empty($params['soft_credit_to'])) {
195 $params['soft_credit'][] = array(
196 'contact_id' => $params['soft_credit_to'],
197 'amount' => $params['total_amount'],
198 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
199 );
200 }
201 if (!empty($params['honor_contact_id'])) {
202 $params['soft_credit'][] = array(
203 'contact_id' => $params['honor_contact_id'],
204 'amount' => $params['total_amount'],
205 'soft_credit_type_id' => CRM_Utils_Array::value('honor_type_id', $params, CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'in_honor_of')),
206 );
207 }
208 }
209
210 /**
211 * Delete a Contribution.
212 *
213 * @param array $params
214 * Input parameters.
215 *
216 * @return array
217 */
218 function civicrm_api3_contribution_delete($params) {
219
220 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
221 // First check contribution financial type
222 $financialType = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionID, 'financial_type_id');
223 // Now check permissioned lineitems & permissioned contribution
224 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
225 && !CRM_Core_Permission::check('delete contributions of type ' . CRM_Contribute_PseudoConstant::financialType($financialType)) ||
226 !CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($contributionID, 'delete', FALSE)
227 ) {
228 return civicrm_api3_create_error('You do not have permission to delete this contribution');
229 }
230 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
231 return civicrm_api3_create_success(array($contributionID => 1));
232 }
233 else {
234 return civicrm_api3_create_error('Could not delete contribution');
235 }
236 }
237
238 /**
239 * Modify metadata for delete action.
240 *
241 * Legacy support for contribution_id.
242 *
243 * @param array $params
244 */
245 function _civicrm_api3_contribution_delete_spec(&$params) {
246 $params['id']['api.aliases'] = array('contribution_id');
247 }
248
249 /**
250 * Retrieve a set of contributions.
251 *
252 * @param array $params
253 * Input parameters.
254 *
255 * @return array
256 * Array of contributions, if error an array with an error id and error message
257 */
258 function civicrm_api3_contribution_get($params) {
259
260 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
261 $additionalOptions = _civicrm_api3_contribution_get_support_nonunique_returns($params);
262 $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode);
263
264 $contributions = _civicrm_api3_get_using_query_object('Contribution', $params, $additionalOptions, NULL, $mode, $returnProperties);
265
266 foreach ($contributions as $id => $contribution) {
267 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id, TRUE);
268 $contributions[$id] = array_merge($contribution, $softContribution);
269 // format soft credit for backward compatibility
270 _civicrm_api3_format_soft_credit($contributions[$id]);
271 _civicrm_api3_contribution_add_supported_fields($contributions[$id]);
272
273 }
274 return civicrm_api3_create_success($contributions, $params, 'Contribution', 'get');
275 }
276
277 /**
278 * Fix the return values to reflect cases where the schema has been changed.
279 *
280 * At the query object level using uniquenames dismbiguates between tables.
281 *
282 * However, adding uniquename can change inputs accepted by the api, so we need
283 * to ensure we are asking for the unique name return fields.
284 *
285 * @param array $params
286 *
287 * @return array
288 * @throws \API_Exception
289 */
290 function _civicrm_api3_contribution_get_support_nonunique_returns($params) {
291 $additionalOptions = array();
292 $options = _civicrm_api3_get_options_from_params($params, TRUE);
293 foreach (array('check_number', 'address_id') as $changedVariable) {
294 if (isset($options['return']) && !empty($options['return'][$changedVariable])) {
295 $additionalOptions['return']['contribution_' . $changedVariable] = 1;
296 }
297 }
298 return $additionalOptions;
299 }
300
301 /**
302 * Support for supported output variables.
303 *
304 * @param $contribution
305 */
306 function _civicrm_api3_contribution_add_supported_fields(&$contribution) {
307 // These are output fields that are supported in our test contract.
308 // Arguably we should also do the same with 'campaign_id' &
309 // 'source' - which are also fields being rendered with unique names.
310 // That seems more consistent with other api where we output the actual field names.
311 $outputAliases = array(
312 'contribution_check_number' => 'check_number',
313 'contribution_address_id' => 'address_id',
314 'payment_instrument_id' => 'instrument_id',
315 );
316 foreach ($outputAliases as $returnName => $copyTo) {
317 if (array_key_exists($returnName, $contribution)) {
318 $contribution[$copyTo] = $contribution[$returnName];
319 }
320 }
321
322 }
323
324 /**
325 * Get number of contacts matching the supplied criteria.
326 *
327 * @param array $params
328 *
329 * @return int
330 */
331 function civicrm_api3_contribution_getcount($params) {
332 $count = _civicrm_api3_get_using_query_object('Contribution', $params, array(), TRUE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE);
333 return (int) $count;
334 }
335
336 /**
337 * This function is used to format the soft credit for backward compatibility.
338 *
339 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
340 * but we still return first soft credit as a part of contribution array
341 *
342 * @param $contribution
343 */
344 function _civicrm_api3_format_soft_credit(&$contribution) {
345 if (!empty($contribution['soft_credit'])) {
346 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
347 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
348 }
349 }
350
351 /**
352 * Adjust Metadata for Get action.
353 *
354 * The metadata is used for setting defaults, documentation & validation.
355 *
356 * @param array $params
357 * Array of parameters determined by getfields.
358 */
359 function _civicrm_api3_contribution_get_spec(&$params) {
360 $params['contribution_test'] = array(
361 'api.default' => 0,
362 'type' => CRM_Utils_Type::T_BOOLEAN,
363 'title' => 'Get Test Contributions?',
364 'api.aliases' => array('is_test'),
365 );
366
367 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
368 $params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
369 $params['contact_id'] = CRM_Utils_Array::value('contribution_contact_id', $params);
370 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
371 unset($params['contribution_contact_id']);
372 }
373
374 /**
375 * Legacy handling for contribution parameters.
376 *
377 * Take the input parameter list as specified in the data model and
378 * convert it into the same format that we use in QF and BAO object.
379 *
380 * @param array $params
381 * property name/value pairs to insert in new contact.
382 * @param array $values
383 * The reformatted properties that we can use internally.
384 *
385 * @return array
386 */
387 function _civicrm_api3_contribute_format_params($params, &$values) {
388 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
389 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
390 return array();
391 }
392
393 /**
394 * Adjust Metadata for Transact action.
395 *
396 * The metadata is used for setting defaults, documentation & validation.
397 *
398 * @param array $params
399 * Array of parameters determined by getfields.
400 */
401 function _civicrm_api3_contribution_transact_spec(&$params) {
402 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
403 $params = array_merge($params, $fields['values']);
404 $params['receive_date']['api.default'] = 'now';
405 }
406
407 /**
408 * Process a transaction and record it against the contact.
409 *
410 * @param array $params
411 * Input parameters.
412 *
413 * @return array
414 * contribution of created or updated record (or a civicrm error)
415 */
416 function civicrm_api3_contribution_transact($params) {
417 // Set some params specific to payment processing
418 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
419 // 'is_error' set
420 // also trxn_id is not saved.
421 // but since there is no test it's not desirable to jump in & make the obvious changes.
422 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
423 $params['amount'] = $params['total_amount'];
424 if (!isset($params['net_amount'])) {
425 $params['net_amount'] = $params['amount'];
426 }
427 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
428 $params['invoiceID'] = $params['invoice_id'];
429 }
430
431 // Some payment processors expect a unique invoice_id - generate one if not supplied
432 $params['invoice_id'] = CRM_Utils_Array::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
433
434 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
435 $paymentProcessor['object']->doPayment($params);
436
437 $params['payment_instrument_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ? 'Credit Card' : 'Debit Card';
438 return civicrm_api('Contribution', 'create', $params);
439 }
440
441 /**
442 * Send a contribution confirmation (receipt or invoice).
443 *
444 * The appropriate online template will be used (the existence of related objects
445 * (e.g. memberships ) will affect this selection
446 *
447 * @param array $params
448 * Input parameters.
449 *
450 * @throws Exception
451 */
452 function civicrm_api3_contribution_sendconfirmation($params) {
453 $ids = $values = array();
454 $allowedParams = array(
455 'receipt_from_email',
456 'receipt_from_name',
457 'receipt_update',
458 'cc_receipt',
459 'bcc_receipt',
460 'receipt_text',
461 'payment_processor_id',
462 );
463 $input = array_intersect_key($params, array_flip($allowedParams));
464 $input['is_email_receipt'] = TRUE;
465 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $params['id'], $values);
466 }
467
468 /**
469 * Adjust Metadata for sendconfirmation action.
470 *
471 * The metadata is used for setting defaults, documentation & validation.
472 *
473 * @param array $params
474 * Array of parameters determined by getfields.
475 */
476 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
477 $params['id'] = array(
478 'api.required' => 1,
479 'title' => ts('Contribution ID'),
480 'type' => CRM_Utils_Type::T_INT,
481 );
482 $params['receipt_from_email'] = array(
483 'title' => ts('From Email address (string)'),
484 'type' => CRM_Utils_Type::T_STRING,
485 );
486 $params['receipt_from_name'] = array(
487 'title' => ts('From Name (string)'),
488 'type' => CRM_Utils_Type::T_STRING,
489 );
490 $params['cc_receipt'] = array(
491 'title' => ts('CC Email address (string)'),
492 'type' => CRM_Utils_Type::T_STRING,
493 );
494 $params['bcc_receipt'] = array(
495 'title' => ts('BCC Email address (string)'),
496 'type' => CRM_Utils_Type::T_STRING,
497 );
498 $params['receipt_text'] = array(
499 'title' => ts('Message (string)'),
500 'type' => CRM_Utils_Type::T_STRING,
501 );
502 $params['receipt_update'] = array(
503 'title' => ts('Update the Receipt Date'),
504 'type' => CRM_Utils_Type::T_BOOLEAN,
505 'api.default' => TRUE,
506 );
507 $params['payment_processor_id'] = array(
508 'title' => ts('Payment processor Id (avoids mis-guesses)'),
509 'type' => CRM_Utils_Type::T_INT,
510 );
511 }
512
513 /**
514 * Complete an existing (pending) transaction.
515 *
516 * This will update related entities (participant, membership, pledge etc)
517 * and take any complete actions from the contribution page (e.g. send receipt).
518 *
519 * @todo - most of this should live in the BAO layer but as we want it to be an addition
520 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
521 *
522 * @param array $params
523 * Input parameters.
524 *
525 * @return array
526 * API result array
527 * @throws \API_Exception
528 * @throws \CRM_Core_Exception
529 * @throws \Exception
530 */
531 function civicrm_api3_contribution_completetransaction(&$params) {
532 $input = $ids = array();
533 if (isset($params['payment_processor_id'])) {
534 $input['payment_processor_id'] = $params['payment_processor_id'];
535 }
536 $contribution = new CRM_Contribute_BAO_Contribution();
537 $contribution->id = $params['id'];
538 if (!$contribution->find(TRUE)) {
539 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
540 }
541
542 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
543 throw new API_Exception('failed to load related objects');
544 }
545 elseif ($contribution->contribution_status_id == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
546 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
547 }
548 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
549 if (!empty($params['fee_amount'])) {
550 $input['fee_amount'] = $params['fee_amount'];
551 }
552 return _ipn_process_transaction($params, $contribution, $input, $ids);
553
554 }
555
556 /**
557 * Provide function metadata.
558 *
559 * @param array $params
560 */
561 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
562 $params['id'] = array(
563 'title' => 'Contribution ID',
564 'type' => CRM_Utils_Type::T_INT,
565 'api.required' => TRUE,
566 );
567 $params['trxn_id'] = array(
568 'title' => 'Transaction ID',
569 'type' => CRM_Utils_Type::T_STRING,
570 );
571 $params['is_email_receipt'] = array(
572 'title' => 'Send email Receipt?',
573 'type' => CRM_Utils_Type::T_BOOLEAN,
574 );
575 $params['receipt_from_email'] = array(
576 'title' => 'Email to send receipt from.',
577 'description' => 'If not provided this will default to being based on domain mail or contribution page',
578 'type' => CRM_Utils_Type::T_EMAIL,
579 );
580 $params['receipt_from_name'] = array(
581 'title' => 'Name to send receipt from',
582 'description' => '. If not provided this will default to domain mail or contribution page',
583 'type' => CRM_Utils_Type::T_STRING,
584 );
585 $params['payment_processor_id'] = array(
586 'title' => 'Payment processor ID',
587 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
588 'type' => CRM_Utils_Type::T_INT,
589 );
590 $params['fee_amount'] = array(
591 'title' => 'Fee charged on transaction',
592 'description' => 'If a fee has been charged then the amount',
593 'type' => CRM_Utils_Type::T_FLOAT,
594 );
595 $params['trxn_date'] = array(
596 'title' => 'Transaction Date',
597 'description' => 'Date this transaction occurred',
598 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
599 );
600 $params['card_type_id'] = array(
601 'title' => 'Card Type ID',
602 'description' => 'Providing Credit Card Type ID',
603 'type' => CRM_Utils_Type::T_INT,
604 'pseudoconstant' => array(
605 'optionGroupName' => 'accept_creditcard',
606 ),
607 );
608 }
609
610 /**
611 * Complete an existing (pending) transaction.
612 *
613 * This will update related entities (participant, membership, pledge etc)
614 * and take any complete actions from the contribution page (e.g. send receipt).
615 *
616 * @todo - most of this should live in the BAO layer but as we want it to be an addition
617 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
618 *
619 * @param array $params
620 * Input parameters.
621 *
622 * @return array
623 * Api result array.
624 * @throws API_Exception
625 */
626 function civicrm_api3_contribution_repeattransaction(&$params) {
627 $input = $ids = array();
628 civicrm_api3_verify_one_mandatory($params, NULL, array('contribution_recur_id', 'original_contribution_id'));
629 if (empty($params['original_contribution_id'])) {
630 // CRM-19873 call with test mode.
631 $params['original_contribution_id'] = civicrm_api3('contribution', 'getvalue', array(
632 'return' => 'id',
633 'contribution_status_id' => array('IN' => array('Completed')),
634 'contribution_recur_id' => $params['contribution_recur_id'],
635 'contribution_test' => CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur', $params['contribution_recur_id'], 'is_test'),
636 'options' => array('limit' => 1, 'sort' => 'id DESC'),
637 ));
638 }
639 $contribution = new CRM_Contribute_BAO_Contribution();
640 $contribution->id = $params['original_contribution_id'];
641 if (!$contribution->find(TRUE)) {
642 throw new API_Exception(
643 'A valid original contribution ID is required', 'invalid_data');
644 }
645 $original_contribution = clone $contribution;
646 $input['payment_processor_id'] = civicrm_api3('contributionRecur', 'getvalue', array(
647 'return' => 'payment_processor_id',
648 'id' => $contribution->contribution_recur_id,
649 ));
650 try {
651 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
652 throw new API_Exception('failed to load related objects');
653 }
654
655 unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
656 $contribution->receive_date = $params['receive_date'];
657
658 $passThroughParams = array(
659 'trxn_id',
660 'total_amount',
661 'campaign_id',
662 'fee_amount',
663 'financial_type_id',
664 'contribution_status_id',
665 );
666 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
667
668 return _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
669 }
670 catch(Exception $e) {
671 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
672 }
673 }
674
675 /**
676 * Calls IPN complete transaction for completing or repeating a transaction.
677 *
678 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
679 * when separating them in the api layer.
680 *
681 * @param array $params
682 * @param CRM_Contribute_BAO_Contribution $contribution
683 * @param array $input
684 *
685 * @param array $ids
686 *
687 * @param CRM_Contribute_BAO_Contribution $firstContribution
688 *
689 * @return mixed
690 */
691 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
692 $objects = $contribution->_relatedObjects;
693 $objects['contribution'] = &$contribution;
694
695 if ($firstContribution) {
696 $objects['first_contribution'] = $firstContribution;
697 }
698 $input['component'] = $contribution->_component;
699 $input['is_test'] = $contribution->is_test;
700 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
701
702 if (isset($params['is_email_receipt'])) {
703 $input['is_email_receipt'] = $params['is_email_receipt'];
704 }
705 if (!empty($params['trxn_date'])) {
706 $input['trxn_date'] = $params['trxn_date'];
707 }
708 if (!empty($params['receive_date'])) {
709 $input['receive_date'] = $params['receive_date'];
710 }
711 if (empty($contribution->contribution_page_id)) {
712 static $domainFromName;
713 static $domainFromEmail;
714 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
715 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
716 }
717 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
718 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
719 }
720 $input['card_type_id'] = CRM_Utils_Array::value('card_type_id', $params);
721 $input['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $params);
722 $transaction = new CRM_Core_Transaction();
723 return CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, !empty
724 ($contribution->contribution_recur_id), $contribution);
725 }
726
727 /**
728 * Provide function metadata.
729 *
730 * @param array $params
731 */
732 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
733 $params['original_contribution_id'] = array(
734 'title' => 'Original Contribution ID',
735 'description' => 'Contribution ID to copy (will be calculated from recurring contribution if not provided)',
736 'type' => CRM_Utils_Type::T_INT,
737 );
738 $params['contribution_recur_id'] = array(
739 'title' => 'Recurring contribution ID',
740 'type' => CRM_Utils_Type::T_INT,
741 );
742 $params['trxn_id'] = array(
743 'title' => 'Transaction ID',
744 'type' => CRM_Utils_Type::T_STRING,
745 );
746 $params['is_email_receipt'] = array(
747 'title' => 'Send email Receipt?',
748 'type' => CRM_Utils_Type::T_BOOLEAN,
749 );
750 $params['contribution_status_id'] = array(
751 'title' => 'Contribution Status ID',
752 'name' => 'contribution_status_id',
753 'type' => CRM_Utils_Type::T_INT,
754 'pseudoconstant' => array(
755 'optionGroupName' => 'contribution_status',
756 ),
757 'api.required' => TRUE,
758 );
759 $params['receive_date'] = array(
760 'title' => 'Contribution Receive Date',
761 'name' => 'receive_date',
762 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
763 'api.default' => 'now',
764 );
765 $params['trxn_id'] = array(
766 'title' => 'Transaction ID',
767 'name' => 'trxn_id',
768 'type' => CRM_Utils_Type::T_STRING,
769 );
770 $params['campaign_id'] = array(
771 'title' => 'Campaign ID',
772 'name' => 'campaign_id',
773 'type' => CRM_Utils_Type::T_INT,
774 'pseudoconstant' => array(
775 'table' => 'civicrm_campaign',
776 'keyColumn' => 'id',
777 'labelColumn' => 'title',
778 ),
779 );
780 $params['financial_type_id'] = array(
781 'title' => 'Financial ID (ignored if more than one line item)',
782 'name' => 'financial_type_id',
783 'type' => CRM_Utils_Type::T_INT,
784 'pseudoconstant' => array(
785 'table' => 'civicrm_financial_type',
786 'keyColumn' => 'id',
787 'labelColumn' => 'name',
788 ),
789 );
790 $params['payment_processor_id'] = array(
791 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
792 'title' => 'Payment processor ID',
793 'name' => 'payment_processor_id',
794 'type' => CRM_Utils_Type::T_INT,
795 );
796 }