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