Merge pull request #4958 from pratikshad/code-cleanup-batch-19
[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 */
49 function civicrm_api3_contribution_create(&$params) {
50 $values = array();
51 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
52 $params = array_merge($params, $values);
53
54 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
55 $error = array();
56 //throw error for invalid status change such as setting completed back to pending
57 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
58 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
59 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
60 if (array_key_exists('contribution_status_id', $error)) {
61 throw new API_Exception($error['contribution_status_id']);
62 }
63 }
64
65 _civicrm_api3_contribution_create_legacy_support_45($params);
66
67 // make sure tax calculation is handled via api
68 $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
69
70 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
71 }
72
73 /**
74 * Adjust Metadata for Create action
75 *
76 * The metadata is used for setting defaults, documentation & validation
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 * The main purpose of the API is to provide integrators a level of stability not provided by
148 * the core code or schema - this means we have to provide support for api calls (where possible)
149 * across schema changes.
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 * (reference ) input parameters.
175 *
176 * @return bool
177 * true if success, else false
178 */
179 function civicrm_api3_contribution_delete($params) {
180
181 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
182 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
183 return civicrm_api3_create_success(array($contributionID => 1));
184 }
185 else {
186 return civicrm_api3_create_error('Could not delete contribution');
187 }
188 }
189
190 /**
191 * modify metadata. Legacy support for contribution_id
192 * @param array $params
193 */
194 function _civicrm_api3_contribution_delete_spec(&$params) {
195 $params['id']['api.aliases'] = array('contribution_id');
196 }
197
198 /**
199 * Retrieve a set of contributions, given a set of input params
200 *
201 * @param array $params
202 * (reference ) input parameters.
203 *
204 * @return array
205 * Array of contributions, if error an array with an error id and error message
206 */
207 function civicrm_api3_contribution_get($params) {
208
209 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
210 $entity = 'contribution';
211 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, $entity);
212
213 $contribution = array();
214 while ($dao->fetch()) {
215 //CRM-8662
216 $contribution_details = $query->store($dao);
217 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id, TRUE);
218 $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution);
219 // format soft credit for backward compatibility
220 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
221 }
222 return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao);
223 }
224
225 /**
226 * This function is used to format the soft credit for backward compatibility
227 * as of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
228 * but we still return first soft credit as a part of contribution array
229 * @param $contribution
230 */
231 function _civicrm_api3_format_soft_credit(&$contribution) {
232 if (!empty($contribution['soft_credit'])) {
233 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
234 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
235 }
236 }
237
238 /**
239 * Adjust Metadata for Get action
240 *
241 * The metadata is used for setting defaults, documentation & validation
242 * @param array $params
243 * Array or parameters determined by getfields.
244 */
245 function _civicrm_api3_contribution_get_spec(&$params) {
246 $params['contribution_test']['api.default'] = 0;
247 $params['contribution_test']['title'] = 'Get Test Contributions?';
248 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
249 $params['contact_id'] = $params['contribution_contact_id'];
250 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
251 unset($params['contribution_contact_id']);
252 }
253
254 /**
255 * take the input parameter list as specified in the data model and
256 * convert it into the same format that we use in QF and BAO object
257 *
258 * @param array $params
259 * property name/value pairs to insert in new contact.
260 * @param array $values
261 * The reformatted properties that we can use internally.
262 *
263 * @return array
264 */
265 function _civicrm_api3_contribute_format_params($params, &$values) {
266 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
267 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
268 return array();
269 }
270
271 /**
272 * Adjust Metadata for Transact action
273 *
274 * The metadata is used for setting defaults, documentation & validation
275 * @param array $params
276 * Array or parameters determined by getfields.
277 */
278 function _civicrm_api3_contribution_transact_spec(&$params) {
279 $fields = civicrm_api3('contribution', 'getfields', array('action' => 'create'));
280 $params = array_merge($params, $fields['values']);
281 $params['receive_date']['api.default'] = 'now';
282 }
283
284 /**
285 * Process a transaction and record it against the contact.
286 *
287 * @param array $params
288 * (reference ) input parameters.
289 *
290 * @return array
291 * contribution of created or updated record (or a civicrm error)
292 */
293 function civicrm_api3_contribution_transact($params) {
294 // Set some params specific to payment processing
295 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
296 $params['amount'] = $params['total_amount'];
297 if (!isset($params['net_amount'])) {
298 $params['net_amount'] = $params['amount'];
299 }
300 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
301 $params['invoiceID'] = $params['invoice_id'];
302 }
303
304 // Some payment processors expect a unique invoice_id - generate one if not supplied
305 $params['invoice_id'] = CRM_Utils_Array::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
306
307 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
308 if (civicrm_error($paymentProcessor)) {
309 return $paymentProcessor;
310 }
311
312 $payment = CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
313 if (civicrm_error($payment)) {
314 return $payment;
315 }
316
317 $transaction = $payment->doDirectPayment($params);
318 if (civicrm_error($transaction)) {
319 return $transaction;
320 }
321
322 // but actually, $payment->doDirectPayment() doesn't return a
323 // CRM_Core_Error by itself
324 if (is_object($transaction) && get_class($transaction) == 'CRM_Core_Error') {
325 $errs = $transaction->getErrors();
326 if (!empty($errs)) {
327 $last_error = array_shift($errs);
328 return CRM_Core_Error::createApiError($last_error['message']);
329 }
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 * The appropriate online template will be used (the existence of related objects
338 * (e.g. memberships ) will affect this selection
339 *
340 * @param array $params
341 * Input parameters.
342 *
343 * @throws Exception
344 * Api result array.
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 * @param array $params
362 * Array or parameters determined by getfields.
363 */
364 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
365 $params['id'] = array(
366 'api.required' => 1,
367 'title' => 'Contribution ID',
368 );
369 $params['receipt_from_email'] = array(
370 'api.required' => 1,
371 'title' => 'From Email address (string) required until someone provides a patch :-)',
372 );
373 $params['receipt_from_name'] = array(
374 'title' => 'From Name (string)',
375 );
376 $params['cc_receipt'] = array(
377 'title' => 'CC Email address (string)',
378 );
379 $params['bcc_receipt'] = array(
380 'title' => 'BCC Email address (string)',
381 );
382 $params['receipt_text'] = array(
383 'title' => 'Message (string)',
384 );
385 }
386
387 /**
388 * Complete an existing (pending) transaction, updating related entities (participant, membership, pledge etc)
389 * and taking any complete actions from the contribution page (e.g. send receipt)
390 *
391 * @todo - most of this should live in the BAO layer but as we want it to be an addition
392 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
393 *
394 * @param array $params
395 * Input parameters.
396 * {@getfields Contribution_completetransaction}
397 *
398 * @throws API_Exception
399 * Api result array.
400 */
401 function civicrm_api3_contribution_completetransaction(&$params) {
402
403 $input = $ids = array();
404 $contribution = new CRM_Contribute_BAO_Contribution();
405 $contribution->id = $params['id'];
406 $contribution->find(TRUE);
407 if (!$contribution->id == $params['id']) {
408 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
409 }
410 try {
411 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
412 throw new API_Exception('failed to load related objects');
413 }
414 elseif ($contribution->contribution_status_id == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
415 throw new API_Exception(ts('Contribution already completed'));
416 }
417 $objects = $contribution->_relatedObjects;
418 $objects['contribution'] = &$contribution;
419 $input['component'] = $contribution->_component;
420 $input['is_test'] = $contribution->is_test;
421 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
422 $input['amount'] = $contribution->total_amount;
423 if (isset($params['is_email_receipt'])) {
424 $input['is_email_receipt'] = $params['is_email_receipt'];
425 }
426 // @todo required for base ipn but problematic as api layer handles this
427 $transaction = new CRM_Core_Transaction();
428 $ipn = new CRM_Core_Payment_BaseIPN();
429 $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id));
430 }
431 catch(Exception $e) {
432 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
433 }
434 }
435
436 /**
437 * provide function metadata
438 * @param array $params
439 */
440 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
441 $params['id'] = array(
442 'title' => 'Contribution ID',
443 'type' => CRM_Utils_Type::T_INT,
444 'api.required' => TRUE,
445 );
446 $params['trxn_id'] = array(
447 'title' => 'Transaction ID',
448 'type' => CRM_Utils_Type::T_STRING,
449 );
450 $params['is_email_receipt'] = array(
451 'title' => 'Send email Receipt?',
452 'type' => CRM_Utils_Type::T_BOOLEAN,
453 );
454 }