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