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