Merge pull request #2266 from yashodha/4.4.CRM-13977
[civicrm-core.git] / api / v3 / Contribution.php
CommitLineData
6a488035 1<?php
6a488035
TO
2
3/*
4 +--------------------------------------------------------------------+
232624b1 5 | CiviCRM version 4.4 |
6a488035
TO
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 * @return array Api result array
46 * @static void
47 * @access public
48 * @example ContributionCreate.php
49 * {@getfields Contribution_create}
50 */
51function civicrm_api3_contribution_create(&$params) {
52 $values = array();
6a488035 53 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
504a78f6 54 $params = array_merge($params, $values);
55
56 //legacy soft credit handling - recommended approach is chaining
502b3d42 57 if(!empty($params['soft_credit_to'])){
504a78f6 58 $params['soft_credit'] = array(array(
502b3d42 59 'contact_id' => $params['soft_credit_to'],
60 'amount' => $params['total_amount']));
61 }
6a488035 62
504a78f6 63 if (CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('contribution_status_id', $params)) {
64 $error = array();
65 //throw error for invalid status change such as setting completed back to pending
66 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
67 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
68 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
69 if (array_key_exists('contribution_status_id', $error)) {
70 throw new API_Exception($error['contribution_status_id']);
71 }
6a488035 72 }
504a78f6 73 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
6a488035 74}
11e09c59
TO
75
76/**
6a488035
TO
77 * Adjust Metadata for Create action
78 *
79 * The metadata is used for setting defaults, documentation & validation
80 * @param array $params array or parameters determined by getfields
81 */
82function _civicrm_api3_contribution_create_spec(&$params) {
83 $params['contact_id']['api.required'] = 1;
84 $params['total_amount']['api.required'] = 1;
53191813 85 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
6a488035
TO
86 $params['payment_processor'] = array(
87 'name' => 'payment_processor',
88 'title' => 'Payment Processor ID',
89 'description' => 'ID of payment processor used for this contribution',
90 // field is called payment processor - not payment processor id but can only be one id so
91 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
92 'api.aliases' => array('payment_processor_id'),
93 );
94 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
95 $params['financial_type_id']['api.required'] = 1;
96 $params['note'] = array(
97 'name' => 'note',
98 'uniqueName' => 'contribution_note',
99 'title' => 'note',
100 'type' => 2,
101 'description' => 'Associated Note in the notes table',
102 );
103 $params['soft_credit_to'] = array(
104 'name' => 'soft_credit_to',
105 'title' => 'Soft Credit contact ID',
106 'type' => 1,
107 'description' => 'ID of Contact to be Soft credited to',
108 'FKClassName' => 'CRM_Contact_DAO_Contact',
109 );
110 // note this is a recommended option but not adding as a default to avoid
111 // creating unecessary changes for the dev
112 $params['skipRecentView'] = array(
113 'name' => 'skipRecentView',
114 'title' => 'Skip adding to recent view',
0900b21e 115 'type' => CRM_Utils_Type::T_BOOLEAN,
6a488035
TO
116 'description' => 'Do not add to recent view (setting this improves performance)',
117 );
118 $params['skipLineItem'] = array(
119 'name' => 'skipLineItem',
120 'title' => 'Skip adding line items',
121 'type' => 1,
122 'api.default' => 0,
123 'description' => 'Do not add line items by default (if you wish to add your own)',
124 );
599c61ac
E
125 $params['batch_id'] = array(
126 'title' => 'Batch',
127 'type' => 1,
128 'description' => 'Batch which relevant transactions should be added to',
129 );
6a488035
TO
130}
131
132/**
133 * Delete a contribution
134 *
135 * @param array $params (reference ) input parameters
136 *
137 * @return boolean true if success, else false
138 * @static void
139 * @access public
140 * {@getfields Contribution_delete}
141 * @example ContributionDelete.php
142 */
143function civicrm_api3_contribution_delete($params) {
144
145 $contributionID = CRM_Utils_Array::value('contribution_id', $params) ? $params['contribution_id'] : $params['id'];
146 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
147 return civicrm_api3_create_success(array($contributionID => 1));
148 }
149 else {
150 return civicrm_api3_create_error('Could not delete contribution');
151 }
152}
11e09c59
TO
153
154/**
6a488035
TO
155 * modify metadata. Legacy support for contribution_id
156 */
157function _civicrm_api3_contribution_delete_spec(&$params) {
158 $params['id']['api.aliases'] = array('contribution_id');
159}
160
161/**
162 * Retrieve a set of contributions, given a set of input params
163 *
164 * @param array $params (reference ) input parameters
165 * @param array $returnProperties Which properties should be included in the
166 * returned Contribution object. If NULL, the default
167 * set of properties will be included.
168 *
169 * @return array (reference ) array of contributions, if error an array with an error id and error message
170 * @static void
171 * @access public
172 * {@getfields Contribution_get}
173 * @example ContributionGet.php
174 */
175function civicrm_api3_contribution_get($params) {
176
177 $options = _civicrm_api3_get_options_from_params($params, TRUE,'contribution','get');
178 $sort = CRM_Utils_Array::value('sort', $options, NULL);
179 $offset = CRM_Utils_Array::value('offset', $options);
180 $rowCount = CRM_Utils_Array::value('limit', $options);
181 $smartGroupCache = CRM_Utils_Array::value('smartGroupCache', $params);
182 $inputParams = CRM_Utils_Array::value('input_params', $options, array());
183 $returnProperties = CRM_Utils_Array::value('return', $options, NULL);
6a488035
TO
184 if (empty($returnProperties)) {
185 $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties(CRM_Contact_BAO_Query::MODE_CONTRIBUTE);
186 }
187
188 $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams);
189 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
190 FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE
191 );
192 list($select, $from, $where, $having) = $query->query();
193
194 $sql = "$select $from $where $having";
195
196 if (!empty($sort)) {
197 $sql .= " ORDER BY $sort ";
198 }
199 $sql .= " LIMIT $offset, $rowCount ";
200 $dao = CRM_Core_DAO::executeQuery($sql);
201
202 $contribution = array();
203 while ($dao->fetch()) {
204 //CRM-8662
76ca3345
KJ
205 $contribution_details = $query->store($dao);
206 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id , TRUE);
207 $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution);
a1c68fd2 208 if(isset($contribution[$dao->contribution_id]['financial_type_id'])){
209 $contribution[$dao->contribution_id]['financial_type_id'] = $contribution[$dao->contribution_id]['financial_type_id'];
210 }
76ca3345
KJ
211 // format soft credit for backward compatibility
212 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
6a488035
TO
213 }
214 return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao);
215}
11e09c59 216
76ca3345
KJ
217/**
218 * This function is used to format the soft credit for backward compatibility
219 * as of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
220 * but we still return first soft credit as a part of contribution array
221 */
222function _civicrm_api3_format_soft_credit(&$contribution) {
223 if (!empty($contribution['soft_credit'])) {
224 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
225 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
226 }
227}
228
11e09c59 229/**
6a488035
TO
230 * Adjust Metadata for Get action
231 *
232 * The metadata is used for setting defaults, documentation & validation
233 * @param array $params array or parameters determined by getfields
234 */
235function _civicrm_api3_contribution_get_spec(&$params) {
236 $params['contribution_test']['api.default'] = 0;
237 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
238 $params['contact_id'] = $params['contribution_contact_id'];
239 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
240 unset($params['contribution_contact_id']);
241}
242
243/**
244 * take the input parameter list as specified in the data model and
245 * convert it into the same format that we use in QF and BAO object
246 *
247 * @param array $params Associative array of property name/value
248 * pairs to insert in new contact.
249 * @param array $values The reformatted properties that we can use internally
250 * '
251 *
252 * @return array|CRM_Error
253 * @access public
254 */
255function _civicrm_api3_contribute_format_params($params, &$values, $create = FALSE) {
256//legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
6a488035 257 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
6a488035
TO
258 return array();
259}
260
16c0ec8d
CW
261/**
262 * Adjust Metadata for Transact action
263 *
264 * The metadata is used for setting defaults, documentation & validation
265 * @param array $params array or parameters determined by getfields
266 */
267function _civicrm_api3_contribution_transact_spec(&$params) {
268 // This function calls create, so should inherit create spec
269 _civicrm_api3_contribution_create_spec($params);
270 $params['receive_date']['api.default'] = 'now';
271}
272
6a488035
TO
273/**
274 * Process a transaction and record it against the contact.
275 *
276 * @param array $params (reference ) input parameters
277 *
278 * @return array (reference ) contribution of created or updated record (or a civicrm error)
279 * @static void
280 * @access public
281 *
282 */
283function civicrm_api3_contribution_transact($params) {
16c0ec8d
CW
284 // Set some params specific to payment processing
285 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
286 $params['amount'] = $params['total_amount'];
6a488035
TO
287 if (!isset($params['net_amount'])) {
288 $params['net_amount'] = $params['amount'];
289 }
6a488035
TO
290 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
291 $params['invoiceID'] = $params['invoice_id'];
292 }
293
16c0ec8d 294 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
6a488035
TO
295 if (civicrm_error($paymentProcessor)) {
296 return $paymentProcessor;
297 }
298
16c0ec8d 299 $payment = CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
6a488035
TO
300 if (civicrm_error($payment)) {
301 return $payment;
302 }
303
304 $transaction = $payment->doDirectPayment($params);
305 if (civicrm_error($transaction)) {
306 return $transaction;
307 }
308
309 // but actually, $payment->doDirectPayment() doesn't return a
310 // CRM_Core_Error by itself
16c0ec8d 311 if (is_object($transaction) && get_class($transaction) == 'CRM_Core_Error') {
6a488035
TO
312 $errs = $transaction->getErrors();
313 if (!empty($errs)) {
314 $last_error = array_shift($errs);
315 return CRM_Core_Error::createApiError($last_error['message']);
316 }
317 }
318
16c0ec8d 319 return civicrm_api('contribution', 'create', $params);
6a488035
TO
320}
321/**
322 * Send a contribution confirmation (receipt or invoice)
323 * The appropriate online template will be used (the existence of related objects
324 * (e.g. memberships ) will affect this selection
325 * @param array $params input parameters
326 * {@getfields Contribution_sendconfirmation}
327 * @return array Api result array
328 * @static void
329 * @access public
330 *
331 */
332function civicrm_api3_contribution_sendconfirmation($params) {
333 $contribution = new CRM_Contribute_BAO_Contribution();
334 $contribution->id = $params['id'];
76ca3345 335 if (! $contribution->find(TRUE)) {
6a488035
TO
336 throw new Exception('Contribution does not exist');
337}
338 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
76ca3345
KJ
339 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
340 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
6a488035
TO
341}
342
11e09c59 343/**
6a0cf2c6 344 * Adjust Metadata for sendconfirmation action
6a488035
TO
345 *
346 * The metadata is used for setting defaults, documentation & validation
347 * @param array $params array or parameters determined by getfields
348 */
349function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
350 $params['id'] = array(
351 'api.required' => 1,
352 'title' => 'Contribution ID'
353 );
354 $params['receipt_from_email'] = array(
355 'api.required' =>1,
6a0cf2c6
CW
356 'title' => 'From Email address (string) required until someone provides a patch :-)',
357 );
358 $params['receipt_from_name'] = array(
359 'title' => 'From Name (string)',
360 );
361 $params['cc_receipt'] = array(
362 'title' => 'CC Email address (string)',
363 );
364 $params['bcc_receipt'] = array(
365 'title' => 'BCC Email address (string)',
366 );
367 $params['receipt_text'] = array(
368 'title' => 'Message (string)',
6a488035
TO
369 );
370}
0efa8efe 371
372/**
373 * Complete an existing (pending) transaction, updating related entities (participant, membership, pledge etc)
374 * and taking any complete actions from the contribution page (e.g. send receipt)
375 *
376 * @todo - most of this should live in the BAO layer but as we want it to be an addition
377 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
378 *
379 * @param array $params input parameters
380 * {@getfields Contribution_completetransaction}
381 * @return array Api result array
382 * @static void
383 * @access public
384 *
385 */
386function civicrm_api3_contribution_completetransaction(&$params) {
387
388 $input = $ids = array();
389 $contribution = new CRM_Contribute_BAO_Contribution();
390 $contribution->id = $params['id'];
391 $contribution->find(TRUE);
392 if(!$contribution->id == $params['id']){
393 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
394 }
395 try {
396 if(!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)){
397 throw new API_Exception('failed to load related objects');
398 }
399 $objects = $contribution->_relatedObjects;
400 $objects['contribution'] = &$contribution;
401 $input['component'] = $contribution->_component;
402 $input['is_test'] = $contribution->is_test;
403 $input['trxn_id']= $contribution->trxn_id;
404 $input['amount'] = $contribution->total_amount;
405 if(isset($params['is_email_receipt'])){
406 $input['is_email_receipt'] = $params['is_email_receipt'];
407 }
408 // @todo required for base ipn but problematic as api layer handles this
409 $transaction = new CRM_Core_Transaction();
410 $ipn = new CRM_Core_Payment_BaseIPN();
411 $ipn->completeTransaction($input, $ids, $objects, $transaction);
412 }
0e37ad72 413 catch(Exception $e) {
0efa8efe 414 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
415 }
416}
417
418function _civicrm_api3_contribution_completetransaction(&$params) {
419
420}