phpdoc params is always an array in api
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 *
34 * @copyright CiviCRM LLC (c) 2004-2014
35 * @version $Id: Contribution.php 30486 2010-11-02 16:12:09Z shot $
36 *
37 */
38
39 /**
40 * Add or update a contribution
41 *
42 * @param array $params
43 * (reference ) input parameters.
44 *
45 * @throws API_Exception
46 * @return array
47 * Api result array
48 * @static
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 * @param array $params
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 * @param array $params
201 */
202 function _civicrm_api3_contribution_delete_spec(&$params) {
203 $params['id']['api.aliases'] = array('contribution_id');
204 }
205
206 /**
207 * Retrieve a set of contributions, given a set of input params
208 *
209 * @param array $params
210 * (reference ) input parameters.
211 *
212 * @return array
213 * Array of contributions, if error an array with an error id and error message
214 * @static
215 * @access public
216 * {@getfields Contribution_get}
217 * @example ContributionGet.php
218 */
219 function civicrm_api3_contribution_get($params) {
220
221 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
222 $entity = 'contribution';
223 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, $entity);
224
225 $contribution = array();
226 while ($dao->fetch()) {
227 //CRM-8662
228 $contribution_details = $query->store($dao);
229 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id, TRUE);
230 $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution);
231 if (isset($contribution[$dao->contribution_id]['financial_type_id'])) {
232 $contribution[$dao->contribution_id]['financial_type_id'] = $contribution[$dao->contribution_id]['financial_type_id'];
233 }
234 // format soft credit for backward compatibility
235 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
236 }
237 return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao);
238 }
239
240 /**
241 * This function is used to format the soft credit for backward compatibility
242 * as of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
243 * but we still return first soft credit as a part of contribution array
244 * @param $contribution
245 */
246 function _civicrm_api3_format_soft_credit(&$contribution) {
247 if (!empty($contribution['soft_credit'])) {
248 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
249 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
250 }
251 }
252
253 /**
254 * Adjust Metadata for Get action
255 *
256 * The metadata is used for setting defaults, documentation & validation
257 * @param array $params
258 * Array or parameters determined by getfields.
259 */
260 function _civicrm_api3_contribution_get_spec(&$params) {
261 $params['contribution_test']['api.default'] = 0;
262 $params['contribution_test']['title'] = 'Get Test Contributions?';
263 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
264 $params['contact_id'] = $params['contribution_contact_id'];
265 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
266 unset($params['contribution_contact_id']);
267 }
268
269 /**
270 * take the input parameter list as specified in the data model and
271 * convert it into the same format that we use in QF and BAO object
272 *
273 * @param array $params
274 * Associative array of property name/value.
275 * pairs to insert in new contact.
276 * @param array $values
277 * The reformatted properties that we can use internally.
278 * '
279 *
280 * @param bool $create
281 *
282 * @return array|CRM_Error
283 * @access public
284 */
285 function _civicrm_api3_contribute_format_params($params, &$values, $create = FALSE) {
286 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
287 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
288 return array();
289 }
290
291 /**
292 * Adjust Metadata for Transact action
293 *
294 * The metadata is used for setting defaults, documentation & validation
295 * @param array $params
296 * Array or parameters determined by getfields.
297 */
298 function _civicrm_api3_contribution_transact_spec(&$params) {
299 $fields = civicrm_api3('contribution', 'getfields', array('action' => 'create'));
300 $params = array_merge($params, $fields['values']);
301 $params['receive_date']['api.default'] = 'now';
302 }
303
304 /**
305 * Process a transaction and record it against the contact.
306 *
307 * @param array $params
308 * (reference ) input parameters.
309 *
310 * @return array
311 * (reference ) contribution of created or updated record (or a civicrm error)
312 * @static
313 * @access public
314 *
315 */
316 function civicrm_api3_contribution_transact($params) {
317 // Set some params specific to payment processing
318 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
319 $params['amount'] = $params['total_amount'];
320 if (!isset($params['net_amount'])) {
321 $params['net_amount'] = $params['amount'];
322 }
323 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
324 $params['invoiceID'] = $params['invoice_id'];
325 }
326
327 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
328 if (civicrm_error($paymentProcessor)) {
329 return $paymentProcessor;
330 }
331
332 $payment = CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
333 if (civicrm_error($payment)) {
334 return $payment;
335 }
336
337 $transaction = $payment->doDirectPayment($params);
338 if (civicrm_error($transaction)) {
339 return $transaction;
340 }
341
342 // but actually, $payment->doDirectPayment() doesn't return a
343 // CRM_Core_Error by itself
344 if (is_object($transaction) && get_class($transaction) == 'CRM_Core_Error') {
345 $errs = $transaction->getErrors();
346 if (!empty($errs)) {
347 $last_error = array_shift($errs);
348 return CRM_Core_Error::createApiError($last_error['message']);
349 }
350 }
351 $params['payment_instrument_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ? 'Credit Card' : 'Debit Card';
352 return civicrm_api('contribution', 'create', $params);
353 }
354
355 /**
356 * Send a contribution confirmation (receipt or invoice)
357 * The appropriate online template will be used (the existence of related objects
358 * (e.g. memberships ) will affect this selection
359 *
360 * @param array $params
361 * Input parameters.
362 * {@getfields Contribution_sendconfirmation}
363 *
364 * @throws Exception
365 * @return array
366 * Api result array
367 * @static
368 * @access public
369 */
370 function civicrm_api3_contribution_sendconfirmation($params) {
371 $contribution = new CRM_Contribute_BAO_Contribution();
372 $contribution->id = $params['id'];
373 if (! $contribution->find(TRUE)) {
374 throw new Exception('Contribution does not exist');
375 }
376 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
377 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
378 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
379 }
380
381 /**
382 * Adjust Metadata for sendconfirmation action
383 *
384 * The metadata is used for setting defaults, documentation & validation
385 * @param array $params
386 * Array or parameters determined by getfields.
387 */
388 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
389 $params['id'] = array(
390 'api.required' => 1,
391 'title' => 'Contribution ID',
392 );
393 $params['receipt_from_email'] = array(
394 'api.required' => 1,
395 'title' => 'From Email address (string) required until someone provides a patch :-)',
396 );
397 $params['receipt_from_name'] = array(
398 'title' => 'From Name (string)',
399 );
400 $params['cc_receipt'] = array(
401 'title' => 'CC Email address (string)',
402 );
403 $params['bcc_receipt'] = array(
404 'title' => 'BCC Email address (string)',
405 );
406 $params['receipt_text'] = array(
407 'title' => 'Message (string)',
408 );
409 }
410
411 /**
412 * Complete an existing (pending) transaction, updating related entities (participant, membership, pledge etc)
413 * and taking any complete actions from the contribution page (e.g. send receipt)
414 *
415 * @todo - most of this should live in the BAO layer but as we want it to be an addition
416 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
417 *
418 * @param array $params
419 * Input parameters.
420 * {@getfields Contribution_completetransaction}
421 *
422 * @throws API_Exception
423 * @return array
424 * Api result array
425 * @static
426 * @access public
427 */
428 function civicrm_api3_contribution_completetransaction(&$params) {
429
430 $input = $ids = array();
431 $contribution = new CRM_Contribute_BAO_Contribution();
432 $contribution->id = $params['id'];
433 $contribution->find(TRUE);
434 if (!$contribution->id == $params['id']) {
435 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
436 }
437 try {
438 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
439 throw new API_Exception('failed to load related objects');
440 }
441 elseif ($contribution->contribution_status_id == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
442 throw new API_Exception(ts('Contribution already completed'));
443 }
444 $objects = $contribution->_relatedObjects;
445 $objects['contribution'] = &$contribution;
446 $input['component'] = $contribution->_component;
447 $input['is_test'] = $contribution->is_test;
448 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
449 $input['amount'] = $contribution->total_amount;
450 if (isset($params['is_email_receipt'])) {
451 $input['is_email_receipt'] = $params['is_email_receipt'];
452 }
453 // @todo required for base ipn but problematic as api layer handles this
454 $transaction = new CRM_Core_Transaction();
455 $ipn = new CRM_Core_Payment_BaseIPN();
456 $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id));
457 }
458 catch(Exception $e) {
459 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
460 }
461 }
462
463 /**
464 * provide function metadata
465 * @param array $params
466 */
467 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
468 $params['id'] = array(
469 'title' => 'Contribution ID',
470 'type' => CRM_Utils_Type::T_INT,
471 'api.required' => TRUE,
472 );
473 $params['trxn_id'] = array(
474 'title' => 'Transaction ID',
475 'type' => CRM_Utils_Type::T_STRING,
476 );
477 $params['is_email_receipt'] = array(
478 'title' => 'Send email Receipt?',
479 'type' => CRM_Utils_Type::T_BOOLEAN,
480 );
481 }