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