Merge pull request #12834 from pradpnayak/preRelHook
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 (!empty($params['check_permissions']) && 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 throw new API_Exception('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 * @throws \API_Exception
218 */
219 function civicrm_api3_contribution_delete($params) {
220
221 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
222 // First check contribution financial type
223 $financialType = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionID, 'financial_type_id');
224 // Now check permissioned lineitems & permissioned contribution
225 if (!empty($params['check_permissions']) && CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() &&
226 (
227 !CRM_Core_Permission::check('delete contributions of type ' . CRM_Contribute_PseudoConstant::financialType($financialType))
228 || !CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($contributionID, 'delete', FALSE)
229 )
230 ) {
231 throw new API_Exception('You do not have permission to delete this contribution');
232 }
233 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
234 return civicrm_api3_create_success(array($contributionID => 1));
235 }
236 else {
237 throw new API_Exception('Could not delete contribution');
238 }
239 }
240
241 /**
242 * Modify metadata for delete action.
243 *
244 * Legacy support for contribution_id.
245 *
246 * @param array $params
247 */
248 function _civicrm_api3_contribution_delete_spec(&$params) {
249 $params['id']['api.aliases'] = array('contribution_id');
250 }
251
252 /**
253 * Retrieve a set of contributions.
254 *
255 * @param array $params
256 * Input parameters.
257 *
258 * @return array
259 * Array of contributions, if error an array with an error id and error message
260 */
261 function civicrm_api3_contribution_get($params) {
262
263 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
264 $additionalOptions = _civicrm_api3_contribution_get_support_nonunique_returns($params);
265 $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode);
266
267 $contributions = _civicrm_api3_get_using_query_object('Contribution', $params, $additionalOptions, NULL, $mode, $returnProperties);
268
269 foreach ($contributions as $id => $contribution) {
270 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id, TRUE);
271 $contributions[$id] = array_merge($contribution, $softContribution);
272 // format soft credit for backward compatibility
273 _civicrm_api3_format_soft_credit($contributions[$id]);
274 _civicrm_api3_contribution_add_supported_fields($contributions[$id]);
275
276 }
277 return civicrm_api3_create_success($contributions, $params, 'Contribution', 'get');
278 }
279
280 /**
281 * Fix the return values to reflect cases where the schema has been changed.
282 *
283 * At the query object level using uniquenames dismbiguates between tables.
284 *
285 * However, adding uniquename can change inputs accepted by the api, so we need
286 * to ensure we are asking for the unique name return fields.
287 *
288 * @param array $params
289 *
290 * @return array
291 * @throws \API_Exception
292 */
293 function _civicrm_api3_contribution_get_support_nonunique_returns($params) {
294 $additionalOptions = array();
295 $options = _civicrm_api3_get_options_from_params($params, TRUE);
296 foreach (array('check_number', 'address_id') as $changedVariable) {
297 if (isset($options['return']) && !empty($options['return'][$changedVariable])) {
298 $additionalOptions['return']['contribution_' . $changedVariable] = 1;
299 }
300 }
301 return $additionalOptions;
302 }
303
304 /**
305 * Support for supported output variables.
306 *
307 * @param $contribution
308 */
309 function _civicrm_api3_contribution_add_supported_fields(&$contribution) {
310 // These are output fields that are supported in our test contract.
311 // Arguably we should also do the same with 'campaign_id' &
312 // 'source' - which are also fields being rendered with unique names.
313 // That seems more consistent with other api where we output the actual field names.
314 $outputAliases = array(
315 'contribution_check_number' => 'check_number',
316 'contribution_address_id' => 'address_id',
317 'payment_instrument_id' => 'instrument_id',
318 );
319 foreach ($outputAliases as $returnName => $copyTo) {
320 if (array_key_exists($returnName, $contribution)) {
321 $contribution[$copyTo] = $contribution[$returnName];
322 }
323 }
324
325 }
326
327 /**
328 * Get number of contacts matching the supplied criteria.
329 *
330 * @param array $params
331 *
332 * @return int
333 */
334 function civicrm_api3_contribution_getcount($params) {
335 $count = _civicrm_api3_get_using_query_object('Contribution', $params, array(), TRUE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE);
336 return (int) $count;
337 }
338
339 /**
340 * This function is used to format the soft credit for backward compatibility.
341 *
342 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
343 * but we still return first soft credit as a part of contribution array
344 *
345 * @param $contribution
346 */
347 function _civicrm_api3_format_soft_credit(&$contribution) {
348 if (!empty($contribution['soft_credit'])) {
349 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
350 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
351 }
352 }
353
354 /**
355 * Adjust Metadata for Get action.
356 *
357 * The metadata is used for setting defaults, documentation & validation.
358 *
359 * @param array $params
360 * Array of parameters determined by getfields.
361 */
362 function _civicrm_api3_contribution_get_spec(&$params) {
363 $params['contribution_test'] = array(
364 'api.default' => 0,
365 'type' => CRM_Utils_Type::T_BOOLEAN,
366 'title' => 'Get Test Contributions?',
367 'api.aliases' => array('is_test'),
368 );
369
370 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
371 $params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
372 $params['contact_id'] = CRM_Utils_Array::value('contribution_contact_id', $params);
373 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
374 unset($params['contribution_contact_id']);
375 }
376
377 /**
378 * Legacy handling for contribution parameters.
379 *
380 * Take the input parameter list as specified in the data model and
381 * convert it into the same format that we use in QF and BAO object.
382 *
383 * @param array $params
384 * property name/value pairs to insert in new contact.
385 * @param array $values
386 * The reformatted properties that we can use internally.
387 *
388 * @return array
389 */
390 function _civicrm_api3_contribute_format_params($params, &$values) {
391 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
392 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
393 return array();
394 }
395
396 /**
397 * Adjust Metadata for Transact action.
398 *
399 * The metadata is used for setting defaults, documentation & validation.
400 *
401 * @param array $params
402 * Array of parameters determined by getfields.
403 */
404 function _civicrm_api3_contribution_transact_spec(&$params) {
405 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
406 $params = array_merge($params, $fields['values']);
407 $params['receive_date']['api.default'] = 'now';
408 }
409
410 /**
411 * Process a transaction and record it against the contact.
412 *
413 * @param array $params
414 * Input parameters.
415 *
416 * @return array
417 * contribution of created or updated record (or a civicrm error)
418 */
419 function civicrm_api3_contribution_transact($params) {
420 // Set some params specific to payment processing
421 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
422 // 'is_error' set
423 // also trxn_id is not saved.
424 // but since there is no test it's not desirable to jump in & make the obvious changes.
425 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
426 $params['amount'] = $params['total_amount'];
427 if (!isset($params['net_amount'])) {
428 $params['net_amount'] = $params['amount'];
429 }
430 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
431 $params['invoiceID'] = $params['invoice_id'];
432 }
433
434 // Some payment processors expect a unique invoice_id - generate one if not supplied
435 $params['invoice_id'] = CRM_Utils_Array::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
436
437 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
438 $paymentProcessor['object']->doPayment($params);
439
440 $params['payment_instrument_id'] = $paymentProcessor['object']->getPaymentInstrumentID();
441
442 return civicrm_api('Contribution', 'create', $params);
443 }
444
445 /**
446 * Send a contribution confirmation (receipt or invoice).
447 *
448 * The appropriate online template will be used (the existence of related objects
449 * (e.g. memberships ) will affect this selection
450 *
451 * @param array $params
452 * Input parameters.
453 *
454 * @throws Exception
455 */
456 function civicrm_api3_contribution_sendconfirmation($params) {
457 $ids = $values = array();
458 $allowedParams = array(
459 'receipt_from_email',
460 'receipt_from_name',
461 'receipt_update',
462 'cc_receipt',
463 'bcc_receipt',
464 'receipt_text',
465 'payment_processor_id',
466 );
467 $input = array_intersect_key($params, array_flip($allowedParams));
468 $input['is_email_receipt'] = TRUE;
469 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $params['id'], $values);
470 }
471
472 /**
473 * Adjust Metadata for sendconfirmation action.
474 *
475 * The metadata is used for setting defaults, documentation & validation.
476 *
477 * @param array $params
478 * Array of parameters determined by getfields.
479 */
480 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
481 $params['id'] = array(
482 'api.required' => 1,
483 'title' => ts('Contribution ID'),
484 'type' => CRM_Utils_Type::T_INT,
485 );
486 $params['receipt_from_email'] = array(
487 'title' => ts('From Email address (string)'),
488 'type' => CRM_Utils_Type::T_STRING,
489 );
490 $params['receipt_from_name'] = array(
491 'title' => ts('From Name (string)'),
492 'type' => CRM_Utils_Type::T_STRING,
493 );
494 $params['cc_receipt'] = array(
495 'title' => ts('CC Email address (string)'),
496 'type' => CRM_Utils_Type::T_STRING,
497 );
498 $params['bcc_receipt'] = array(
499 'title' => ts('BCC Email address (string)'),
500 'type' => CRM_Utils_Type::T_STRING,
501 );
502 $params['receipt_text'] = array(
503 'title' => ts('Message (string)'),
504 'type' => CRM_Utils_Type::T_STRING,
505 );
506 $params['receipt_update'] = array(
507 'title' => ts('Update the Receipt Date'),
508 'type' => CRM_Utils_Type::T_BOOLEAN,
509 'api.default' => TRUE,
510 );
511 $params['payment_processor_id'] = array(
512 'title' => ts('Payment processor Id (avoids mis-guesses)'),
513 'type' => CRM_Utils_Type::T_INT,
514 );
515 }
516
517 /**
518 * Complete an existing (pending) transaction.
519 *
520 * This will update related entities (participant, membership, pledge etc)
521 * and take any complete actions from the contribution page (e.g. send receipt).
522 *
523 * @todo - most of this should live in the BAO layer but as we want it to be an addition
524 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
525 *
526 * @param array $params
527 * Input parameters.
528 *
529 * @return array
530 * API result array
531 * @throws \API_Exception
532 * @throws \CRM_Core_Exception
533 * @throws \Exception
534 */
535 function civicrm_api3_contribution_completetransaction(&$params) {
536 $input = $ids = array();
537 if (isset($params['payment_processor_id'])) {
538 $input['payment_processor_id'] = $params['payment_processor_id'];
539 }
540 $contribution = new CRM_Contribute_BAO_Contribution();
541 $contribution->id = $params['id'];
542 if (!$contribution->find(TRUE)) {
543 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
544 }
545
546 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
547 throw new API_Exception('failed to load related objects');
548 }
549 elseif ($contribution->contribution_status_id == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
550 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
551 }
552 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
553 if (!empty($params['fee_amount'])) {
554 $input['fee_amount'] = $params['fee_amount'];
555 }
556 return _ipn_process_transaction($params, $contribution, $input, $ids);
557
558 }
559
560 /**
561 * Provide function metadata.
562 *
563 * @param array $params
564 */
565 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
566 $params['id'] = array(
567 'title' => 'Contribution ID',
568 'type' => CRM_Utils_Type::T_INT,
569 'api.required' => TRUE,
570 );
571 $params['trxn_id'] = array(
572 'title' => 'Transaction ID',
573 'type' => CRM_Utils_Type::T_STRING,
574 );
575 $params['is_email_receipt'] = array(
576 'title' => 'Send email Receipt?',
577 'type' => CRM_Utils_Type::T_BOOLEAN,
578 );
579 $params['receipt_from_email'] = array(
580 'title' => 'Email to send receipt from.',
581 'description' => 'If not provided this will default to being based on domain mail or contribution page',
582 'type' => CRM_Utils_Type::T_EMAIL,
583 );
584 $params['receipt_from_name'] = array(
585 'title' => 'Name to send receipt from',
586 'description' => '. If not provided this will default to domain mail or contribution page',
587 'type' => CRM_Utils_Type::T_STRING,
588 );
589 $params['payment_processor_id'] = array(
590 'title' => 'Payment processor ID',
591 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
592 'type' => CRM_Utils_Type::T_INT,
593 );
594 $params['fee_amount'] = array(
595 'title' => 'Fee charged on transaction',
596 'description' => 'If a fee has been charged then the amount',
597 'type' => CRM_Utils_Type::T_FLOAT,
598 );
599 $params['trxn_date'] = array(
600 'title' => 'Transaction Date',
601 'description' => 'Date this transaction occurred',
602 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
603 );
604 $params['card_type_id'] = array(
605 'title' => 'Card Type ID',
606 'description' => 'Providing Credit Card Type ID',
607 'type' => CRM_Utils_Type::T_INT,
608 'pseudoconstant' => array(
609 'optionGroupName' => 'accept_creditcard',
610 ),
611 );
612 }
613
614 /**
615 * Complete an existing (pending) transaction.
616 *
617 * This will update related entities (participant, membership, pledge etc)
618 * and take any complete actions from the contribution page (e.g. send receipt).
619 *
620 * @todo - most of this should live in the BAO layer but as we want it to be an addition
621 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
622 *
623 * @param array $params
624 * Input parameters.
625 *
626 * @return array
627 * Api result array.
628 * @throws API_Exception
629 */
630 function civicrm_api3_contribution_repeattransaction(&$params) {
631 $input = $ids = array();
632 civicrm_api3_verify_one_mandatory($params, NULL, array('contribution_recur_id', 'original_contribution_id'));
633 if (empty($params['original_contribution_id'])) {
634 // CRM-19873 call with test mode.
635 $params['original_contribution_id'] = civicrm_api3('contribution', 'getvalue', array(
636 'return' => 'id',
637 'contribution_status_id' => array('IN' => array('Completed')),
638 'contribution_recur_id' => $params['contribution_recur_id'],
639 'contribution_test' => CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur', $params['contribution_recur_id'], 'is_test'),
640 'options' => array('limit' => 1, 'sort' => 'id DESC'),
641 ));
642 }
643 $contribution = new CRM_Contribute_BAO_Contribution();
644 $contribution->id = $params['original_contribution_id'];
645 if (!$contribution->find(TRUE)) {
646 throw new API_Exception(
647 'A valid original contribution ID is required', 'invalid_data');
648 }
649 $original_contribution = clone $contribution;
650 $input['payment_processor_id'] = civicrm_api3('contributionRecur', 'getvalue', array(
651 'return' => 'payment_processor_id',
652 'id' => $contribution->contribution_recur_id,
653 ));
654 try {
655 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
656 throw new API_Exception('failed to load related objects');
657 }
658
659 unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
660 $contribution->receive_date = $params['receive_date'];
661
662 $passThroughParams = array(
663 'trxn_id',
664 'total_amount',
665 'campaign_id',
666 'fee_amount',
667 'financial_type_id',
668 'contribution_status_id',
669 );
670 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
671
672 return _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
673 }
674 catch(Exception $e) {
675 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
676 }
677 }
678
679 /**
680 * Calls IPN complete transaction for completing or repeating a transaction.
681 *
682 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
683 * when separating them in the api layer.
684 *
685 * @param array $params
686 * @param CRM_Contribute_BAO_Contribution $contribution
687 * @param array $input
688 *
689 * @param array $ids
690 *
691 * @param CRM_Contribute_BAO_Contribution $firstContribution
692 *
693 * @return mixed
694 */
695 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
696 $objects = $contribution->_relatedObjects;
697 $objects['contribution'] = &$contribution;
698
699 if ($firstContribution) {
700 $objects['first_contribution'] = $firstContribution;
701 }
702 $input['component'] = $contribution->_component;
703 $input['is_test'] = $contribution->is_test;
704 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
705
706 if (isset($params['is_email_receipt'])) {
707 $input['is_email_receipt'] = $params['is_email_receipt'];
708 }
709 if (!empty($params['trxn_date'])) {
710 $input['trxn_date'] = $params['trxn_date'];
711 }
712 if (!empty($params['receive_date'])) {
713 $input['receive_date'] = $params['receive_date'];
714 }
715 if (empty($contribution->contribution_page_id)) {
716 static $domainFromName;
717 static $domainFromEmail;
718 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
719 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
720 }
721 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
722 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
723 }
724 $input['card_type_id'] = CRM_Utils_Array::value('card_type_id', $params);
725 $input['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $params);
726 $transaction = new CRM_Core_Transaction();
727 return CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, !empty
728 ($contribution->contribution_recur_id), $contribution);
729 }
730
731 /**
732 * Provide function metadata.
733 *
734 * @param array $params
735 */
736 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
737 $params['original_contribution_id'] = array(
738 'title' => 'Original Contribution ID',
739 'description' => 'Contribution ID to copy (will be calculated from recurring contribution if not provided)',
740 'type' => CRM_Utils_Type::T_INT,
741 );
742 $params['contribution_recur_id'] = array(
743 'title' => 'Recurring contribution ID',
744 'type' => CRM_Utils_Type::T_INT,
745 );
746 $params['trxn_id'] = array(
747 'title' => 'Transaction ID',
748 'type' => CRM_Utils_Type::T_STRING,
749 );
750 $params['is_email_receipt'] = array(
751 'title' => 'Send email Receipt?',
752 'type' => CRM_Utils_Type::T_BOOLEAN,
753 );
754 $params['contribution_status_id'] = array(
755 'title' => 'Contribution Status ID',
756 'name' => 'contribution_status_id',
757 'type' => CRM_Utils_Type::T_INT,
758 'pseudoconstant' => array(
759 'optionGroupName' => 'contribution_status',
760 ),
761 'api.required' => TRUE,
762 );
763 $params['receive_date'] = array(
764 'title' => 'Contribution Receive Date',
765 'name' => 'receive_date',
766 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
767 'api.default' => 'now',
768 );
769 $params['trxn_id'] = array(
770 'title' => 'Transaction ID',
771 'name' => 'trxn_id',
772 'type' => CRM_Utils_Type::T_STRING,
773 );
774 $params['campaign_id'] = array(
775 'title' => 'Campaign ID',
776 'name' => 'campaign_id',
777 'type' => CRM_Utils_Type::T_INT,
778 'pseudoconstant' => array(
779 'table' => 'civicrm_campaign',
780 'keyColumn' => 'id',
781 'labelColumn' => 'title',
782 ),
783 );
784 $params['financial_type_id'] = array(
785 'title' => 'Financial ID (ignored if more than one line item)',
786 'name' => 'financial_type_id',
787 'type' => CRM_Utils_Type::T_INT,
788 'pseudoconstant' => array(
789 'table' => 'civicrm_financial_type',
790 'keyColumn' => 'id',
791 'labelColumn' => 'name',
792 ),
793 );
794 $params['payment_processor_id'] = array(
795 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
796 'title' => 'Payment processor ID',
797 'name' => 'payment_processor_id',
798 'type' => CRM_Utils_Type::T_INT,
799 );
800 }