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