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