Merge pull request #13186 from aydun/override_active_tokens
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
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'] = $paymentProcessor['object']->getPaymentInstrumentID();
438
439 return civicrm_api('Contribution', 'create', $params);
440 }
441
442 /**
443 * Send a contribution confirmation (receipt or invoice).
444 *
445 * The appropriate online template will be used (the existence of related objects
446 * (e.g. memberships ) will affect this selection
447 *
448 * @param array $params
449 * Input parameters.
450 *
451 * @throws Exception
452 */
453 function civicrm_api3_contribution_sendconfirmation($params) {
454 $ids = $values = array();
455 $allowedParams = array(
456 'receipt_from_email',
457 'receipt_from_name',
458 'receipt_update',
459 'cc_receipt',
460 'bcc_receipt',
461 'receipt_text',
462 'payment_processor_id',
463 );
464 $input = array_intersect_key($params, array_flip($allowedParams));
465 $input['is_email_receipt'] = TRUE;
466 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $params['id'], $values);
467 }
468
469 /**
470 * Adjust Metadata for sendconfirmation action.
471 *
472 * The metadata is used for setting defaults, documentation & validation.
473 *
474 * @param array $params
475 * Array of parameters determined by getfields.
476 */
477 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
478 $params['id'] = array(
479 'api.required' => 1,
480 'title' => ts('Contribution ID'),
481 'type' => CRM_Utils_Type::T_INT,
482 );
483 $params['receipt_from_email'] = array(
484 'title' => ts('From Email address (string)'),
485 'type' => CRM_Utils_Type::T_STRING,
486 );
487 $params['receipt_from_name'] = array(
488 'title' => ts('From Name (string)'),
489 'type' => CRM_Utils_Type::T_STRING,
490 );
491 $params['cc_receipt'] = array(
492 'title' => ts('CC Email address (string)'),
493 'type' => CRM_Utils_Type::T_STRING,
494 );
495 $params['bcc_receipt'] = array(
496 'title' => ts('BCC Email address (string)'),
497 'type' => CRM_Utils_Type::T_STRING,
498 );
499 $params['receipt_text'] = array(
500 'title' => ts('Message (string)'),
501 'type' => CRM_Utils_Type::T_STRING,
502 );
503 $params['receipt_update'] = array(
504 'title' => ts('Update the Receipt Date'),
505 'type' => CRM_Utils_Type::T_BOOLEAN,
506 'api.default' => TRUE,
507 );
508 $params['payment_processor_id'] = array(
509 'title' => ts('Payment processor Id (avoids mis-guesses)'),
510 'type' => CRM_Utils_Type::T_INT,
511 );
512 }
513
514 /**
515 * Complete an existing (pending) transaction.
516 *
517 * This will update related entities (participant, membership, pledge etc)
518 * and take any complete actions from the contribution page (e.g. send receipt).
519 *
520 * @todo - most of this should live in the BAO layer but as we want it to be an addition
521 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
522 *
523 * @param array $params
524 * Input parameters.
525 *
526 * @return array
527 * API result array
528 * @throws \API_Exception
529 * @throws \CRM_Core_Exception
530 * @throws \Exception
531 */
532 function civicrm_api3_contribution_completetransaction(&$params) {
533 $input = $ids = array();
534 if (isset($params['payment_processor_id'])) {
535 $input['payment_processor_id'] = $params['payment_processor_id'];
536 }
537 $contribution = new CRM_Contribute_BAO_Contribution();
538 $contribution->id = $params['id'];
539 if (!$contribution->find(TRUE)) {
540 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
541 }
542
543 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
544 throw new API_Exception('failed to load related objects');
545 }
546 elseif ($contribution->contribution_status_id == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
547 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
548 }
549 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
550 if (!empty($params['fee_amount'])) {
551 $input['fee_amount'] = $params['fee_amount'];
552 }
553 return _ipn_process_transaction($params, $contribution, $input, $ids);
554
555 }
556
557 /**
558 * Provide function metadata.
559 *
560 * @param array $params
561 */
562 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
563 $params['id'] = array(
564 'title' => 'Contribution ID',
565 'type' => CRM_Utils_Type::T_INT,
566 'api.required' => TRUE,
567 );
568 $params['trxn_id'] = array(
569 'title' => 'Transaction ID',
570 'type' => CRM_Utils_Type::T_STRING,
571 );
572 $params['is_email_receipt'] = array(
573 'title' => 'Send email Receipt?',
574 'type' => CRM_Utils_Type::T_BOOLEAN,
575 );
576 $params['receipt_from_email'] = array(
577 'title' => 'Email to send receipt from.',
578 'description' => 'If not provided this will default to being based on domain mail or contribution page',
579 'type' => CRM_Utils_Type::T_EMAIL,
580 );
581 $params['receipt_from_name'] = array(
582 'title' => 'Name to send receipt from',
583 'description' => '. If not provided this will default to domain mail or contribution page',
584 'type' => CRM_Utils_Type::T_STRING,
585 );
586 $params['payment_processor_id'] = array(
587 'title' => 'Payment processor ID',
588 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
589 'type' => CRM_Utils_Type::T_INT,
590 );
591 $params['fee_amount'] = array(
592 'title' => 'Fee charged on transaction',
593 'description' => 'If a fee has been charged then the amount',
594 'type' => CRM_Utils_Type::T_FLOAT,
595 );
596 $params['trxn_date'] = array(
597 'title' => 'Transaction Date',
598 'description' => 'Date this transaction occurred',
599 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
600 );
601 $params['card_type_id'] = array(
602 'title' => 'Card Type ID',
603 'description' => 'Providing Credit Card Type ID',
604 'type' => CRM_Utils_Type::T_INT,
605 'pseudoconstant' => array(
606 'optionGroupName' => 'accept_creditcard',
607 ),
608 );
609 }
610
611 /**
612 * Complete an existing (pending) transaction.
613 *
614 * This will update related entities (participant, membership, pledge etc)
615 * and take any complete actions from the contribution page (e.g. send receipt).
616 *
617 * @todo - most of this should live in the BAO layer but as we want it to be an addition
618 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
619 *
620 * @param array $params
621 * Input parameters.
622 *
623 * @return array
624 * Api result array.
625 * @throws API_Exception
626 */
627 function civicrm_api3_contribution_repeattransaction(&$params) {
628 $input = $ids = array();
629 civicrm_api3_verify_one_mandatory($params, NULL, array('contribution_recur_id', 'original_contribution_id'));
630 if (empty($params['original_contribution_id'])) {
631 // CRM-19873 call with test mode.
632 $params['original_contribution_id'] = civicrm_api3('contribution', 'getvalue', array(
633 'return' => 'id',
634 'contribution_status_id' => array('IN' => array('Completed')),
635 'contribution_recur_id' => $params['contribution_recur_id'],
636 'contribution_test' => CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur', $params['contribution_recur_id'], 'is_test'),
637 'options' => array('limit' => 1, 'sort' => 'id DESC'),
638 ));
639 }
640 $contribution = new CRM_Contribute_BAO_Contribution();
641 $contribution->id = $params['original_contribution_id'];
642 if (!$contribution->find(TRUE)) {
643 throw new API_Exception(
644 'A valid original contribution ID is required', 'invalid_data');
645 }
646 $original_contribution = clone $contribution;
647 $input['payment_processor_id'] = civicrm_api3('contributionRecur', 'getvalue', array(
648 'return' => 'payment_processor_id',
649 'id' => $contribution->contribution_recur_id,
650 ));
651 try {
652 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
653 throw new API_Exception('failed to load related objects');
654 }
655
656 unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
657 $contribution->receive_date = $params['receive_date'];
658
659 $passThroughParams = array(
660 'trxn_id',
661 'total_amount',
662 'campaign_id',
663 'fee_amount',
664 'financial_type_id',
665 'contribution_status_id',
666 );
667 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
668
669 return _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
670 }
671 catch(Exception $e) {
672 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
673 }
674 }
675
676 /**
677 * Calls IPN complete transaction for completing or repeating a transaction.
678 *
679 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
680 * when separating them in the api layer.
681 *
682 * @param array $params
683 * @param CRM_Contribute_BAO_Contribution $contribution
684 * @param array $input
685 *
686 * @param array $ids
687 *
688 * @param CRM_Contribute_BAO_Contribution $firstContribution
689 *
690 * @return mixed
691 */
692 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
693 $objects = $contribution->_relatedObjects;
694 $objects['contribution'] = &$contribution;
695
696 if ($firstContribution) {
697 $objects['first_contribution'] = $firstContribution;
698 }
699 $input['component'] = $contribution->_component;
700 $input['is_test'] = $contribution->is_test;
701 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
702
703 if (isset($params['is_email_receipt'])) {
704 $input['is_email_receipt'] = $params['is_email_receipt'];
705 }
706 if (!empty($params['trxn_date'])) {
707 $input['trxn_date'] = $params['trxn_date'];
708 }
709 if (!empty($params['receive_date'])) {
710 $input['receive_date'] = $params['receive_date'];
711 }
712 if (empty($contribution->contribution_page_id)) {
713 static $domainFromName;
714 static $domainFromEmail;
715 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
716 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
717 }
718 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
719 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
720 }
721 $input['card_type_id'] = CRM_Utils_Array::value('card_type_id', $params);
722 $input['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $params);
723 $transaction = new CRM_Core_Transaction();
724 return CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, !empty
725 ($contribution->contribution_recur_id), $contribution);
726 }
727
728 /**
729 * Provide function metadata.
730 *
731 * @param array $params
732 */
733 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
734 $params['original_contribution_id'] = array(
735 'title' => 'Original Contribution ID',
736 'description' => 'Contribution ID to copy (will be calculated from recurring contribution if not provided)',
737 'type' => CRM_Utils_Type::T_INT,
738 );
739 $params['contribution_recur_id'] = array(
740 'title' => 'Recurring contribution ID',
741 'type' => CRM_Utils_Type::T_INT,
742 );
743 $params['trxn_id'] = array(
744 'title' => 'Transaction ID',
745 'type' => CRM_Utils_Type::T_STRING,
746 );
747 $params['is_email_receipt'] = array(
748 'title' => 'Send email Receipt?',
749 'type' => CRM_Utils_Type::T_BOOLEAN,
750 );
751 $params['contribution_status_id'] = array(
752 'title' => 'Contribution Status ID',
753 'name' => 'contribution_status_id',
754 'type' => CRM_Utils_Type::T_INT,
755 'pseudoconstant' => array(
756 'optionGroupName' => 'contribution_status',
757 ),
758 'api.required' => TRUE,
759 );
760 $params['receive_date'] = array(
761 'title' => 'Contribution Receive Date',
762 'name' => 'receive_date',
763 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
764 'api.default' => 'now',
765 );
766 $params['trxn_id'] = array(
767 'title' => 'Transaction ID',
768 'name' => 'trxn_id',
769 'type' => CRM_Utils_Type::T_STRING,
770 );
771 $params['campaign_id'] = array(
772 'title' => 'Campaign ID',
773 'name' => 'campaign_id',
774 'type' => CRM_Utils_Type::T_INT,
775 'pseudoconstant' => array(
776 'table' => 'civicrm_campaign',
777 'keyColumn' => 'id',
778 'labelColumn' => 'title',
779 ),
780 );
781 $params['financial_type_id'] = array(
782 'title' => 'Financial ID (ignored if more than one line item)',
783 'name' => 'financial_type_id',
784 'type' => CRM_Utils_Type::T_INT,
785 'pseudoconstant' => array(
786 'table' => 'civicrm_financial_type',
787 'keyColumn' => 'id',
788 'labelColumn' => 'name',
789 ),
790 );
791 $params['payment_processor_id'] = array(
792 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
793 'title' => 'Payment processor ID',
794 'name' => 'payment_processor_id',
795 'type' => CRM_Utils_Type::T_INT,
796 );
797 }