Merge pull request #999 from lcdservices/master
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.3 |
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
54 _civicrm_api3_contribute_format_params($params, $values);
55
56 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
57 $values["contact_id"] = CRM_Utils_Array::value('contact_id', $params);
58 $values["source"] = CRM_Utils_Array::value('source', $params);
59 //legacy soft credit handling
60 if(!empty($params['soft_credit_to'])){
61 $values['soft_credit'] = array(array(
62 'contact_id' => $params['soft_credit_to'],
63 'amount' => $params['total_amount']));
64 }
65 $ids = array();
66 if (CRM_Utils_Array::value('id', $params)) {
67 $ids['contribution'] = $params['id'];
68 // CRM-12498
69 if (CRM_Utils_Array::value('contribution_status_id', $params)) {
70 $error = array();
71 //throw error for invalid status change
72 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
73 if (array_key_exists('contribution_status_id', $error)) {
74 return civicrm_api3_create_error($error['contribution_status_id']);
75 }
76 }
77 }
78 $contribution = CRM_Contribute_BAO_Contribution::create($values, $ids);
79
80 if (is_a($contribution, 'CRM_Core_Error')) {
81 return civicrm_api3_create_error($contribution->_errors[0]['message']);
82 }
83 _civicrm_api3_object_to_array($contribution, $contributeArray[$contribution->id]);
84
85 return civicrm_api3_create_success($contributeArray, $params, 'contribution', 'create', $contribution);
86 }
87
88 /**
89 * Adjust Metadata for Create action
90 *
91 * The metadata is used for setting defaults, documentation & validation
92 * @param array $params array or parameters determined by getfields
93 */
94 function _civicrm_api3_contribution_create_spec(&$params) {
95 $params['contact_id']['api.required'] = 1;
96 $params['total_amount']['api.required'] = 1;
97 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
98 $params['payment_processor'] = array(
99 'name' => 'payment_processor',
100 'title' => 'Payment Processor ID',
101 'description' => 'ID of payment processor used for this contribution',
102 // field is called payment processor - not payment processor id but can only be one id so
103 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
104 'api.aliases' => array('payment_processor_id'),
105 );
106 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
107 $params['financial_type_id']['api.required'] = 1;
108 $params['note'] = array(
109 'name' => 'note',
110 'uniqueName' => 'contribution_note',
111 'title' => 'note',
112 'type' => 2,
113 'description' => 'Associated Note in the notes table',
114 );
115 $params['soft_credit_to'] = array(
116 'name' => 'soft_credit_to',
117 'title' => 'Soft Credit contact ID',
118 'type' => 1,
119 'description' => 'ID of Contact to be Soft credited to',
120 'FKClassName' => 'CRM_Contact_DAO_Contact',
121 );
122 // note this is a recommended option but not adding as a default to avoid
123 // creating unecessary changes for the dev
124 $params['skipRecentView'] = array(
125 'name' => 'skipRecentView',
126 'title' => 'Skip adding to recent view',
127 'type' => 1,
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 }
138
139 /**
140 * Delete a contribution
141 *
142 * @param array $params (reference ) input parameters
143 *
144 * @return boolean true if success, else false
145 * @static void
146 * @access public
147 * {@getfields Contribution_delete}
148 * @example ContributionDelete.php
149 */
150 function civicrm_api3_contribution_delete($params) {
151
152 $contributionID = CRM_Utils_Array::value('contribution_id', $params) ? $params['contribution_id'] : $params['id'];
153 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
154 return civicrm_api3_create_success(array($contributionID => 1));
155 }
156 else {
157 return civicrm_api3_create_error('Could not delete contribution');
158 }
159 }
160
161 /**
162 * modify metadata. Legacy support for contribution_id
163 */
164 function _civicrm_api3_contribution_delete_spec(&$params) {
165 $params['id']['api.aliases'] = array('contribution_id');
166 }
167
168 /**
169 * Retrieve a set of contributions, given a set of input params
170 *
171 * @param array $params (reference ) input parameters
172 * @param array $returnProperties Which properties should be included in the
173 * returned Contribution object. If NULL, the default
174 * set of properties will be included.
175 *
176 * @return array (reference ) array of contributions, if error an array with an error id and error message
177 * @static void
178 * @access public
179 * {@getfields Contribution_get}
180 * @example ContributionGet.php
181 */
182 function civicrm_api3_contribution_get($params) {
183
184 $options = _civicrm_api3_get_options_from_params($params, TRUE,'contribution','get');
185 $sort = CRM_Utils_Array::value('sort', $options, NULL);
186 $offset = CRM_Utils_Array::value('offset', $options);
187 $rowCount = CRM_Utils_Array::value('limit', $options);
188 $smartGroupCache = CRM_Utils_Array::value('smartGroupCache', $params);
189 $inputParams = CRM_Utils_Array::value('input_params', $options, array());
190 $returnProperties = CRM_Utils_Array::value('return', $options, NULL);
191 if (empty($returnProperties)) {
192 $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties(CRM_Contact_BAO_Query::MODE_CONTRIBUTE);
193 }
194
195 $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams);
196 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
197 FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE
198 );
199 list($select, $from, $where, $having) = $query->query();
200
201 $sql = "$select $from $where $having";
202
203 if (!empty($sort)) {
204 $sql .= " ORDER BY $sort ";
205 }
206 $sql .= " LIMIT $offset, $rowCount ";
207 $dao = CRM_Core_DAO::executeQuery($sql);
208
209 $contribution = array();
210 while ($dao->fetch()) {
211 //CRM-8662
212 $contribution_details = $query->store($dao);
213 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id , TRUE);
214 $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution);
215 if(isset($contribution[$dao->contribution_id]['financial_type_id'])){
216 $contribution[$dao->contribution_id]['financial_type_id'] = $contribution[$dao->contribution_id]['financial_type_id'];
217 }
218 // format soft credit for backward compatibility
219 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
220 }
221 return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao);
222 }
223
224 /**
225 * This function is used to format the soft credit for backward compatibility
226 * as of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
227 * but we still return first soft credit as a part of contribution array
228 */
229 function _civicrm_api3_format_soft_credit(&$contribution) {
230 if (!empty($contribution['soft_credit'])) {
231 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
232 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
233 }
234 }
235
236 /**
237 * Adjust Metadata for Get action
238 *
239 * The metadata is used for setting defaults, documentation & validation
240 * @param array $params array or parameters determined by getfields
241 */
242 function _civicrm_api3_contribution_get_spec(&$params) {
243 $params['contribution_test']['api.default'] = 0;
244 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
245 $params['contact_id'] = $params['contribution_contact_id'];
246 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
247 unset($params['contribution_contact_id']);
248 }
249
250 /**
251 * take the input parameter list as specified in the data model and
252 * convert it into the same format that we use in QF and BAO object
253 *
254 * @param array $params Associative array of property name/value
255 * pairs to insert in new contact.
256 * @param array $values The reformatted properties that we can use internally
257 * '
258 *
259 * @return array|CRM_Error
260 * @access public
261 */
262 function _civicrm_api3_contribute_format_params($params, &$values, $create = FALSE) {
263 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
264 require_once 'api/v3/utils.php';
265 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
266
267 foreach ($params as $key => $value) {
268 // ignore empty values or empty arrays etc
269 if (CRM_Utils_System::isNull($value)) {
270 continue;
271 }
272 // note that this is legacy handling - these should be handled at the api layer
273 switch ($key) {
274 case 'financial_type' :// should be dealt with either api pseudoconstant in validate_integer fn
275 $contributionTypeId = CRM_Utils_Array::key ( ucfirst ( $value ), CRM_Contribute_PseudoConstant::financialType() );
276 if ($contributionTypeId) {
277 if (CRM_Utils_Array::value('financial_type_id', $values) && $contributionTypeId != $values['financial_type_id']) {
278 throw new Exception("Mismatched Financial Type and Financial Type Id");
279 }
280 $values ['financial_type_id'] = $contributionTypeId;
281 }
282 else {
283 throw new Exception("Invalid Financial Type");
284 }
285 break;
286
287 default:
288 break;
289 }
290 }
291
292 return array();
293 }
294
295 /**
296 * Process a transaction and record it against the contact.
297 *
298 * @param array $params (reference ) input parameters
299 *
300 * @return array (reference ) contribution of created or updated record (or a civicrm error)
301 * @static void
302 * @access public
303 *
304 */
305 function civicrm_api3_contribution_transact($params) {
306 $required = array('amount');
307 foreach ($required as $key) {
308 if (!isset($params[$key])) {
309 return civicrm_api3_create_error("Missing parameter $key: civicrm_contribute_transact() requires a parameter '$key'.");
310 }
311 }
312
313 // allow people to omit some values for convenience
314 // 'payment_processor_id' => NULL /* we could retrieve the default processor here, but only if it's missing to avoid an extra lookup */
315 $defaults = array(
316 'payment_processor_mode' => 'live',
317 );
318 $params = array_merge($defaults, $params);
319
320 // clean up / adjust some values which
321 if (!isset($params['total_amount'])) {
322 $params['total_amount'] = $params['amount'];
323 }
324 if (!isset($params['net_amount'])) {
325 $params['net_amount'] = $params['amount'];
326 }
327 if (!isset($params['receive_date'])) {
328 $params['receive_date'] = date('Y-m-d');
329 }
330 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
331 $params['invoiceID'] = $params['invoice_id'];
332 }
333
334 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor_id'], $params['payment_processor_mode']);
335 if (civicrm_error($paymentProcessor)) {
336 return $paymentProcessor;
337 }
338
339 $payment = &CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
340 if (civicrm_error($payment)) {
341 return $payment;
342 }
343
344 $transaction = $payment->doDirectPayment($params);
345 if (civicrm_error($transaction)) {
346 return $transaction;
347 }
348
349 // but actually, $payment->doDirectPayment() doesn't return a
350 // CRM_Core_Error by itself
351 if (get_class($transaction) == 'CRM_Core_Error') {
352 $errs = $transaction->getErrors();
353 if (!empty($errs)) {
354 $last_error = array_shift($errs);
355 return CRM_Core_Error::createApiError($last_error['message']);
356 }
357 }
358
359 $contribution = civicrm_api('contribution', 'create', $params);
360 return $contribution['values'];
361 }
362 /**
363 * Send a contribution confirmation (receipt or invoice)
364 * The appropriate online template will be used (the existence of related objects
365 * (e.g. memberships ) will affect this selection
366 * @param array $params input parameters
367 * {@getfields Contribution_sendconfirmation}
368 * @return array Api result array
369 * @static void
370 * @access public
371 *
372 */
373 function civicrm_api3_contribution_sendconfirmation($params) {
374 $contribution = new CRM_Contribute_BAO_Contribution();
375 $contribution->id = $params['id'];
376 if (! $contribution->find(TRUE)) {
377 throw new Exception('Contribution does not exist');
378 }
379 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
380 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
381 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
382 }
383
384 /**
385 * Adjust Metadata for Create action
386 *
387 * The metadata is used for setting defaults, documentation & validation
388 * @param array $params array or parameters determined by getfields
389 */
390 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
391 $params['id'] = array(
392 'api.required' => 1,
393 'title' => 'Contribution ID'
394 );
395 $params['receipt_from_email'] = array(
396 'api.required' =>1,
397 'title' => 'From Email (required until someone provides a patch :-)',
398
399 );
400 }