INFRA-132 - Batch 14 (g)
[civicrm-core.git] / api / v3 / Contribution.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
731a0992 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 * File for the CiviCRM APIv3 Contribution functions
30 *
31 * @package CiviCRM_APIv3
32 * @subpackage API_Contribute
33 *
731a0992 34 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
35 * @version $Id: Contribution.php 30486 2010-11-02 16:12:09Z shot $
36 *
37 */
38
39/**
40 * Add or update a contribution
41 *
cf470720
TO
42 * @param array $params
43 * (reference ) input parameters.
6a488035 44 *
69dbd1ba 45 * @throws API_Exception
a6c01b45 46 * @return array
72b3a70c 47 * Api result array
6a488035
TO
48 */
49function civicrm_api3_contribution_create(&$params) {
50 $values = array();
6a488035 51 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
504a78f6 52 $params = array_merge($params, $values);
53
8cc574cf 54 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
504a78f6 55 $error = array();
56 //throw error for invalid status change such as setting completed back to pending
57 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
58 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
59 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
60 if (array_key_exists('contribution_status_id', $error)) {
61 throw new API_Exception($error['contribution_status_id']);
62 }
6a488035 63 }
6a516bd6
DG
64
65 _civicrm_api3_contribution_create_legacy_support_45($params);
66
21a3b46e 67 // make sure tax calculation is handled via api
b5935203 68 $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
ebf2b57b 69
504a78f6 70 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
6a488035 71}
11e09c59
TO
72
73/**
6a488035
TO
74 * Adjust Metadata for Create action
75 *
76 * The metadata is used for setting defaults, documentation & validation
cf470720
TO
77 * @param array $params
78 * Array or parameters determined by getfields.
6a488035
TO
79 */
80function _civicrm_api3_contribution_create_spec(&$params) {
81 $params['contact_id']['api.required'] = 1;
82 $params['total_amount']['api.required'] = 1;
53191813 83 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
8757a378 84 $params['receive_date']['api.default'] = 'now';
6a488035
TO
85 $params['payment_processor'] = array(
86 'name' => 'payment_processor',
87 'title' => 'Payment Processor ID',
88 'description' => 'ID of payment processor used for this contribution',
89 // field is called payment processor - not payment processor id but can only be one id so
90 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
91 'api.aliases' => array('payment_processor_id'),
92 );
93 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
94 $params['financial_type_id']['api.required'] = 1;
95 $params['note'] = array(
96 'name' => 'note',
97 'uniqueName' => 'contribution_note',
98 'title' => 'note',
99 'type' => 2,
100 'description' => 'Associated Note in the notes table',
101 );
102 $params['soft_credit_to'] = array(
103 'name' => 'soft_credit_to',
33a429d4 104 'title' => 'Soft Credit contact ID (legacy)',
6a488035 105 'type' => 1,
33a429d4 106 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
6a488035
TO
107 'FKClassName' => 'CRM_Contact_DAO_Contact',
108 );
6a516bd6
DG
109 $params['honor_contact_id'] = array(
110 'name' => 'honor_contact_id',
33a429d4 111 'title' => 'Honoree contact ID (legacy)',
6a516bd6 112 'type' => 1,
33a429d4 113 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
6a516bd6
DG
114 'FKClassName' => 'CRM_Contact_DAO_Contact',
115 );
33a429d4
CW
116 $params['honor_type_id'] = array(
117 'name' => 'honor_type_id',
118 'title' => 'Honoree Type (legacy)',
119 'type' => 1,
120 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
121 'pseudoconstant' => TRUE,
122 );
6a488035 123 // note this is a recommended option but not adding as a default to avoid
c206647d 124 // creating unnecessary changes for the dev
6a488035
TO
125 $params['skipRecentView'] = array(
126 'name' => 'skipRecentView',
127 'title' => 'Skip adding to recent view',
0900b21e 128 'type' => CRM_Utils_Type::T_BOOLEAN,
6a488035
TO
129 'description' => 'Do not add to recent view (setting this improves performance)',
130 );
131 $params['skipLineItem'] = array(
132 'name' => 'skipLineItem',
133 'title' => 'Skip adding line items',
134 'type' => 1,
135 'api.default' => 0,
136 'description' => 'Do not add line items by default (if you wish to add your own)',
137 );
599c61ac
E
138 $params['batch_id'] = array(
139 'title' => 'Batch',
140 'type' => 1,
141 'description' => 'Batch which relevant transactions should be added to',
142 );
6a488035
TO
143}
144
6a516bd6 145/**
35671d00
TO
146 * Support for schema changes made in 4.5
147 * The main purpose of the API is to provide integrators a level of stability not provided by
148 * the core code or schema - this means we have to provide support for api calls (where possible)
149 * across schema changes.
d0997921 150 * @param array $params
35671d00 151 */
9b873358 152function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
6a516bd6 153 //legacy soft credit handling - recommended approach is chaining
9b873358 154 if (!empty($params['soft_credit_to'])) {
33a429d4 155 $params['soft_credit'][] = array(
6a516bd6
DG
156 'contact_id' => $params['soft_credit_to'],
157 'amount' => $params['total_amount'],
21dfd5f5 158 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
33a429d4 159 );
6a516bd6 160 }
9b873358 161 if (!empty($params['honor_contact_id'])) {
33a429d4 162 $params['soft_credit'][] = array(
6a516bd6
DG
163 'contact_id' => $params['honor_contact_id'],
164 'amount' => $params['total_amount'],
21dfd5f5 165 'soft_credit_type_id' => CRM_Utils_Array::value('honor_type_id', $params, CRM_Core_OptionGroup::getValue('soft_credit_type', 'in_honor_of', 'name')),
33a429d4 166 );
6a516bd6
DG
167 }
168}
169
6a488035
TO
170/**
171 * Delete a contribution
172 *
cf470720
TO
173 * @param array $params
174 * (reference ) input parameters.
6a488035 175 *
a6c01b45 176 * @return boolean
72b3a70c 177 * true if success, else false
6a488035
TO
178 */
179function civicrm_api3_contribution_delete($params) {
180
0d8afee2 181 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
6a488035
TO
182 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
183 return civicrm_api3_create_success(array($contributionID => 1));
184 }
185 else {
186 return civicrm_api3_create_error('Could not delete contribution');
187 }
188}
11e09c59
TO
189
190/**
6a488035 191 * modify metadata. Legacy support for contribution_id
d0997921 192 * @param array $params
6a488035
TO
193 */
194function _civicrm_api3_contribution_delete_spec(&$params) {
195 $params['id']['api.aliases'] = array('contribution_id');
196}
197
198/**
199 * Retrieve a set of contributions, given a set of input params
200 *
cf470720
TO
201 * @param array $params
202 * (reference ) input parameters.
69dbd1ba 203 *
a6c01b45 204 * @return array
16b10e64 205 * Array of contributions, if error an array with an error id and error message
6a488035
TO
206 */
207function civicrm_api3_contribution_get($params) {
208
82f7d8b2
EM
209 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
210 $entity = 'contribution';
211 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, $entity);
6a488035
TO
212
213 $contribution = array();
214 while ($dao->fetch()) {
215 //CRM-8662
76ca3345 216 $contribution_details = $query->store($dao);
35671d00 217 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id, TRUE);
76ca3345 218 $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution);
76ca3345
KJ
219 // format soft credit for backward compatibility
220 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
6a488035
TO
221 }
222 return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao);
223}
11e09c59 224
76ca3345
KJ
225/**
226 * This function is used to format the soft credit for backward compatibility
227 * as of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
228 * but we still return first soft credit as a part of contribution array
645ee340 229 * @param $contribution
76ca3345
KJ
230 */
231function _civicrm_api3_format_soft_credit(&$contribution) {
232 if (!empty($contribution['soft_credit'])) {
233 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
234 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
235 }
236}
237
11e09c59 238/**
6a488035
TO
239 * Adjust Metadata for Get action
240 *
241 * The metadata is used for setting defaults, documentation & validation
cf470720
TO
242 * @param array $params
243 * Array or parameters determined by getfields.
6a488035
TO
244 */
245function _civicrm_api3_contribution_get_spec(&$params) {
246 $params['contribution_test']['api.default'] = 0;
4c41ecb2 247 $params['contribution_test']['title'] = 'Get Test Contributions?';
6a488035
TO
248 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
249 $params['contact_id'] = $params['contribution_contact_id'];
250 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
251 unset($params['contribution_contact_id']);
252}
253
254/**
255 * take the input parameter list as specified in the data model and
256 * convert it into the same format that we use in QF and BAO object
257 *
cf470720 258 * @param array $params
c23f45d3 259 * property name/value pairs to insert in new contact.
cf470720
TO
260 * @param array $values
261 * The reformatted properties that we can use internally.
6a488035 262 *
c23f45d3 263 * @return array
6a488035 264 */
c23f45d3 265function _civicrm_api3_contribute_format_params($params, &$values) {
35671d00 266 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
6a488035 267 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
6a488035
TO
268 return array();
269}
270
16c0ec8d
CW
271/**
272 * Adjust Metadata for Transact action
273 *
274 * The metadata is used for setting defaults, documentation & validation
cf470720
TO
275 * @param array $params
276 * Array or parameters determined by getfields.
16c0ec8d
CW
277 */
278function _civicrm_api3_contribution_transact_spec(&$params) {
4c41ecb2
EM
279 $fields = civicrm_api3('contribution', 'getfields', array('action' => 'create'));
280 $params = array_merge($params, $fields['values']);
16c0ec8d
CW
281 $params['receive_date']['api.default'] = 'now';
282}
283
6a488035
TO
284/**
285 * Process a transaction and record it against the contact.
286 *
cf470720
TO
287 * @param array $params
288 * (reference ) input parameters.
6a488035 289 *
a6c01b45 290 * @return array
c23f45d3 291 * contribution of created or updated record (or a civicrm error)
6a488035
TO
292 */
293function civicrm_api3_contribution_transact($params) {
16c0ec8d
CW
294 // Set some params specific to payment processing
295 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
296 $params['amount'] = $params['total_amount'];
6a488035
TO
297 if (!isset($params['net_amount'])) {
298 $params['net_amount'] = $params['amount'];
299 }
6a488035
TO
300 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
301 $params['invoiceID'] = $params['invoice_id'];
302 }
303
be06e507
CW
304 // Some payment processors expect a unique invoice_id - generate one if not supplied
305 $params['invoice_id'] = CRM_Utils_Array::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
306
16c0ec8d 307 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
6a488035
TO
308 if (civicrm_error($paymentProcessor)) {
309 return $paymentProcessor;
310 }
311
16c0ec8d 312 $payment = CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
6a488035
TO
313 if (civicrm_error($payment)) {
314 return $payment;
315 }
316
317 $transaction = $payment->doDirectPayment($params);
318 if (civicrm_error($transaction)) {
319 return $transaction;
320 }
321
322 // but actually, $payment->doDirectPayment() doesn't return a
323 // CRM_Core_Error by itself
16c0ec8d 324 if (is_object($transaction) && get_class($transaction) == 'CRM_Core_Error') {
6a488035
TO
325 $errs = $transaction->getErrors();
326 if (!empty($errs)) {
327 $last_error = array_shift($errs);
328 return CRM_Core_Error::createApiError($last_error['message']);
329 }
330 }
26ad2b72 331 $params['payment_instrument_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ? 'Credit Card' : 'Debit Card';
16c0ec8d 332 return civicrm_api('contribution', 'create', $params);
6a488035 333}
69dbd1ba 334
6a488035
TO
335/**
336 * Send a contribution confirmation (receipt or invoice)
337 * The appropriate online template will be used (the existence of related objects
338 * (e.g. memberships ) will affect this selection
69dbd1ba 339 *
cf470720
TO
340 * @param array $params
341 * Input parameters.
69dbd1ba
EM
342 *
343 * @throws Exception
a6c01b45 344 * @return array
72b3a70c 345 * Api result array
6a488035
TO
346 */
347function civicrm_api3_contribution_sendconfirmation($params) {
348 $contribution = new CRM_Contribute_BAO_Contribution();
349 $contribution->id = $params['id'];
76ca3345 350 if (! $contribution->find(TRUE)) {
6a488035 351 throw new Exception('Contribution does not exist');
35671d00 352 }
6a488035 353 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
76ca3345
KJ
354 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
355 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
6a488035
TO
356}
357
11e09c59 358/**
6a0cf2c6 359 * Adjust Metadata for sendconfirmation action
6a488035
TO
360 *
361 * The metadata is used for setting defaults, documentation & validation
cf470720
TO
362 * @param array $params
363 * Array or parameters determined by getfields.
6a488035
TO
364 */
365function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
366 $params['id'] = array(
367 'api.required' => 1,
21dfd5f5 368 'title' => 'Contribution ID',
6a488035
TO
369 );
370 $params['receipt_from_email'] = array(
35671d00 371 'api.required' => 1,
6a0cf2c6
CW
372 'title' => 'From Email address (string) required until someone provides a patch :-)',
373 );
374 $params['receipt_from_name'] = array(
375 'title' => 'From Name (string)',
376 );
377 $params['cc_receipt'] = array(
378 'title' => 'CC Email address (string)',
379 );
380 $params['bcc_receipt'] = array(
381 'title' => 'BCC Email address (string)',
382 );
383 $params['receipt_text'] = array(
384 'title' => 'Message (string)',
6a488035
TO
385 );
386}
0efa8efe 387
388/**
389 * Complete an existing (pending) transaction, updating related entities (participant, membership, pledge etc)
390 * and taking any complete actions from the contribution page (e.g. send receipt)
391 *
392 * @todo - most of this should live in the BAO layer but as we want it to be an addition
393 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
394 *
cf470720
TO
395 * @param array $params
396 * Input parameters.
0efa8efe 397 * {@getfields Contribution_completetransaction}
69dbd1ba
EM
398 *
399 * @throws API_Exception
a6c01b45 400 * @return array
72b3a70c 401 * Api result array
0efa8efe 402 */
403function civicrm_api3_contribution_completetransaction(&$params) {
404
405 $input = $ids = array();
406 $contribution = new CRM_Contribute_BAO_Contribution();
407 $contribution->id = $params['id'];
408 $contribution->find(TRUE);
9b873358 409 if (!$contribution->id == $params['id']) {
0efa8efe 410 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
411 }
412 try {
9b873358 413 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
0efa8efe 414 throw new API_Exception('failed to load related objects');
415 }
1ba809f7 416 elseif ($contribution->contribution_status_id == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
9e2ee07b
EM
417 throw new API_Exception(ts('Contribution already completed'));
418 }
0efa8efe 419 $objects = $contribution->_relatedObjects;
420 $objects['contribution'] = &$contribution;
421 $input['component'] = $contribution->_component;
422 $input['is_test'] = $contribution->is_test;
35671d00 423 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
0efa8efe 424 $input['amount'] = $contribution->total_amount;
9b873358 425 if (isset($params['is_email_receipt'])) {
0efa8efe 426 $input['is_email_receipt'] = $params['is_email_receipt'];
427 }
428 // @todo required for base ipn but problematic as api layer handles this
429 $transaction = new CRM_Core_Transaction();
430 $ipn = new CRM_Core_Payment_BaseIPN();
f6780fb8 431 $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id));
0efa8efe 432 }
0e37ad72 433 catch(Exception $e) {
0efa8efe 434 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
435 }
436}
437
aa1b1481 438/**
3dfbdece 439 * provide function metadata
c490a46a 440 * @param array $params
aa1b1481 441 */
3dfbdece 442function _civicrm_api3_contribution_completetransaction_spec(&$params) {
eac25df2
EM
443 $params['id'] = array(
444 'title' => 'Contribution ID',
445 'type' => CRM_Utils_Type::T_INT,
446 'api.required' => TRUE,
447 );
448 $params['trxn_id'] = array(
449 'title' => 'Transaction ID',
450 'type' => CRM_Utils_Type::T_STRING,
451 );
452 $params['is_email_receipt'] = array(
453 'title' => 'Send email Receipt?',
454 'type' => CRM_Utils_Type::T_BOOLEAN,
455 );
0efa8efe 456}