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