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