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