CIVI-28 Handled permission for create contribution API
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * This api exposes CiviCRM Contribution records.
30 *
31 * @package CiviCRM_APIv3
32 */
33
34 /**
35 * Add or update a Contribution.
36 *
37 * @param array $params
38 * Input parameters.
39 *
40 * @throws API_Exception
41 * @return array
42 * Api result array
43 */
44 function civicrm_api3_contribution_create(&$params) {
45 $values = array();
46 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
47 $params = array_merge($params, $values);
48
49 if (empty($params['id'])) {
50 $op = 'add';
51 }
52 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types, $op);
53 if (!in_array($params['financial_type_id'], array_keys($types))) {
54 return civicrm_api3_create_error('You do not have permission to create this contribution');
55 }
56
57 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
58 $error = array();
59 //throw error for invalid status change such as setting completed back to pending
60 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
61 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
62 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
63 if (array_key_exists('contribution_status_id', $error)) {
64 throw new API_Exception($error['contribution_status_id']);
65 }
66 }
67 if (!empty($params['id']) && !empty($params['financial_type_id'])) {
68 $error = array();
69 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
70 if (array_key_exists('financial_type_id', $error)) {
71 throw new API_Exception($error['financial_type_id']);
72 }
73 }
74 _civicrm_api3_contribution_create_legacy_support_45($params);
75
76 // Make sure tax calculation is handled via api.
77 $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
78
79 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
80 }
81
82 /**
83 * Adjust Metadata for Create action.
84 *
85 * The metadata is used for setting defaults, documentation & validation.
86 *
87 * @param array $params
88 * Array of parameters determined by getfields.
89 */
90 function _civicrm_api3_contribution_create_spec(&$params) {
91 $params['contact_id']['api.required'] = 1;
92 $params['total_amount']['api.required'] = 1;
93 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
94 $params['receive_date']['api.default'] = 'now';
95 $params['payment_processor'] = array(
96 'name' => 'payment_processor',
97 'title' => 'Payment Processor ID',
98 'description' => 'ID of payment processor used for this contribution',
99 // field is called payment processor - not payment processor id but can only be one id so
100 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
101 'api.aliases' => array('payment_processor_id'),
102 'type' => CRM_Utils_Type::T_INT,
103 );
104 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
105 $params['financial_type_id']['api.required'] = 1;
106 $params['note'] = array(
107 'name' => 'note',
108 'uniqueName' => 'contribution_note',
109 'title' => 'note',
110 'type' => 2,
111 'description' => 'Associated Note in the notes table',
112 );
113 $params['soft_credit_to'] = array(
114 'name' => 'soft_credit_to',
115 'title' => 'Soft Credit contact ID (legacy)',
116 'type' => 1,
117 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
118 'FKClassName' => 'CRM_Contact_DAO_Contact',
119 );
120 $params['honor_contact_id'] = array(
121 'name' => 'honor_contact_id',
122 'title' => 'Honoree contact ID (legacy)',
123 'type' => 1,
124 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
125 'FKClassName' => 'CRM_Contact_DAO_Contact',
126 );
127 $params['honor_type_id'] = array(
128 'name' => 'honor_type_id',
129 'title' => 'Honoree Type (legacy)',
130 'type' => 1,
131 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
132 'pseudoconstant' => TRUE,
133 );
134 // note this is a recommended option but not adding as a default to avoid
135 // creating unnecessary changes for the dev
136 $params['skipRecentView'] = array(
137 'name' => 'skipRecentView',
138 'title' => 'Skip adding to recent view',
139 'type' => CRM_Utils_Type::T_BOOLEAN,
140 'description' => 'Do not add to recent view (setting this improves performance)',
141 );
142 $params['skipLineItem'] = array(
143 'name' => 'skipLineItem',
144 'title' => 'Skip adding line items',
145 'type' => CRM_Utils_Type::T_BOOLEAN,
146 'api.default' => 0,
147 'description' => 'Do not add line items by default (if you wish to add your own)',
148 );
149 $params['batch_id'] = array(
150 'title' => 'Batch',
151 'type' => 1,
152 'description' => 'Batch which relevant transactions should be added to',
153 );
154 }
155
156 /**
157 * Support for schema changes made in 4.5.
158 *
159 * The main purpose of the API is to provide integrators a level of stability not provided by
160 * the core code or schema - this means we have to provide support for api calls (where possible)
161 * across schema changes.
162 *
163 * @param array $params
164 */
165 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
166 //legacy soft credit handling - recommended approach is chaining
167 if (!empty($params['soft_credit_to'])) {
168 $params['soft_credit'][] = array(
169 'contact_id' => $params['soft_credit_to'],
170 'amount' => $params['total_amount'],
171 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
172 );
173 }
174 if (!empty($params['honor_contact_id'])) {
175 $params['soft_credit'][] = array(
176 'contact_id' => $params['honor_contact_id'],
177 'amount' => $params['total_amount'],
178 'soft_credit_type_id' => CRM_Utils_Array::value('honor_type_id', $params, CRM_Core_OptionGroup::getValue('soft_credit_type', 'in_honor_of', 'name')),
179 );
180 }
181 }
182
183 /**
184 * Delete a Contribution.
185 *
186 * @param array $params
187 * Input parameters.
188 *
189 * @return array
190 */
191 function civicrm_api3_contribution_delete($params) {
192
193 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
194 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
195 return civicrm_api3_create_success(array($contributionID => 1));
196 }
197 else {
198 return civicrm_api3_create_error('Could not delete contribution');
199 }
200 }
201
202 /**
203 * Modify metadata for delete action.
204 *
205 * Legacy support for contribution_id.
206 *
207 * @param array $params
208 */
209 function _civicrm_api3_contribution_delete_spec(&$params) {
210 $params['id']['api.aliases'] = array('contribution_id');
211 }
212
213 /**
214 * Retrieve a set of contributions.
215 *
216 * @param array $params
217 * Input parameters.
218 *
219 * @return array
220 * Array of contributions, if error an array with an error id and error message
221 */
222 function civicrm_api3_contribution_get($params) {
223
224 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
225 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Contribution');
226
227 $contribution = array();
228 while ($dao->fetch()) {
229 //CRM-8662
230 $contribution_details = $query->store($dao);
231 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id, TRUE);
232 $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution);
233 // format soft credit for backward compatibility
234 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
235 }
236 return civicrm_api3_create_success($contribution, $params, 'Contribution', 'get', $dao);
237 }
238
239 /**
240 * This function is used to format the soft credit for backward compatibility.
241 *
242 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
243 * but we still return first soft credit as a part of contribution array
244 *
245 * @param $contribution
246 */
247 function _civicrm_api3_format_soft_credit(&$contribution) {
248 if (!empty($contribution['soft_credit'])) {
249 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
250 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
251 }
252 }
253
254 /**
255 * Adjust Metadata for Get action.
256 *
257 * The metadata is used for setting defaults, documentation & validation.
258 *
259 * @param array $params
260 * Array of parameters determined by getfields.
261 */
262 function _civicrm_api3_contribution_get_spec(&$params) {
263 $params['contribution_test'] = array(
264 'api.default' => 0,
265 'type' => CRM_Utils_Type::T_BOOLEAN,
266 'title' => 'Get Test Contributions?',
267 'api.aliases' => array('is_test'),
268 );
269
270 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
271 $params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
272 $params['contact_id'] = $params['contribution_contact_id'];
273 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
274 unset($params['contribution_contact_id']);
275 }
276
277 /**
278 * Legacy handling for contribution parameters.
279 *
280 * Take the input parameter list as specified in the data model and
281 * convert it into the same format that we use in QF and BAO object.
282 *
283 * @param array $params
284 * property name/value pairs to insert in new contact.
285 * @param array $values
286 * The reformatted properties that we can use internally.
287 *
288 * @return array
289 */
290 function _civicrm_api3_contribute_format_params($params, &$values) {
291 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
292 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
293 return array();
294 }
295
296 /**
297 * Adjust Metadata for Transact action.
298 *
299 * The metadata is used for setting defaults, documentation & validation.
300 *
301 * @param array $params
302 * Array of parameters determined by getfields.
303 */
304 function _civicrm_api3_contribution_transact_spec(&$params) {
305 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
306 $params = array_merge($params, $fields['values']);
307 $params['receive_date']['api.default'] = 'now';
308 }
309
310 /**
311 * Process a transaction and record it against the contact.
312 *
313 * @param array $params
314 * Input parameters.
315 *
316 * @return array
317 * contribution of created or updated record (or a civicrm error)
318 */
319 function civicrm_api3_contribution_transact($params) {
320 // Set some params specific to payment processing
321 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
322 // 'is_error' set
323 // also trxn_id is not saved.
324 // but since there is no test it's not desirable to jump in & make the obvious changes.
325 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
326 $params['amount'] = $params['total_amount'];
327 if (!isset($params['net_amount'])) {
328 $params['net_amount'] = $params['amount'];
329 }
330 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
331 $params['invoiceID'] = $params['invoice_id'];
332 }
333
334 // Some payment processors expect a unique invoice_id - generate one if not supplied
335 $params['invoice_id'] = CRM_Utils_Array::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
336
337 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
338 $paymentProcessor['object']->doPayment($params);
339
340 $params['payment_instrument_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ? 'Credit Card' : 'Debit Card';
341 return civicrm_api('Contribution', 'create', $params);
342 }
343
344 /**
345 * Send a contribution confirmation (receipt or invoice).
346 *
347 * The appropriate online template will be used (the existence of related objects
348 * (e.g. memberships ) will affect this selection
349 *
350 * @param array $params
351 * Input parameters.
352 *
353 * @throws Exception
354 */
355 function civicrm_api3_contribution_sendconfirmation($params) {
356 $contribution = new CRM_Contribute_BAO_Contribution();
357 $contribution->id = $params['id'];
358 if (!$contribution->find(TRUE)) {
359 throw new Exception('Contribution does not exist');
360 }
361 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
362 $contribution->loadRelatedObjects($input, $ids, TRUE);
363 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
364 }
365
366 /**
367 * Adjust Metadata for sendconfirmation action.
368 *
369 * The metadata is used for setting defaults, documentation & validation.
370 *
371 * @param array $params
372 * Array of parameters determined by getfields.
373 */
374 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
375 $params['id'] = array(
376 'api.required' => 1,
377 'title' => 'Contribution ID',
378 'type' => CRM_Utils_Type::T_INT,
379 );
380 $params['receipt_from_email'] = array(
381 'api.required' => 1,
382 'title' => 'From Email address (string) required until someone provides a patch :-)',
383 'type' => CRM_Utils_Type::T_STRING,
384 );
385 $params['receipt_from_name'] = array(
386 'title' => 'From Name (string)',
387 'type' => CRM_Utils_Type::T_STRING,
388 );
389 $params['cc_receipt'] = array(
390 'title' => 'CC Email address (string)',
391 'type' => CRM_Utils_Type::T_STRING,
392 );
393 $params['bcc_receipt'] = array(
394 'title' => 'BCC Email address (string)',
395 'type' => CRM_Utils_Type::T_STRING,
396 );
397 $params['receipt_text'] = array(
398 'title' => 'Message (string)',
399 'type' => CRM_Utils_Type::T_STRING,
400 );
401 }
402
403 /**
404 * Complete an existing (pending) transaction.
405 *
406 * This will update related entities (participant, membership, pledge etc)
407 * and take any complete actions from the contribution page (e.g. send receipt).
408 *
409 * @todo - most of this should live in the BAO layer but as we want it to be an addition
410 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
411 *
412 * @param array $params
413 * Input parameters.
414 *
415 * @throws API_Exception
416 * Api result array.
417 */
418 function civicrm_api3_contribution_completetransaction(&$params) {
419
420 $input = $ids = array();
421 if (isset($params['payment_processor_id'])) {
422 $input['payment_processor_id'] = $params['payment_processor_id'];
423 }
424 $contribution = new CRM_Contribute_BAO_Contribution();
425 $contribution->id = $params['id'];
426 $contribution->find(TRUE);
427 if (!$contribution->id == $params['id']) {
428 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
429 }
430
431 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
432 throw new API_Exception('failed to load related objects');
433 }
434 elseif ($contribution->contribution_status_id == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
435 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
436 }
437 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
438 if (!empty($params['fee_amount'])) {
439 $input['fee_amount'] = $params['fee_amount'];
440 }
441 $params = _ipn_process_transaction($params, $contribution, $input, $ids);
442
443 }
444
445 /**
446 * Provide function metadata.
447 *
448 * @param array $params
449 */
450 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
451 $params['id'] = array(
452 'title' => 'Contribution ID',
453 'type' => CRM_Utils_Type::T_INT,
454 'api.required' => TRUE,
455 );
456 $params['trxn_id'] = array(
457 'title' => 'Transaction ID',
458 'type' => CRM_Utils_Type::T_STRING,
459 );
460 $params['is_email_receipt'] = array(
461 'title' => 'Send email Receipt?',
462 'type' => CRM_Utils_Type::T_BOOLEAN,
463 );
464 $params['receipt_from_email'] = array(
465 'title' => 'Email to send receipt from.',
466 'description' => 'If not provided this will default to being based on domain mail or contribution page',
467 'type' => CRM_Utils_Type::T_EMAIL,
468 );
469 $params['receipt_from_name'] = array(
470 'title' => 'Name to send receipt from',
471 'description' => '. If not provided this will default to domain mail or contribution page',
472 'type' => CRM_Utils_Type::T_STRING,
473 );
474 $params['payment_processor_id'] = array(
475 'title' => 'Payment processor ID',
476 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
477 'type' => CRM_Utils_Type::T_INT,
478 );
479 $params['fee_amount'] = array(
480 'title' => 'Fee charged on transaction',
481 'description' => 'If a fee has been charged then the amount',
482 'type' => CRM_Utils_Type::T_FLOAT,
483 );
484 $params['trxn_date'] = array(
485 'title' => 'Transaction Date',
486 'description' => 'Date this transaction occurred',
487 'type' => CRM_Utils_Type::T_DATE,
488 );
489 }
490
491 /**
492 * Complete an existing (pending) transaction.
493 *
494 * This will update related entities (participant, membership, pledge etc)
495 * and take any complete actions from the contribution page (e.g. send receipt).
496 *
497 * @todo - most of this should live in the BAO layer but as we want it to be an addition
498 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
499 *
500 * @param array $params
501 * Input parameters.
502 *
503 * @throws API_Exception
504 * Api result array.
505 */
506 function civicrm_api3_contribution_repeattransaction(&$params) {
507 $input = $ids = array();
508 $contribution = new CRM_Contribute_BAO_Contribution();
509 $contribution->id = $params['original_contribution_id'];
510 if (!$contribution->find(TRUE)) {
511 throw new API_Exception(
512 'A valid original contribution ID is required', 'invalid_data');
513 }
514 $original_contribution = clone $contribution;
515 try {
516 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
517 throw new API_Exception('failed to load related objects');
518 }
519
520 unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
521 $contribution->contribution_status_id = $params['contribution_status_id'];
522 $contribution->receive_date = $params['receive_date'];
523
524 $passThroughParams = array('trxn_id', 'total_amount', 'campaign_id', 'fee_amount');
525 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
526
527 $params = _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
528 }
529 catch(Exception $e) {
530 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
531 }
532 }
533
534 /**
535 * Calls IPN complete transaction for completing or repeating a transaction.
536 *
537 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
538 * when separating them in the api layer.
539 *
540 * @param array $params
541 * @param CRM_Contribute_BAO_Contribution $contribution
542 * @param array $input
543 *
544 * @param array $ids
545 *
546 * @param CRM_Contribute_BAO_Contribution $firstContribution
547 *
548 * @return mixed
549 */
550 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
551 $objects = $contribution->_relatedObjects;
552 $objects['contribution'] = &$contribution;
553
554 if ($firstContribution) {
555 $objects['first_contribution'] = $firstContribution;
556 }
557 $input['component'] = $contribution->_component;
558 $input['is_test'] = $contribution->is_test;
559 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
560
561 if (isset($params['is_email_receipt'])) {
562 $input['is_email_receipt'] = $params['is_email_receipt'];
563 }
564 if (!empty($params['trxn_date'])) {
565 $input['trxn_date'] = $params['trxn_date'];
566 }
567 if (empty($contribution->contribution_page_id)) {
568 static $domainFromName;
569 static $domainFromEmail;
570 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
571 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
572 }
573 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
574 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
575 }
576 $transaction = new CRM_Core_Transaction();
577 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id), $contribution,
578 FALSE, FALSE);
579 return $params;
580 }
581
582 /**
583 * Provide function metadata.
584 *
585 * @param array $params
586 */
587 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
588 $params['original_contribution_id'] = array(
589 'title' => 'Original Contribution ID',
590 'type' => CRM_Utils_Type::T_INT,
591 'api.required' => TRUE,
592 );
593 $params['trxn_id'] = array(
594 'title' => 'Transaction ID',
595 'type' => CRM_Utils_Type::T_STRING,
596 );
597 $params['is_email_receipt'] = array(
598 'title' => 'Send email Receipt?',
599 'type' => CRM_Utils_Type::T_BOOLEAN,
600 );
601 $params['contribution_status_id'] = array(
602 'title' => 'Contribution Status ID',
603 'name' => 'contribution_status_id',
604 'type' => CRM_Utils_Type::T_INT,
605 'pseudoconstant' => array(
606 'optionGroupName' => 'contribution_status',
607 ),
608 'api.required' => TRUE,
609 );
610 $params['receive_date'] = array(
611 'title' => 'Contribution Receive Date',
612 'name' => 'receive_date',
613 'type' => CRM_Utils_Type::T_DATE,
614 'api.default' => 'now',
615 );
616 $params['trxn_id'] = array(
617 'title' => 'Transaction ID',
618 'name' => 'trxn_id',
619 'type' => CRM_Utils_Type::T_STRING,
620 );
621 $params['payment_processor_id'] = array(
622 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
623 'title' => 'Payment processor ID',
624 'name' => 'payment_processor_id',
625 'type' => CRM_Utils_Type::T_INT,
626 );
627 }