Merge pull request #10996 from omarabuhussein/CRM-21195-Adding-icons-to-navigation...
[civicrm-core.git] / api / v3 / Contribution.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
81621fee 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
1f4ea726 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
b081365f 29 * This api exposes CiviCRM Contribution records.
6a488035
TO
30 *
31 * @package CiviCRM_APIv3
6a488035
TO
32 */
33
34/**
244bbdd8 35 * Add or update a Contribution.
6a488035 36 *
cf470720 37 * @param array $params
9d32e6f7 38 * Input parameters.
6a488035 39 *
69dbd1ba 40 * @throws API_Exception
a6c01b45 41 * @return array
72b3a70c 42 * Api result array
6a488035
TO
43 */
44function civicrm_api3_contribution_create(&$params) {
45 $values = array();
6a488035 46 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
504a78f6 47 $params = array_merge($params, $values);
48
3300bf67
PN
49 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
50 if (empty($params['id'])) {
8715ff99 51 $op = CRM_Core_Action::ADD;
3300bf67
PN
52 }
53 else {
54 if (empty($params['financial_type_id'])) {
f4a331f4 55 $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $params['id'], 'financial_type_id');
3300bf67 56 }
8715ff99 57 $op = CRM_Core_Action::UPDATE;
3300bf67
PN
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 }
816cac04 63 }
8cc574cf 64 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
504a78f6 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 }
6a488035 73 }
4d47ad17
PN
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 }
6a516bd6
DG
81 _civicrm_api3_contribution_create_legacy_support_45($params);
82
504a78f6 83 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
6a488035 84}
11e09c59
TO
85
86/**
0aa0303c
EM
87 * Adjust Metadata for Create action.
88 *
89 * The metadata is used for setting defaults, documentation & validation.
6a488035 90 *
cf470720 91 * @param array $params
b081365f 92 * Array of parameters determined by getfields.
6a488035
TO
93 */
94function _civicrm_api3_contribution_create_spec(&$params) {
95 $params['contact_id']['api.required'] = 1;
96 $params['total_amount']['api.required'] = 1;
53191813 97 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
8757a378 98 $params['receive_date']['api.default'] = 'now';
6a488035
TO
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'),
d142432b 106 'type' => CRM_Utils_Type::T_INT,
6a488035
TO
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',
33a429d4 119 'title' => 'Soft Credit contact ID (legacy)',
797d4c52 120 'type' => CRM_Utils_Type::T_INT,
33a429d4 121 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
6a488035
TO
122 'FKClassName' => 'CRM_Contact_DAO_Contact',
123 );
6a516bd6
DG
124 $params['honor_contact_id'] = array(
125 'name' => 'honor_contact_id',
33a429d4 126 'title' => 'Honoree contact ID (legacy)',
797d4c52 127 'type' => CRM_Utils_Type::T_INT,
33a429d4 128 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
6a516bd6
DG
129 'FKClassName' => 'CRM_Contact_DAO_Contact',
130 );
33a429d4
CW
131 $params['honor_type_id'] = array(
132 'name' => 'honor_type_id',
133 'title' => 'Honoree Type (legacy)',
797d4c52 134 'type' => CRM_Utils_Type::T_INT,
33a429d4
CW
135 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
136 'pseudoconstant' => TRUE,
137 );
6a488035 138 // note this is a recommended option but not adding as a default to avoid
c206647d 139 // creating unnecessary changes for the dev
6a488035
TO
140 $params['skipRecentView'] = array(
141 'name' => 'skipRecentView',
142 'title' => 'Skip adding to recent view',
0900b21e 143 'type' => CRM_Utils_Type::T_BOOLEAN,
6a488035
TO
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',
b3b7f4c5 149 'type' => CRM_Utils_Type::T_BOOLEAN,
6a488035
TO
150 'api.default' => 0,
151 'description' => 'Do not add line items by default (if you wish to add your own)',
152 );
599c61ac
E
153 $params['batch_id'] = array(
154 'title' => 'Batch',
797d4c52 155 'type' => CRM_Utils_Type::T_INT,
599c61ac
E
156 'description' => 'Batch which relevant transactions should be added to',
157 );
797d4c52 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 );
a55e39e9 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 );
6a488035
TO
171}
172
6a516bd6 173/**
9d32e6f7
EM
174 * Support for schema changes made in 4.5.
175 *
35671d00
TO
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.
dc64d047 179 *
d0997921 180 * @param array $params
35671d00 181 */
9b873358 182function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
6a516bd6 183 //legacy soft credit handling - recommended approach is chaining
9b873358 184 if (!empty($params['soft_credit_to'])) {
33a429d4 185 $params['soft_credit'][] = array(
6a516bd6
DG
186 'contact_id' => $params['soft_credit_to'],
187 'amount' => $params['total_amount'],
21dfd5f5 188 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
33a429d4 189 );
6a516bd6 190 }
9b873358 191 if (!empty($params['honor_contact_id'])) {
33a429d4 192 $params['soft_credit'][] = array(
6a516bd6
DG
193 'contact_id' => $params['honor_contact_id'],
194 'amount' => $params['total_amount'],
a28ce73f 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')),
33a429d4 196 );
6a516bd6
DG
197 }
198}
199
6a488035 200/**
244bbdd8 201 * Delete a Contribution.
6a488035 202 *
cf470720 203 * @param array $params
9d32e6f7 204 * Input parameters.
6a488035 205 *
9d32e6f7 206 * @return array
6a488035
TO
207 */
208function civicrm_api3_contribution_delete($params) {
209
0d8afee2 210 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
c93fecd1
E
211 // First check contribution financial type
212 $financialType = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionID, 'financial_type_id');
c93fecd1 213 // Now check permissioned lineitems & permissioned contribution
40c655aa
E
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)
66af7c48 217 ) {
c93fecd1
E
218 return civicrm_api3_create_error('You do not have permission to delete this contribution');
219 }
6a488035
TO
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}
11e09c59
TO
227
228/**
9d32e6f7
EM
229 * Modify metadata for delete action.
230 *
231 * Legacy support for contribution_id.
232 *
d0997921 233 * @param array $params
6a488035
TO
234 */
235function _civicrm_api3_contribution_delete_spec(&$params) {
236 $params['id']['api.aliases'] = array('contribution_id');
237}
238
239/**
35823763 240 * Retrieve a set of contributions.
6a488035 241 *
cf470720 242 * @param array $params
35823763 243 * Input parameters.
69dbd1ba 244 *
a6c01b45 245 * @return array
16b10e64 246 * Array of contributions, if error an array with an error id and error message
6a488035
TO
247 */
248function civicrm_api3_contribution_get($params) {
249
82f7d8b2 250 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
3123273f 251 $additionalOptions = _civicrm_api3_contribution_get_support_nonunique_returns($params);
be81f101 252 $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode);
6a488035 253
3123273f 254 $contributions = _civicrm_api3_get_using_query_object('Contribution', $params, $additionalOptions, NULL, $mode, $returnProperties);
be81f101 255
256 foreach ($contributions as $id => $contribution) {
257 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id, TRUE);
258 $contributions[$id] = array_merge($contribution, $softContribution);
76ca3345 259 // format soft credit for backward compatibility
be81f101 260 _civicrm_api3_format_soft_credit($contributions[$id]);
3123273f 261 _civicrm_api3_contribution_add_supported_fields($contributions[$id]);
262
6a488035 263 }
be81f101 264 return civicrm_api3_create_success($contributions, $params, 'Contribution', 'get');
9ae25b56 265}
266
3123273f 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 */
280function _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 */
296function _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
9ae25b56 314/**
315 * Get number of contacts matching the supplied criteria.
316 *
317 * @param array $params
318 *
319 * @return int
320 */
321function 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;
6a488035 324}
11e09c59 325
76ca3345 326/**
1747ab99
EM
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
76ca3345 330 * but we still return first soft credit as a part of contribution array
dc64d047 331 *
645ee340 332 * @param $contribution
76ca3345
KJ
333 */
334function _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
11e09c59 341/**
1747ab99 342 * Adjust Metadata for Get action.
6a488035 343 *
0aa0303c
EM
344 * The metadata is used for setting defaults, documentation & validation.
345 *
cf470720 346 * @param array $params
b081365f 347 * Array of parameters determined by getfields.
6a488035
TO
348 */
349function _civicrm_api3_contribution_get_spec(&$params) {
d142432b
EM
350 $params['contribution_test'] = array(
351 'api.default' => 0,
352 'type' => CRM_Utils_Type::T_BOOLEAN,
353 'title' => 'Get Test Contributions?',
71d5a412 354 'api.aliases' => array('is_test'),
d142432b 355 );
739a8336 356
6a488035 357 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
e6b9e2ae 358 $params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
03df80cf 359 $params['contact_id'] = CRM_Utils_Array::value('contribution_contact_id', $params);
6a488035
TO
360 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
361 unset($params['contribution_contact_id']);
362}
363
364/**
1747ab99
EM
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.
6a488035 369 *
cf470720 370 * @param array $params
c23f45d3 371 * property name/value pairs to insert in new contact.
cf470720
TO
372 * @param array $values
373 * The reformatted properties that we can use internally.
6a488035 374 *
c23f45d3 375 * @return array
6a488035 376 */
c23f45d3 377function _civicrm_api3_contribute_format_params($params, &$values) {
35671d00 378 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
6a488035 379 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
6a488035
TO
380 return array();
381}
382
16c0ec8d 383/**
1747ab99 384 * Adjust Metadata for Transact action.
16c0ec8d 385 *
0aa0303c
EM
386 * The metadata is used for setting defaults, documentation & validation.
387 *
cf470720 388 * @param array $params
b081365f 389 * Array of parameters determined by getfields.
16c0ec8d
CW
390 */
391function _civicrm_api3_contribution_transact_spec(&$params) {
244bbdd8 392 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
4c41ecb2 393 $params = array_merge($params, $fields['values']);
16c0ec8d
CW
394 $params['receive_date']['api.default'] = 'now';
395}
396
6a488035
TO
397/**
398 * Process a transaction and record it against the contact.
399 *
cf470720 400 * @param array $params
1747ab99 401 * Input parameters.
6a488035 402 *
a6c01b45 403 * @return array
c23f45d3 404 * contribution of created or updated record (or a civicrm error)
6a488035
TO
405 */
406function civicrm_api3_contribution_transact($params) {
16c0ec8d 407 // Set some params specific to payment processing
8319cf11
EM
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.
16c0ec8d
CW
412 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
413 $params['amount'] = $params['total_amount'];
6a488035
TO
414 if (!isset($params['net_amount'])) {
415 $params['net_amount'] = $params['amount'];
416 }
6a488035
TO
417 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
418 $params['invoiceID'] = $params['invoice_id'];
419 }
420
be06e507
CW
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
16c0ec8d 424 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
9d8f43b1 425 $paymentProcessor['object']->doPayment($params);
6a488035 426
26ad2b72 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';
244bbdd8 428 return civicrm_api('Contribution', 'create', $params);
6a488035 429}
69dbd1ba 430
6a488035 431/**
1747ab99
EM
432 * Send a contribution confirmation (receipt or invoice).
433 *
6a488035
TO
434 * The appropriate online template will be used (the existence of related objects
435 * (e.g. memberships ) will affect this selection
69dbd1ba 436 *
cf470720
TO
437 * @param array $params
438 * Input parameters.
69dbd1ba
EM
439 *
440 * @throws Exception
6a488035
TO
441 */
442function civicrm_api3_contribution_sendconfirmation($params) {
71687b3d
CW
443 $ids = $values = array();
444 $allowedParams = array(
ec7e3954
E
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 );
71687b3d 453 $input = array_intersect_key($params, array_flip($allowedParams));
55df1211 454 $input['is_email_receipt'] = TRUE;
ec7e3954 455 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $params['id'], $values);
6a488035
TO
456}
457
11e09c59 458/**
1747ab99 459 * Adjust Metadata for sendconfirmation action.
6a488035 460 *
0aa0303c
EM
461 * The metadata is used for setting defaults, documentation & validation.
462 *
cf470720 463 * @param array $params
b081365f 464 * Array of parameters determined by getfields.
6a488035
TO
465 */
466function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
467 $params['id'] = array(
468 'api.required' => 1,
ec7e3954 469 'title' => ts('Contribution ID'),
d142432b 470 'type' => CRM_Utils_Type::T_INT,
6a488035
TO
471 );
472 $params['receipt_from_email'] = array(
ec7e3954 473 'title' => ts('From Email address (string)'),
d142432b 474 'type' => CRM_Utils_Type::T_STRING,
6a0cf2c6
CW
475 );
476 $params['receipt_from_name'] = array(
ec7e3954 477 'title' => ts('From Name (string)'),
d142432b 478 'type' => CRM_Utils_Type::T_STRING,
6a0cf2c6
CW
479 );
480 $params['cc_receipt'] = array(
ec7e3954 481 'title' => ts('CC Email address (string)'),
d142432b 482 'type' => CRM_Utils_Type::T_STRING,
6a0cf2c6
CW
483 );
484 $params['bcc_receipt'] = array(
ec7e3954 485 'title' => ts('BCC Email address (string)'),
d142432b 486 'type' => CRM_Utils_Type::T_STRING,
6a0cf2c6
CW
487 );
488 $params['receipt_text'] = array(
ec7e3954 489 'title' => ts('Message (string)'),
d142432b 490 'type' => CRM_Utils_Type::T_STRING,
6a488035 491 );
ec7e3954
E
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 );
6a488035 501}
0efa8efe 502
503/**
1747ab99
EM
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).
0efa8efe 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 *
cf470720
TO
512 * @param array $params
513 * Input parameters.
69dbd1ba 514 *
734d2daa 515 * @return array
516 * API result array
517 * @throws \API_Exception
518 * @throws \CRM_Core_Exception
519 * @throws \Exception
0efa8efe 520 */
521function civicrm_api3_contribution_completetransaction(&$params) {
0efa8efe 522 $input = $ids = array();
07b46478 523 if (isset($params['payment_processor_id'])) {
524 $input['payment_processor_id'] = $params['payment_processor_id'];
525 }
0efa8efe 526 $contribution = new CRM_Contribute_BAO_Contribution();
527 $contribution->id = $params['id'];
528 $contribution->find(TRUE);
9b873358 529 if (!$contribution->id == $params['id']) {
0efa8efe 530 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
531 }
5ddd6889 532
276e3ec6 533 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
5ddd6889 534 throw new API_Exception('failed to load related objects');
0efa8efe 535 }
f527e012 536 elseif ($contribution->contribution_status_id == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
5ddd6889 537 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
0efa8efe 538 }
5ddd6889 539 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
080a561b 540 if (!empty($params['fee_amount'])) {
541 $input['fee_amount'] = $params['fee_amount'];
542 }
734d2daa 543 return _ipn_process_transaction($params, $contribution, $input, $ids);
5ddd6889 544
0efa8efe 545}
546
aa1b1481 547/**
9d32e6f7
EM
548 * Provide function metadata.
549 *
c490a46a 550 * @param array $params
aa1b1481 551 */
3dfbdece 552function _civicrm_api3_contribution_completetransaction_spec(&$params) {
eac25df2
EM
553 $params['id'] = array(
554 'title' => 'Contribution ID',
555 'type' => CRM_Utils_Type::T_INT,
556 'api.required' => TRUE,
557 );
558 $params['trxn_id'] = array(
559 'title' => 'Transaction ID',
560 'type' => CRM_Utils_Type::T_STRING,
561 );
562 $params['is_email_receipt'] = array(
563 'title' => 'Send email Receipt?',
564 'type' => CRM_Utils_Type::T_BOOLEAN,
565 );
0930231a
EM
566 $params['receipt_from_email'] = array(
567 'title' => 'Email to send receipt from.',
568 'description' => 'If not provided this will default to being based on domain mail or contribution page',
569 'type' => CRM_Utils_Type::T_EMAIL,
570 );
571 $params['receipt_from_name'] = array(
572 'title' => 'Name to send receipt from',
573 'description' => '. If not provided this will default to domain mail or contribution page',
574 'type' => CRM_Utils_Type::T_STRING,
575 );
07b46478 576 $params['payment_processor_id'] = array(
577 'title' => 'Payment processor ID',
080a561b 578 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
07b46478 579 'type' => CRM_Utils_Type::T_INT,
580 );
080a561b 581 $params['fee_amount'] = array(
582 'title' => 'Fee charged on transaction',
583 'description' => 'If a fee has been charged then the amount',
584 'type' => CRM_Utils_Type::T_FLOAT,
585 );
7104593e 586 $params['trxn_date'] = array(
587 'title' => 'Transaction Date',
588 'description' => 'Date this transaction occurred',
970aa2fe 589 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
7104593e 590 );
a55e39e9 591 $params['card_type_id'] = array(
592 'title' => 'Card Type ID',
593 'description' => 'Providing Credit Card Type ID',
594 'type' => CRM_Utils_Type::T_INT,
595 'pseudoconstant' => array(
596 'optionGroupName' => 'accept_creditcard',
597 ),
598 );
0efa8efe 599}
5fa7c328
EM
600
601/**
602 * Complete an existing (pending) transaction.
603 *
604 * This will update related entities (participant, membership, pledge etc)
605 * and take any complete actions from the contribution page (e.g. send receipt).
606 *
607 * @todo - most of this should live in the BAO layer but as we want it to be an addition
608 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
609 *
610 * @param array $params
611 * Input parameters.
612 *
e4384ce8 613 * @return array
5fa7c328 614 * Api result array.
e4384ce8 615 * @throws API_Exception
5fa7c328
EM
616 */
617function civicrm_api3_contribution_repeattransaction(&$params) {
618 $input = $ids = array();
1eade77d 619 civicrm_api3_verify_one_mandatory($params, NULL, array('contribution_recur_id', 'original_contribution_id'));
620 if (empty($params['original_contribution_id'])) {
018203cd 621 // CRM-19873 call with test mode.
1eade77d 622 $params['original_contribution_id'] = civicrm_api3('contribution', 'getvalue', array(
623 'return' => 'id',
d2334242 624 'contribution_status_id' => array('IN' => array('Completed')),
1eade77d 625 'contribution_recur_id' => $params['contribution_recur_id'],
018203cd 626 'contribution_test' => CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur', $params['contribution_recur_id'], 'is_test'),
1eade77d 627 'options' => array('limit' => 1, 'sort' => 'id DESC'),
628 ));
629 }
5fa7c328
EM
630 $contribution = new CRM_Contribute_BAO_Contribution();
631 $contribution->id = $params['original_contribution_id'];
632 if (!$contribution->find(TRUE)) {
633 throw new API_Exception(
634 'A valid original contribution ID is required', 'invalid_data');
635 }
d97c96dc 636 $original_contribution = clone $contribution;
69a2b0bc
AD
637 $input['payment_processor_id'] = civicrm_api3('contributionRecur', 'getvalue', array(
638 'return' => 'payment_processor_id',
639 'id' => $contribution->contribution_recur_id,
640 ));
5fa7c328 641 try {
276e3ec6 642 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
5fa7c328
EM
643 throw new API_Exception('failed to load related objects');
644 }
d97c96dc
EM
645
646 unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
5fa7c328 647 $contribution->receive_date = $params['receive_date'];
96f0fe0d 648
d5580ed4 649 $passThroughParams = array(
650 'trxn_id',
651 'total_amount',
652 'campaign_id',
653 'fee_amount',
654 'financial_type_id',
655 'contribution_status_id',
656 );
96f0fe0d 657 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
d97c96dc 658
734d2daa 659 return _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
5fa7c328
EM
660 }
661 catch(Exception $e) {
662 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
663 }
664}
665
666/**
667 * Calls IPN complete transaction for completing or repeating a transaction.
668 *
669 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
670 * when separating them in the api layer.
671 *
672 * @param array $params
673 * @param CRM_Contribute_BAO_Contribution $contribution
674 * @param array $input
675 *
676 * @param array $ids
677 *
d97c96dc
EM
678 * @param CRM_Contribute_BAO_Contribution $firstContribution
679 *
5fa7c328
EM
680 * @return mixed
681 */
d97c96dc 682function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
5fa7c328
EM
683 $objects = $contribution->_relatedObjects;
684 $objects['contribution'] = &$contribution;
d97c96dc
EM
685
686 if ($firstContribution) {
687 $objects['first_contribution'] = $firstContribution;
688 }
5fa7c328
EM
689 $input['component'] = $contribution->_component;
690 $input['is_test'] = $contribution->is_test;
96f0fe0d
EM
691 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
692
5fa7c328
EM
693 if (isset($params['is_email_receipt'])) {
694 $input['is_email_receipt'] = $params['is_email_receipt'];
695 }
7104593e 696 if (!empty($params['trxn_date'])) {
697 $input['trxn_date'] = $params['trxn_date'];
698 }
dccd9f4f
ERL
699 if (!empty($params['receive_date'])) {
700 $input['receive_date'] = $params['receive_date'];
701 }
0930231a
EM
702 if (empty($contribution->contribution_page_id)) {
703 static $domainFromName;
704 static $domainFromEmail;
705 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
37b8953e 706 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
0930231a
EM
707 }
708 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
709 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
710 }
a55e39e9 711 $input['card_type_id'] = CRM_Utils_Array::value('card_type_id', $params);
712 $input['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $params);
4b6c8c1e 713 $transaction = new CRM_Core_Transaction();
734d2daa 714 return CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, !empty
4086637a 715 ($contribution->contribution_recur_id), $contribution);
5fa7c328
EM
716}
717
718/**
719 * Provide function metadata.
720 *
721 * @param array $params
722 */
723function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
724 $params['original_contribution_id'] = array(
725 'title' => 'Original Contribution ID',
1eade77d 726 'description' => 'Contribution ID to copy (will be calculated from recurring contribution if not provided)',
727 'type' => CRM_Utils_Type::T_INT,
728 );
729 $params['contribution_recur_id'] = array(
730 'title' => 'Recurring contribution ID',
5fa7c328 731 'type' => CRM_Utils_Type::T_INT,
5fa7c328
EM
732 );
733 $params['trxn_id'] = array(
734 'title' => 'Transaction ID',
735 'type' => CRM_Utils_Type::T_STRING,
736 );
737 $params['is_email_receipt'] = array(
738 'title' => 'Send email Receipt?',
739 'type' => CRM_Utils_Type::T_BOOLEAN,
740 );
741 $params['contribution_status_id'] = array(
742 'title' => 'Contribution Status ID',
d97c96dc 743 'name' => 'contribution_status_id',
5fa7c328
EM
744 'type' => CRM_Utils_Type::T_INT,
745 'pseudoconstant' => array(
746 'optionGroupName' => 'contribution_status',
747 ),
748 'api.required' => TRUE,
749 );
750 $params['receive_date'] = array(
751 'title' => 'Contribution Receive Date',
d97c96dc 752 'name' => 'receive_date',
970aa2fe 753 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
5fa7c328
EM
754 'api.default' => 'now',
755 );
d97c96dc
EM
756 $params['trxn_id'] = array(
757 'title' => 'Transaction ID',
758 'name' => 'trxn_id',
759 'type' => CRM_Utils_Type::T_STRING,
760 );
c02c17df 761 $params['campaign_id'] = array(
762 'title' => 'Campaign ID',
763 'name' => 'campaign_id',
764 'type' => CRM_Utils_Type::T_INT,
765 'pseudoconstant' => array(
766 'table' => 'civicrm_campaign',
767 'keyColumn' => 'id',
768 'labelColumn' => 'title',
769 ),
770 );
3c49d90c 771 $params['financial_type_id'] = array(
772 'title' => 'Financial ID (ignored if more than one line item)',
773 'name' => 'financial_type_id',
774 'type' => CRM_Utils_Type::T_INT,
775 'pseudoconstant' => array(
776 'table' => 'civicrm_financial_type',
777 'keyColumn' => 'id',
778 'labelColumn' => 'name',
779 ),
780 );
d97c96dc
EM
781 $params['payment_processor_id'] = array(
782 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
783 'title' => 'Payment processor ID',
784 'name' => 'payment_processor_id',
785 'type' => CRM_Utils_Type::T_INT,
786 );
5fa7c328 787}