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