Merge pull request #727 from dlobo/MiscFixes
[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
205 // format soft credit for backward compatibility
206 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
207 }
208 return civicrm_api3_create_success($contribution, $params, 'contribution', 'get', $dao);
209 }
210
211 /**
212 * This function is used to format the soft credit for backward compatibility
213 * as of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
214 * but we still return first soft credit as a part of contribution array
215 */
216 function _civicrm_api3_format_soft_credit(&$contribution) {
217 if (!empty($contribution['soft_credit'])) {
218 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
219 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
220 }
221 }
222
223 /**
224 * Adjust Metadata for Get action
225 *
226 * The metadata is used for setting defaults, documentation & validation
227 * @param array $params array or parameters determined by getfields
228 */
229 function _civicrm_api3_contribution_get_spec(&$params) {
230 $params['contribution_test']['api.default'] = 0;
231 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
232 $params['contact_id'] = $params['contribution_contact_id'];
233 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
234 unset($params['contribution_contact_id']);
235 }
236
237 /**
238 * take the input parameter list as specified in the data model and
239 * convert it into the same format that we use in QF and BAO object
240 *
241 * @param array $params Associative array of property name/value
242 * pairs to insert in new contact.
243 * @param array $values The reformatted properties that we can use internally
244 * '
245 *
246 * @return array|CRM_Error
247 * @access public
248 */
249 function _civicrm_api3_contribute_format_params($params, &$values, $create = FALSE) {
250 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
251 require_once 'api/v3/utils.php';
252 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
253
254 foreach ($params as $key => $value) {
255 // ignore empty values or empty arrays etc
256 if (CRM_Utils_System::isNull($value)) {
257 continue;
258 }
259 // note that this is legacy handling - these should be handled at the api layer
260 switch ($key) {
261 case 'financial_type' :// should be dealt with either api pseudoconstant in validate_integer fn
262 $contributionTypeId = CRM_Utils_Array::key ( ucfirst ( $value ), CRM_Contribute_PseudoConstant::financialType() );
263 if ($contributionTypeId) {
264 if (CRM_Utils_Array::value('financial_type_id', $values) && $contributionTypeId != $values['financial_type_id']) {
265 throw new Exception("Mismatched Financial Type and Financial Type Id");
266 }
267 $values ['financial_type_id'] = $contributionTypeId;
268 }
269 else {
270 throw new Exception("Invalid Financial Type");
271 }
272 break;
273
274 case 'soft_credit_to':// should be dealt with by validate integer
275 if (!CRM_Utils_Rule::integer($value)) {
276 return civicrm_api3_create_error("$key not a valid Id: $value");
277 }
278 $values['soft_credit_to'] = $value;
279 break;
280
281 default:
282 break;
283 }
284 }
285
286 return array();
287 }
288
289 /**
290 * Process a transaction and record it against the contact.
291 *
292 * @param array $params (reference ) input parameters
293 *
294 * @return array (reference ) contribution of created or updated record (or a civicrm error)
295 * @static void
296 * @access public
297 *
298 */
299 function civicrm_api3_contribution_transact($params) {
300 $required = array('amount');
301 foreach ($required as $key) {
302 if (!isset($params[$key])) {
303 return civicrm_api3_create_error("Missing parameter $key: civicrm_contribute_transact() requires a parameter '$key'.");
304 }
305 }
306
307 // allow people to omit some values for convenience
308 // 'payment_processor_id' => NULL /* we could retrieve the default processor here, but only if it's missing to avoid an extra lookup */
309 $defaults = array(
310 'payment_processor_mode' => 'live',
311 );
312 $params = array_merge($defaults, $params);
313
314 // clean up / adjust some values which
315 if (!isset($params['total_amount'])) {
316 $params['total_amount'] = $params['amount'];
317 }
318 if (!isset($params['net_amount'])) {
319 $params['net_amount'] = $params['amount'];
320 }
321 if (!isset($params['receive_date'])) {
322 $params['receive_date'] = date('Y-m-d');
323 }
324 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
325 $params['invoiceID'] = $params['invoice_id'];
326 }
327
328 require_once 'CRM/Financial/BAO/PaymentProcessor.php';
329 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor_id'], $params['payment_processor_mode']);
330 if (civicrm_error($paymentProcessor)) {
331 return $paymentProcessor;
332 }
333
334 require_once 'CRM/Core/Payment.php';
335 $payment = &CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
336 if (civicrm_error($payment)) {
337 return $payment;
338 }
339
340 $transaction = $payment->doDirectPayment($params);
341 if (civicrm_error($transaction)) {
342 return $transaction;
343 }
344
345 // but actually, $payment->doDirectPayment() doesn't return a
346 // CRM_Core_Error by itself
347 if (get_class($transaction) == 'CRM_Core_Error') {
348 $errs = $transaction->getErrors();
349 if (!empty($errs)) {
350 $last_error = array_shift($errs);
351 return CRM_Core_Error::createApiError($last_error['message']);
352 }
353 }
354
355 $contribution = civicrm_api('contribution', 'create', $params);
356 return $contribution['values'];
357 }
358 /**
359 * Send a contribution confirmation (receipt or invoice)
360 * The appropriate online template will be used (the existence of related objects
361 * (e.g. memberships ) will affect this selection
362 * @param array $params input parameters
363 * {@getfields Contribution_sendconfirmation}
364 * @return array Api result array
365 * @static void
366 * @access public
367 *
368 */
369 function civicrm_api3_contribution_sendconfirmation($params) {
370 $contribution = new CRM_Contribute_BAO_Contribution();
371 $contribution->id = $params['id'];
372 if (! $contribution->find(TRUE)) {
373 throw new Exception('Contribution does not exist');
374 }
375 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
376 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
377 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
378 }
379
380 /**
381 * Adjust Metadata for Create action
382 *
383 * The metadata is used for setting defaults, documentation & validation
384 * @param array $params array or parameters determined by getfields
385 */
386 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
387 $params['id'] = array(
388 'api.required' => 1,
389 'title' => 'Contribution ID'
390 );
391 $params['receipt_from_email'] = array(
392 'api.required' =>1,
393 'title' => 'From Email (required until someone provides a patch :-)',
394
395 );
396 }