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