Merge pull request #16500 from eileenmcnaughton/fatal
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
18
19 /**
20 * Static field for all the contribution information that we can potentially import
21 *
22 * @var array
23 */
24 public static $_importableFields = NULL;
25
26 /**
27 * Static field for all the contribution information that we can potentially export
28 *
29 * @var array
30 */
31 public static $_exportableFields = NULL;
32
33 /**
34 * Static field to hold financial trxn id's.
35 *
36 * @var array
37 */
38 public static $_trxnIDs = NULL;
39
40 /**
41 * Field for all the objects related to this contribution
42 *
43 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
44 */
45 public $_relatedObjects = [];
46
47 /**
48 * Field for the component - either 'event' (participant) or 'contribute'
49 * (any item related to a contribution page e.g. membership, pledge, contribution)
50 * This is used for composing messages because they have dependency on the
51 * contribution_page or event page - although over time we may eliminate that
52 *
53 * @var string
54 * "contribution"\"event"
55 */
56 public $_component = NULL;
57
58 /**
59 * Possibly obsolete variable.
60 *
61 * If you use it please explain why it is set in the create function here.
62 *
63 * @var string
64 */
65 public $trxn_result_code;
66
67 /**
68 * Class constructor.
69 */
70 public function __construct() {
71 parent::__construct();
72 }
73
74 /**
75 * Takes an associative array and creates a contribution object.
76 *
77 * the function extract all the params it needs to initialize the create a
78 * contribution object. the params array could contain additional unused name/value
79 * pairs
80 *
81 * @param array $params
82 * (reference ) an assoc array of name/value pairs.
83 * @param array $ids
84 * The array that holds all the db ids.
85 *
86 * @return \CRM_Contribute_BAO_Contribution
87 * @throws \CRM_Core_Exception
88 * @throws \CiviCRM_API3_Exception
89 */
90 public static function add(&$params, $ids = []) {
91 if (empty($params)) {
92 return NULL;
93 }
94 if (!empty($ids)) {
95 CRM_Core_Error::deprecatedFunctionWarning('ids should not be passed into Contribution.add');
96 }
97 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
98 $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params));
99 $action = $contributionID ? 'edit' : 'create';
100 $duplicates = [];
101 if (self::checkDuplicate($params, $duplicates, $contributionID)) {
102 $message = ts("Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: %1", [1 => implode(', ', $duplicates)]);
103 throw new CRM_Core_Exception($message);
104 }
105
106 // first clean up all the money fields
107 $moneyFields = [
108 'total_amount',
109 'net_amount',
110 'fee_amount',
111 'non_deductible_amount',
112 ];
113
114 //if priceset is used, no need to cleanup money
115 if (!empty($params['skipCleanMoney'])) {
116 $moneyFields = [];
117 }
118 else {
119 // @todo put a deprecated here - this should be done in the form layer.
120 $params['skipCleanMoney'] = FALSE;
121 Civi::log()->warning('Deprecated code path. Money should always be clean before it hits the BAO.', array('civi.tag' => 'deprecated'));
122 }
123
124 foreach ($moneyFields as $field) {
125 if (isset($params[$field])) {
126 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
127 }
128 }
129
130 //set defaults in create mode
131 if (!$contributionID) {
132 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
133
134 if (empty($params['invoice_number']) && CRM_Invoicing_Utils::isInvoicingEnabled()) {
135 $nextContributionID = CRM_Core_DAO::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
136 $params['invoice_number'] = self::getInvoiceNumber($nextContributionID);
137 }
138 }
139
140 //if contribution is created with cancelled or refunded status, add credit note id
141 // do the same for chargeback - this entered the code 'accidentally' but moving it to here
142 // as part of cleanup maintains consistency.
143 if (self::isContributionStatusNegative(CRM_Utils_Array::value('contribution_status_id', $params))) {
144 if (empty($params['creditnote_id'])) {
145 $params['creditnote_id'] = self::createCreditNoteId();
146 }
147 }
148 $contributionStatusID = $params['contribution_status_id'] ?? NULL;
149 if (CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
150 CRM_Core_Error::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
151 }
152 if (!$contributionStatusID) {
153 // Since the fee amount is expecting this (later on) ensure it is always set.
154 // It would only not be set for an update where it is unchanged.
155 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
156 'id' => $contributionID,
157 'return' => 'contribution_status_id',
158 ]);
159 }
160 $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
161
162 if (!$contributionID
163 && CRM_Utils_Array::value('membership_id', $params)
164 && Civi::settings()->get('deferred_revenue_enabled')
165 ) {
166 $memberStartDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
167 if ($memberStartDate) {
168 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
169 }
170 }
171 self::calculateMissingAmountParams($params, $contributionID);
172
173 if (!empty($params['payment_instrument_id'])) {
174 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
175 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
176 $params['check_number'] = 'null';
177 }
178 }
179
180 $setPrevContribution = TRUE;
181 // CRM-13964 partial payment
182 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
183 $partialAmtTotal = $params['partial_payment_total'];
184 $partialAmtPay = $params['partial_amount_to_pay'];
185 $params['total_amount'] = $partialAmtTotal;
186 if ($partialAmtPay < $partialAmtTotal) {
187 $params['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
188 $params['is_pay_later'] = 0;
189 $setPrevContribution = FALSE;
190 }
191 }
192 if ($contributionID && $setPrevContribution) {
193 $params['prevContribution'] = self::getOriginalContribution($contributionID);
194 }
195 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id) : NULL;
196
197 if ($contributionID && !empty($params['revenue_recognition_date'])
198 && !($previousContributionStatus === 'Pending')
199 && !self::allowUpdateRevenueRecognitionDate($contributionID)
200 ) {
201 unset($params['revenue_recognition_date']);
202 }
203
204 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
205 isset($params['financial_type_id']))) {
206 $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
207 }
208
209 CRM_Utils_Hook::pre($action, 'Contribution', $contributionID, $params);
210
211 $contribution = new CRM_Contribute_BAO_Contribution();
212 $contribution->copyValues($params);
213
214 $contribution->id = $contributionID;
215
216 if (empty($contribution->id)) {
217 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
218 if (!CRM_Utils_Rule::currencyCode($contribution->currency)) {
219 $contribution->currency = CRM_Core_Config::singleton()->defaultCurrency;
220 }
221 }
222
223 $result = $contribution->save();
224
225 // Add financial_trxn details as part of fix for CRM-4724
226 $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params);
227 $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params);
228
229 //add Account details
230 $params['contribution'] = $contribution;
231 if (empty($params['is_post_payment_create'])) {
232 // If this is being called from the Payment.create api/ BAO then that Entity
233 // takes responsibility for the financial transactions. In fact calling Payment.create
234 // to add payments & having it call completetransaction and / or contribution.create
235 // to update related entities is the preferred flow.
236 // Note that leveraging this parameter for any other code flow is not supported and
237 // is likely to break in future and / or cause serious problems in your data.
238 // https://github.com/civicrm/civicrm-core/pull/14673
239 self::recordFinancialAccounts($params);
240 }
241
242 if (self::isUpdateToRecurringContribution($params)) {
243 CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment(
244 (!empty($params['contribution_recur_id']) ? $params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id),
245 $contributionStatus,
246 CRM_Utils_Array::value('receive_date', $params)
247 );
248 }
249
250 $params['contribution_id'] = $contribution->id;
251
252 if (!empty($params['custom']) &&
253 is_array($params['custom'])
254 ) {
255 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id, $action);
256 }
257
258 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
259
260 CRM_Utils_Hook::post($action, 'Contribution', $contribution->id, $contribution);
261 return $result;
262 }
263
264 /**
265 * Is this contribution updating an existing recurring contribution.
266 *
267 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
268 * pending payment is being confirmed (or failing).
269 *
270 * @param array $params
271 *
272 * @return bool
273 */
274 public static function isUpdateToRecurringContribution($params) {
275 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
276 return TRUE;
277 }
278 if (empty($params['prevContribution']) || empty($params['contribution_status_id'])) {
279 return FALSE;
280 }
281 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id)) {
282 return FALSE;
283 }
284 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
285 if ($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)) {
286 return TRUE;
287 }
288 return FALSE;
289 }
290
291 /**
292 * Get defaults for new entity.
293 *
294 * @return array
295 */
296 public static function getDefaults() {
297 return [
298 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument',
299 FALSE, FALSE, FALSE, 'AND is_default = 1')
300 ),
301 'contribution_status_id' => CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
302 'receive_date' => date('Y-m-d H:i:s'),
303 ];
304 }
305
306 /**
307 * Fetch the object and store the values in the values array.
308 *
309 * @param array $params
310 * Input parameters to find object.
311 * @param array $values
312 * Output values of the object.
313 * @param array $ids
314 * The array that holds all the db ids.
315 *
316 * @return CRM_Contribute_BAO_Contribution|null
317 * The found object or null
318 */
319 public static function getValues($params, &$values = [], &$ids = []) {
320 if (empty($params)) {
321 return NULL;
322 }
323 $contribution = new CRM_Contribute_BAO_Contribution();
324
325 $contribution->copyValues($params);
326
327 if ($contribution->find(TRUE)) {
328 $ids['contribution'] = $contribution->id;
329
330 CRM_Core_DAO::storeValues($contribution, $values);
331
332 return $contribution;
333 }
334 // return by reference
335 $null = NULL;
336 return $null;
337 }
338
339 /**
340 * Get the values and resolve the most common mappings.
341 *
342 * Since contribution status is resolved in almost every function that calls getValues it makes
343 * sense to have an extra function to resolve it rather than repeat the code.
344 *
345 * Think carefully before adding more mappings to be resolved as there could be performance implications
346 * if this function starts to be called from more iterative functions.
347 *
348 * @param array $params
349 * Input parameters to find object.
350 *
351 * @return array
352 * Array of the found contribution.
353 * @throws CRM_Core_Exception
354 */
355 public static function getValuesWithMappings($params) {
356 $values = $ids = [];
357 $contribution = self::getValues($params, $values, $ids);
358 if (is_null($contribution)) {
359 throw new CRM_Core_Exception('No contribution found');
360 }
361 $values['contribution_status'] = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
362 return $values;
363 }
364
365 /**
366 * Calculate net_amount & fee_amount if they are not set.
367 *
368 * Net amount should be total - fee.
369 * This should only be called for new contributions.
370 *
371 * @param array $params
372 * Params for a new contribution before they are saved.
373 * @param int|null $contributionID
374 * Contribution ID if we are dealing with an update.
375 *
376 * @throws \CiviCRM_API3_Exception
377 */
378 public static function calculateMissingAmountParams(&$params, $contributionID) {
379 if (!$contributionID && !isset($params['fee_amount'])) {
380 if (isset($params['total_amount']) && isset($params['net_amount'])) {
381 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
382 }
383 else {
384 $params['fee_amount'] = 0;
385 }
386 }
387 if (!isset($params['net_amount'])) {
388 if (!$contributionID) {
389 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
390 }
391 else {
392 if (isset($params['fee_amount']) || isset($params['total_amount'])) {
393 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
394 // net_amount may need adjusting.
395 $contribution = civicrm_api3('Contribution', 'getsingle', [
396 'id' => $contributionID,
397 'return' => ['total_amount', 'net_amount', 'fee_amount'],
398 ]);
399 $totalAmount = (isset($params['total_amount']) ? (float) $params['total_amount'] : (float) CRM_Utils_Array::value('total_amount', $contribution));
400 $feeAmount = (isset($params['fee_amount']) ? (float) $params['fee_amount'] : (float) CRM_Utils_Array::value('fee_amount', $contribution));
401 $params['net_amount'] = $totalAmount - $feeAmount;
402 }
403 }
404 }
405 }
406
407 /**
408 * @param $params
409 * @param $billingLocationTypeID
410 *
411 * @return array
412 */
413 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
414 $hasBillingField = FALSE;
415 $billingFields = [
416 'street_address',
417 'city',
418 'state_province_id',
419 'postal_code',
420 'country_id',
421 ];
422
423 //build address array
424 $addressParams = [];
425 $addressParams['location_type_id'] = $billingLocationTypeID;
426 $addressParams['is_billing'] = 1;
427
428 $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params);
429 $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params);
430 $billingLastName = CRM_Utils_Array::value('billing_last_name', $params);
431 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}";
432
433 foreach ($billingFields as $value) {
434 $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params);
435 if (!empty($addressParams[$value])) {
436 $hasBillingField = TRUE;
437 }
438 }
439 return [$hasBillingField, $addressParams];
440 }
441
442 /**
443 * Get address params ready to be passed to the payment processor.
444 *
445 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
446 * To create an address we need state_province_id.
447 *
448 * @param array $params
449 * @param int $billingLocationTypeID
450 *
451 * @return array
452 */
453 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
454 list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID);
455 foreach ($addressParams as $name => $field) {
456 if (substr($name, 0, 8) == 'billing_') {
457 $addressParams[substr($name, 9)] = $addressParams[$field];
458 }
459 }
460 return [$hasBillingField, $addressParams];
461 }
462
463 /**
464 * Get the number of terms for this contribution for a given membership type
465 * based on querying the line item table and relevant price field values
466 * Note that any one contribution should only be able to have one line item relating to a particular membership
467 * type
468 *
469 * @param int $membershipTypeID
470 *
471 * @param int $contributionID
472 *
473 * @return int
474 */
475 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
476 $numTerms = CRM_Core_DAO::singleValueQuery("
477 SELECT membership_num_terms FROM civicrm_line_item li
478 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
479 WHERE contribution_id = %1 AND membership_type_id = %2",
480 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
481 );
482 // default of 1 is precautionary
483 return empty($numTerms) ? 1 : $numTerms;
484 }
485
486 /**
487 * Takes an associative array and creates a contribution object.
488 *
489 * @param array $params
490 * (reference ) an assoc array of name/value pairs.
491 * @param array $ids
492 * The array that holds all the db ids.
493 *
494 * @return CRM_Contribute_BAO_Contribution
495 *
496 * @throws \CRM_Core_Exception
497 * @throws \CiviCRM_API3_Exception
498 */
499 public static function create(&$params, $ids = []) {
500 $dateFields = [
501 'receive_date',
502 'cancel_date',
503 'receipt_date',
504 'thankyou_date',
505 'revenue_recognition_date',
506 ];
507 foreach ($dateFields as $df) {
508 if (isset($params[$df])) {
509 $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
510 }
511 }
512
513 $transaction = new CRM_Core_Transaction();
514
515 try {
516 if (!isset($params['id']) && isset($ids['contribution'])) {
517 CRM_Core_Error::deprecatedFunctionWarning('ids should not be used for contribution create');
518 $params['id'] = $ids['contribution'];
519 }
520 $contribution = self::add($params);
521 }
522 catch (CRM_Core_Exception $e) {
523 $transaction->rollback();
524 throw $e;
525 }
526
527 $params['contribution_id'] = $contribution->id;
528 $session = CRM_Core_Session::singleton();
529
530 if (!empty($params['note'])) {
531 $noteParams = [
532 'entity_table' => 'civicrm_contribution',
533 'note' => $params['note'],
534 'entity_id' => $contribution->id,
535 'contact_id' => $session->get('userID'),
536 'modified_date' => date('Ymd'),
537 ];
538 if (!$noteParams['contact_id']) {
539 $noteParams['contact_id'] = $params['contact_id'];
540 }
541 CRM_Core_BAO_Note::add($noteParams);
542 }
543
544 // make entry in batch entity batch table
545 if (!empty($params['batch_id'])) {
546 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
547 $titleFields = [
548 'contact_id',
549 'total_amount',
550 'currency',
551 'financial_type_id',
552 ];
553 $retrieveRequired = 0;
554 foreach ($titleFields as $titleField) {
555 if (!isset($contribution->$titleField)) {
556 $retrieveRequired = 1;
557 break;
558 }
559 }
560 if ($retrieveRequired == 1) {
561 $contribution->find(TRUE);
562 }
563 }
564
565 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
566
567 $transaction->commit();
568
569 $activity = civicrm_api3('Activity', 'get', [
570 'source_record_id' => $contribution->id,
571 'options' => ['limit' => 1],
572 'sequential' => 1,
573 'activity_type_id' => 'Contribution',
574 'return' => ['id', 'campaign'],
575 ]);
576
577 //CRM-18406: Update activity when edit contribution.
578 if ($activity['count']) {
579 // CRM-13237 : if activity record found, update it with campaign id of contribution
580 // @todo compare campaign ids first.
581 CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id);
582 $contribution->activity_id = $activity['id'];
583 }
584
585 if (empty($contribution->contact_id)) {
586 $contribution->find(TRUE);
587 }
588 CRM_Activity_BAO_Activity::addActivity($contribution, 'Contribution');
589
590 // do not add to recent items for import, CRM-4399
591 if (empty($params['skipRecentView'])) {
592 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
593 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
594 );
595 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
596 $titleFields = [
597 'contact_id',
598 'total_amount',
599 'currency',
600 'financial_type_id',
601 ];
602 $retrieveRequired = 0;
603 foreach ($titleFields as $titleField) {
604 if (!isset($contribution->$titleField)) {
605 $retrieveRequired = 1;
606 break;
607 }
608 }
609 if ($retrieveRequired == 1) {
610 $contribution->find(TRUE);
611 }
612 $financialType = CRM_Contribute_PseudoConstant::financialType($contribution->financial_type_id);
613 $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $financialType . ')';
614
615 $recentOther = [];
616 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
617 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
618 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
619 );
620 }
621
622 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
623 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
624 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
625 );
626 }
627
628 // add the recently created Contribution
629 CRM_Utils_Recent::add($title,
630 $url,
631 $contribution->id,
632 'Contribution',
633 $contribution->contact_id,
634 NULL,
635 $recentOther
636 );
637 }
638
639 return $contribution;
640 }
641
642 /**
643 * Get the values for pseudoconstants for name->value and reverse.
644 *
645 * @param array $defaults
646 * (reference) the default values, some of which need to be resolved.
647 * @param bool $reverse
648 * True if we want to resolve the values in the reverse direction (value -> name).
649 */
650 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
651 self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse);
652 self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse);
653 self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label'), $reverse);
654 self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse);
655 }
656
657 /**
658 * Convert associative array names to values and vice-versa.
659 *
660 * This function is used by both the web form layer and the api. Note that
661 * the api needs the name => value conversion, also the view layer typically
662 * requires value => name conversion
663 *
664 * @param array $defaults
665 * @param string $property
666 * @param array $lookup
667 * @param bool $reverse
668 *
669 * @return bool
670 */
671 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
672 $id = $property . '_id';
673
674 $src = $reverse ? $property : $id;
675 $dst = $reverse ? $id : $property;
676
677 if (!array_key_exists($src, $defaults)) {
678 return FALSE;
679 }
680
681 $look = $reverse ? array_flip($lookup) : $lookup;
682
683 if (is_array($look)) {
684 if (!array_key_exists($defaults[$src], $look)) {
685 return FALSE;
686 }
687 }
688 $defaults[$dst] = $look[$defaults[$src]];
689 return TRUE;
690 }
691
692 /**
693 * Retrieve DB object based on input parameters.
694 *
695 * It also stores all the retrieved values in the default array.
696 *
697 * @param array $params
698 * (reference ) an assoc array of name/value pairs.
699 * @param array $defaults
700 * (reference ) an assoc array to hold the name / value pairs.
701 * in a hierarchical manner
702 * @param array $ids
703 * (reference) the array that holds all the db ids.
704 *
705 * @return CRM_Contribute_BAO_Contribution
706 */
707 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
708 $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
709 return $contribution;
710 }
711
712 /**
713 * Combine all the importable fields from the lower levels object.
714 *
715 * The ordering is important, since currently we do not have a weight
716 * scheme. Adding weight is super important and should be done in the
717 * next week or so, before this can be called complete.
718 *
719 * @param string $contactType
720 * @param bool $status
721 *
722 * @return array
723 * array of importable Fields
724 */
725 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
726 if (!self::$_importableFields) {
727 if (!self::$_importableFields) {
728 self::$_importableFields = [];
729 }
730
731 if (!$status) {
732 $fields = ['' => ['title' => ts('- do not import -')]];
733 }
734 else {
735 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
736 }
737
738 $note = CRM_Core_DAO_Note::import();
739 $tmpFields = CRM_Contribute_DAO_Contribution::import();
740 unset($tmpFields['option_value']);
741 $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
742 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
743
744 // Using new Dedupe rule.
745 $ruleParams = [
746 'contact_type' => $contactType,
747 'used' => 'Unsupervised',
748 ];
749 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
750 $tmpContactField = [];
751 if (is_array($fieldsArray)) {
752 foreach ($fieldsArray as $value) {
753 //skip if there is no dupe rule
754 if ($value == 'none') {
755 continue;
756 }
757 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
758 $value,
759 'id',
760 'column_name'
761 );
762 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
763 $tmpContactField[trim($value)] = $contactFields[trim($value)];
764 if (!$status) {
765 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
766 }
767 else {
768 $title = $tmpContactField[trim($value)]['title'];
769 }
770 $tmpContactField[trim($value)]['title'] = $title;
771 }
772 }
773
774 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
775 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
776 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
777 $fields = array_merge($fields, $tmpContactField);
778 $fields = array_merge($fields, $tmpFields);
779 $fields = array_merge($fields, $note);
780 $fields = array_merge($fields, $optionFields);
781 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
782 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
783 self::$_importableFields = $fields;
784 }
785 return self::$_importableFields;
786 }
787
788 /**
789 * Combine all the exportable fields from the lower level objects.
790 *
791 * @param bool $checkPermission
792 *
793 * @return array
794 * array of exportable Fields
795 */
796 public static function &exportableFields($checkPermission = TRUE) {
797 if (!self::$_exportableFields) {
798 if (!self::$_exportableFields) {
799 self::$_exportableFields = [];
800 }
801
802 $fields = CRM_Contribute_DAO_Contribution::export();
803 if (CRM_Contribute_BAO_Query::isSiteHasProducts()) {
804 $fields = array_merge(
805 $fields,
806 CRM_Contribute_DAO_Product::export(),
807 CRM_Contribute_DAO_ContributionProduct::export(),
808 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
809 [
810 'contribution_product_id' => [
811 'title' => ts('Premium'),
812 'name' => 'contribution_product_id',
813 'where' => 'civicrm_product.id',
814 'data_type' => CRM_Utils_Type::T_INT,
815 ],
816 ]
817 );
818 }
819
820 $financialAccount = CRM_Financial_DAO_FinancialAccount::export();
821
822 $contributionPage = [
823 'contribution_page' => [
824 'title' => ts('Contribution Page'),
825 'name' => 'contribution_page',
826 'where' => 'civicrm_contribution_page.title',
827 'data_type' => CRM_Utils_Type::T_STRING,
828 ],
829 ];
830
831 $contributionNote = [
832 'contribution_note' => [
833 'title' => ts('Contribution Note'),
834 'name' => 'contribution_note',
835 'data_type' => CRM_Utils_Type::T_TEXT,
836 ],
837 ];
838
839 $extraFields = [
840 'contribution_batch' => [
841 'title' => ts('Batch Name'),
842 ],
843 ];
844
845 // CRM-17787
846 $campaignTitle = [
847 'contribution_campaign_title' => [
848 'title' => ts('Campaign Title'),
849 'name' => 'campaign_title',
850 'where' => 'civicrm_campaign.title',
851 'data_type' => CRM_Utils_Type::T_STRING,
852 ],
853 ];
854 $softCreditFields = [
855 'contribution_soft_credit_name' => [
856 'name' => 'contribution_soft_credit_name',
857 'title' => ts('Soft Credit For'),
858 'where' => 'civicrm_contact_d.display_name',
859 'data_type' => CRM_Utils_Type::T_STRING,
860 ],
861 'contribution_soft_credit_amount' => [
862 'name' => 'contribution_soft_credit_amount',
863 'title' => ts('Soft Credit Amount'),
864 'where' => 'civicrm_contribution_soft.amount',
865 'data_type' => CRM_Utils_Type::T_MONEY,
866 ],
867 'contribution_soft_credit_type' => [
868 'name' => 'contribution_soft_credit_type',
869 'title' => ts('Soft Credit Type'),
870 'where' => 'contribution_softcredit_type.label',
871 'data_type' => CRM_Utils_Type::T_STRING,
872 ],
873 'contribution_soft_credit_contribution_id' => [
874 'name' => 'contribution_soft_credit_contribution_id',
875 'title' => ts('Soft Credit For Contribution ID'),
876 'where' => 'civicrm_contribution_soft.contribution_id',
877 'data_type' => CRM_Utils_Type::T_INT,
878 ],
879 'contribution_soft_credit_contact_id' => [
880 'name' => 'contribution_soft_credit_contact_id',
881 'title' => ts('Soft Credit For Contact ID'),
882 'where' => 'civicrm_contact_d.id',
883 'data_type' => CRM_Utils_Type::T_INT,
884 ],
885 ];
886
887 $fields = array_merge($fields, $contributionPage,
888 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
889 CRM_Core_BAO_CustomField::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
890 );
891
892 self::$_exportableFields = $fields;
893 }
894
895 return self::$_exportableFields;
896 }
897
898 /**
899 * Record an activity when a payment is received.
900 *
901 * @todo this is intended to be moved to payment BAO class as a protected function
902 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
903 * merit it's own function as it makes the code less rather than more readable.
904 *
905 * @param int $contributionId
906 * @param int $participantId
907 * @param string $totalAmount
908 * @param string $currency
909 * @param string $trxnDate
910 *
911 * @throws \CRM_Core_Exception
912 * @throws \CiviCRM_API3_Exception
913 */
914 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
915 $activityType = ($totalAmount < 0) ? 'Refund' : 'Payment';
916
917 if ($participantId) {
918 $inputParams['id'] = $participantId;
919 $values = [];
920 $ids = [];
921 $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
922 $entityObj = $entityObj[$participantId];
923 $title = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
924 }
925 else {
926 $entityObj = new CRM_Contribute_BAO_Contribution();
927 $entityObj->id = $contributionId;
928 $entityObj->find(TRUE);
929 $title = ts('Contribution');
930 }
931 // @todo per block above this is not a logical splitting off of functionality.
932 self::addActivityForPayment($entityObj->contact_id, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
933 }
934
935 /**
936 * Get the value for the To Financial Account.
937 *
938 * @param $contribution
939 * @param $params
940 *
941 * @return int
942 */
943 public static function getToFinancialAccount($contribution, $params) {
944 if (!empty($params['payment_processor_id'])) {
945 return CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
946 }
947 if (!empty($params['payment_instrument_id'])) {
948 return CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
949 }
950 else {
951 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
952 $queryParams = [1 => [$relationTypeId, 'Integer']];
953 return CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
954 }
955 }
956
957 /**
958 * Get memberships related to the contribution.
959 *
960 * @param int $contributionID
961 *
962 * @return array
963 */
964 protected static function getRelatedMemberships($contributionID) {
965 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
966 'return' => 'membership_id',
967 'contribution_id' => (int) $contributionID,
968 ])['values'];
969 $membershipIDs = [];
970 foreach ($membershipPayments as $membershipPayment) {
971 $membershipIDs[] = $membershipPayment['membership_id'];
972 }
973 if (empty($membershipIDs)) {
974 return [];
975 }
976 // We could combine this with the MembershipPayment.get - we'd
977 // need to re-wrangle the params (here or in the calling function)
978 // as they would then me membership.contact_id, membership.is_test etc
979 return civicrm_api3('Membership', 'get', [
980 'id' => ['IN' => $membershipIDs],
981 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
982 ])['values'];
983 }
984
985 /**
986 * Cancel contribution.
987 *
988 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
989 *
990 * @param $processContributionObject
991 * @param $memberships
992 * @param $contributionId
993 * @param $membershipStatuses
994 * @param $updateResult
995 * @param $participant
996 * @param $oldStatus
997 * @param $pledgePayment
998 * @param $pledgeID
999 * @param $pledgePaymentIDs
1000 * @param $contributionStatusId
1001 *
1002 * @return array
1003 */
1004 protected static function cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
1005 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
1006 $processContribution = FALSE;
1007 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1008 if (is_array($memberships)) {
1009 foreach ($memberships as $membership) {
1010 $update = TRUE;
1011 //Update Membership status if there is no other completed contribution associated with the membership.
1012 $relatedContributions = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id, TRUE);
1013 foreach ($relatedContributions as $contriId) {
1014 if ($contriId == $contributionId) {
1015 continue;
1016 }
1017 $statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1018 if (CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1019 $update = FALSE;
1020 }
1021 }
1022 if ($membership && $update) {
1023 $newStatus = array_search('Cancelled', $membershipStatuses);
1024
1025 // Create activity
1026 $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
1027 $activityParam = [
1028 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1029 'source_contact_id' => CRM_Core_Session::singleton()->get('userID'),
1030 'target_contact_id' => $membership->contact_id,
1031 'source_record_id' => $membership->id,
1032 'activity_type_id' => 'Change Membership Status',
1033 'status_id' => 'Completed',
1034 'priority_id' => 'Normal',
1035 'activity_date_time' => 'now',
1036 ];
1037
1038 $membership->status_id = $newStatus;
1039 $membership->is_override = TRUE;
1040 $membership->status_override_end_date = 'null';
1041 $membership->save();
1042 civicrm_api3('activity', 'create', $activityParam);
1043
1044 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1045 if ($processContributionObject) {
1046 $processContribution = TRUE;
1047 }
1048 }
1049 }
1050 }
1051
1052 if ($participant) {
1053 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1054 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1055
1056 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1057 if ($processContributionObject) {
1058 $processContribution = TRUE;
1059 }
1060 }
1061
1062 if ($pledgePayment) {
1063 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1064
1065 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1066 if ($processContributionObject) {
1067 $processContribution = TRUE;
1068 }
1069 }
1070 return [$updateResult, $processContribution];
1071 }
1072
1073 /**
1074 * Do any accounting updates required as a result of a contribution status change.
1075 *
1076 * Currently we have a bit of a roundabout where adding a payment results in this being called &
1077 * this may attempt to add a payment. We need to resolve that....
1078 *
1079 * The 'right' way to add payments or refunds is through the Payment.create api. That api
1080 * then updates the contribution but this process should not also record another financial trxn.
1081 * Currently we have weak detection fot that scenario & where it is detected the first returned
1082 * value is FALSE - meaning 'do not continue'.
1083 *
1084 * We should also look at the fact that the calling function - updateFinancialAccounts
1085 * bunches together some disparate processes rather than having separate appropriate
1086 * functions.
1087 *
1088 * @param array $params
1089 *
1090 * @return bool
1091 * Return indicates whether the updateFinancialAccounts function should continue.
1092 */
1093 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
1094 $previousContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['prevContribution']->contribution_status_id, 'name');
1095 $currentContributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id);
1096
1097 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1098 || ($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1099 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1100 // why it is here or where it is handled instead.
1101 || ($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later == TRUE
1102 && $currentContributionStatus == 'Partially paid'))
1103 ) {
1104 return FALSE;
1105 }
1106
1107 if (self::isContributionUpdateARefund($params['prevContribution']->contribution_status_id, $params['contribution']->contribution_status_id)) {
1108 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1109 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1110 if (empty($params['contribution']->creditnote_id)) {
1111 // This is always set in the Contribution::create function.
1112 CRM_Core_Error::deprecatedFunctionWarning('Logic says this line is never reached & can be removed');
1113 $creditNoteId = self::createCreditNoteId();
1114 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id, 'creditnote_id', $creditNoteId);
1115 }
1116 }
1117 elseif (($previousContributionStatus == 'Pending'
1118 && $params['prevContribution']->is_pay_later) || $previousContributionStatus == 'In Progress'
1119 ) {
1120 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
1121 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1122
1123 if ($currentContributionStatus == 'Cancelled') {
1124 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1125 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1126 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1127 if (empty($params['contribution']->creditnote_id)) {
1128 // This is always set in the Contribution::create function.
1129 CRM_Core_Error::deprecatedFunctionWarning('Logic says this line is never reached & can be removed');
1130 $creditNoteId = self::createCreditNoteId();
1131 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id, 'creditnote_id', $creditNoteId);
1132 }
1133 }
1134 else {
1135 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1136 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1137 }
1138 }
1139
1140 if (($previousContributionStatus == 'Pending'
1141 || $previousContributionStatus == 'In Progress')
1142 && ($currentContributionStatus == 'Completed')
1143 ) {
1144 if (empty($params['line_item'])) {
1145 //CRM-15296
1146 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1147 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1148 // & this can be removed
1149 return FALSE;
1150 }
1151 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1152 // This is an update so original currency if none passed in.
1153 $params['trxnParams']['currency'] = CRM_Utils_Array::value('currency', $params, $params['prevContribution']->currency);
1154
1155 self::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1156 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
1157 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1158 $params['entity_id'] = self::$_trxnIDs[] = $trxn->id;
1159
1160 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1161
1162 $entityParams = [
1163 'entity_table' => 'civicrm_financial_item',
1164 ];
1165 foreach ($params['line_item'] as $fieldId => $fields) {
1166 foreach ($fields as $fieldValueId => $lineItemDetails) {
1167 self::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1168 $fparams = [
1169 1 => [$lineItemDetails['id'], 'Integer'],
1170 ];
1171 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
1172 while ($financialItem->fetch()) {
1173 $entityParams['entity_id'] = $financialItem->id;
1174 $entityParams['amount'] = $financialItem->amount;
1175 foreach (self::$_trxnIDs as $tID) {
1176 $entityParams['financial_trxn_id'] = $tID;
1177 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
1178 }
1179 }
1180 }
1181 }
1182 return FALSE;
1183 }
1184 return TRUE;
1185 }
1186
1187 /**
1188 * It is possible to override the membership id that is updated from the payment processor.
1189 *
1190 * Historically Paypal does this & it still does if it determines data is messed up - see
1191 * https://lab.civicrm.org/dev/membership/issues/13
1192 *
1193 * Read the comment block on repeattransaction for more information
1194 * about how things should work.
1195 *
1196 * @param int $contributionID
1197 * @param array $input
1198 *
1199 * @throws \CiviCRM_API3_Exception
1200 */
1201 protected static function handleMembershipIDOverride($contributionID, $input) {
1202 if (!empty($input['membership_id'])) {
1203 Civi::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1204 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1205 }
1206 }
1207
1208 /**
1209 * Update all financial items related to the line item tto have a status of paid.
1210 *
1211 * @param int $lineItemID
1212 */
1213 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1214 $fparams = [
1215 1 => [
1216 CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1217 'Integer',
1218 ],
1219 2 => [$lineItemID, 'Integer'],
1220 ];
1221 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1222 CRM_Core_DAO::executeQuery($query, $fparams);
1223 }
1224
1225 /**
1226 * Create the financial items for the line.
1227 *
1228 * @param array $params
1229 * @param string $context
1230 * @param array $fields
1231 * @param array $previousLineItems
1232 * @param array $inputParams
1233 * @param bool $isARefund
1234 * @param array $trxnIds
1235 * @param int $fieldId
1236 *
1237 * @return array
1238 */
1239 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1240 foreach ($fields as $fieldValueId => $lineItemDetails) {
1241 $prevFinancialItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($lineItemDetails['id']);
1242 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
1243 if ($params['contribution']->receive_date) {
1244 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
1245 }
1246
1247 $financialAccount = self::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array::value('financial_account_id', $prevFinancialItem));
1248
1249 $currency = $params['prevContribution']->currency;
1250 if ($params['contribution']->currency) {
1251 $currency = $params['contribution']->currency;
1252 }
1253 $previousLineItemTotal = CRM_Utils_Array::value('line_total', CRM_Utils_Array::value($fieldValueId, $previousLineItems), 0);
1254 $itemParams = [
1255 'transaction_date' => $receiveDate,
1256 'contact_id' => $params['prevContribution']->contact_id,
1257 'currency' => $currency,
1258 'amount' => self::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1259 'description' => CRM_Utils_Array::value('description', $prevFinancialItem),
1260 'status_id' => $prevFinancialItem['status_id'],
1261 'financial_account_id' => $financialAccount,
1262 'entity_table' => 'civicrm_line_item',
1263 'entity_id' => $lineItemDetails['id'],
1264 ];
1265 $financialItem = CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
1266 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1267 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id;
1268
1269 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') || ($context == 'changeFinancialType')) {
1270 $taxAmount = (float) $lineItemDetails['tax_amount'];
1271 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1272 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1273 $taxAmount = CRM_Utils_Array::value('tax_amount', CRM_Utils_Array::value($fieldValueId, $previousLineItems), 0);
1274 }
1275 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1276 $taxAmount -= CRM_Utils_Array::value('tax_amount', CRM_Utils_Array::value($fieldValueId, $previousLineItems), 0);
1277 }
1278 if ($taxAmount != 0) {
1279 $itemParams['amount'] = self::getMultiplier($params['contribution']->contribution_status_id, $context) * $taxAmount;
1280 $itemParams['description'] = CRM_Invoicing_Utils::getTaxTerm();
1281 if ($lineItemDetails['financial_type_id']) {
1282 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1283 }
1284 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
1285 }
1286 }
1287 }
1288 return $params;
1289 }
1290
1291 /**
1292 * Does this contributtion status update represent a refund.
1293 *
1294 * @param int $previousContributionStatusID
1295 * @param int $currentContributionStatusID
1296 *
1297 * @return bool
1298 */
1299 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1300 if ('Completed' !== CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1301 return FALSE;
1302 }
1303 return self::isContributionStatusNegative($currentContributionStatusID);
1304 }
1305
1306 /**
1307 * @inheritDoc
1308 */
1309 public function addSelectWhereClause() {
1310 $whereClauses = parent::addSelectWhereClause();
1311 if ($whereClauses !== []) {
1312 // In this case permisssions have been applied & we assume the
1313 // financialaclreport is applying these
1314 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1315 return $whereClauses;
1316 }
1317
1318 if (!CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
1319 return $whereClauses;
1320 }
1321 $types = CRM_Financial_BAO_FinancialType::getAllEnabledAvailableFinancialTypes();
1322 if (empty($types)) {
1323 $whereClauses['financial_type_id'] = 'IN (0)';
1324 }
1325 else {
1326 $whereClauses['financial_type_id'] = [
1327 'IN (' . implode(',', array_keys($types)) . ')',
1328 ];
1329 }
1330 return $whereClauses;
1331 }
1332
1333 /**
1334 * @param null $status
1335 * @param null $startDate
1336 * @param null $endDate
1337 *
1338 * @return array|null
1339 */
1340 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1341 $where = [];
1342 switch ($status) {
1343 case 'Valid':
1344 $where[] = 'contribution_status_id = 1';
1345 break;
1346
1347 case 'Cancelled':
1348 $where[] = 'contribution_status_id = 3';
1349 break;
1350 }
1351
1352 if ($startDate) {
1353 $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
1354 }
1355 if ($endDate) {
1356 $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
1357 }
1358 $financialTypeACLJoin = '';
1359 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
1360 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1361 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
1362 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
1363 if ($financialTypes) {
1364 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1365 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1366 }
1367 else {
1368 $where[] = "c.financial_type_id IN (0)";
1369 }
1370 }
1371
1372 $whereCond = implode(' AND ', $where);
1373
1374 $query = "
1375 SELECT sum( total_amount ) as total_amount,
1376 count( c.id ) as total_count,
1377 currency
1378 FROM civicrm_contribution c
1379 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1380 $financialTypeACLJoin
1381 WHERE $whereCond
1382 AND ( is_test = 0 OR is_test IS NULL )
1383 AND contact.is_deleted = 0
1384 GROUP BY currency
1385 ";
1386
1387 $dao = CRM_Core_DAO::executeQuery($query);
1388 $amount = [];
1389 $count = 0;
1390 while ($dao->fetch()) {
1391 $count += $dao->total_count;
1392 $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
1393 }
1394 if ($count) {
1395 return [
1396 'amount' => implode(', ', $amount),
1397 'count' => $count,
1398 ];
1399 }
1400 return NULL;
1401 }
1402
1403 /**
1404 * Delete the indirect records associated with this contribution first.
1405 *
1406 * @param int $id
1407 *
1408 * @return mixed|null
1409 * $results no of deleted Contribution on success, false otherwise
1410 */
1411 public static function deleteContribution($id) {
1412 CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray);
1413
1414 $transaction = new CRM_Core_Transaction();
1415
1416 $results = NULL;
1417 //delete activity record
1418 $params = [
1419 'source_record_id' => $id,
1420 // activity type id for contribution
1421 'activity_type_id' => 6,
1422 ];
1423
1424 CRM_Activity_BAO_Activity::deleteActivity($params);
1425
1426 //delete billing address if exists for this contribution.
1427 self::deleteAddress($id);
1428
1429 //update pledge and pledge payment, CRM-3961
1430 CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
1431
1432 // remove entry from civicrm_price_set_entity, CRM-5095
1433 if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
1434 CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
1435 }
1436 // cleanup line items.
1437 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1438
1439 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1440 CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id);
1441
1442 if ($participantId) {
1443 CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant');
1444 }
1445 else {
1446 CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution');
1447 }
1448
1449 //delete note.
1450 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution');
1451 $noteId = key($note);
1452 if ($noteId) {
1453 CRM_Core_BAO_Note::del($noteId, FALSE);
1454 }
1455
1456 $dao = new CRM_Contribute_DAO_Contribution();
1457 $dao->id = $id;
1458
1459 $results = $dao->delete();
1460
1461 $transaction->commit();
1462
1463 CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao);
1464
1465 // delete the recently created Contribution
1466 $contributionRecent = [
1467 'id' => $id,
1468 'type' => 'Contribution',
1469 ];
1470 CRM_Utils_Recent::del($contributionRecent);
1471
1472 return $results;
1473 }
1474
1475 /**
1476 * React to a financial transaction (payment) failure.
1477 *
1478 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1479 * payments is important for forensic and outreach reasons.
1480 *
1481 * @param int $contributionID
1482 * @param int $contactID
1483 * @param string $message
1484 *
1485 * @throws \CiviCRM_API3_Exception
1486 */
1487 public static function failPayment($contributionID, $contactID, $message) {
1488 civicrm_api3('activity', 'create', [
1489 'activity_type_id' => 'Failed Payment',
1490 'details' => $message,
1491 'subject' => ts('Payment failed at payment processor'),
1492 'source_record_id' => $contributionID,
1493 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : $contactID,
1494 ]);
1495
1496 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1497 civicrm_api3('contribution', 'create', [
1498 'id' => $contributionID,
1499 'contribution_status_id' => 'Failed',
1500 ]);
1501 }
1502
1503 /**
1504 * Check if there is a contribution with the same trxn_id or invoice_id.
1505 *
1506 * @param array $input
1507 * An assoc array of name/value pairs.
1508 * @param array $duplicates
1509 * (reference) store ids of duplicate contribs.
1510 * @param int $id
1511 *
1512 * @return bool
1513 * true if duplicate, false otherwise
1514 */
1515 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1516 if (!$id) {
1517 $id = CRM_Utils_Array::value('id', $input);
1518 }
1519 $trxn_id = CRM_Utils_Array::value('trxn_id', $input);
1520 $invoice_id = CRM_Utils_Array::value('invoice_id', $input);
1521
1522 $clause = [];
1523 $input = [];
1524
1525 if ($trxn_id) {
1526 $clause[] = "trxn_id = %1";
1527 $input[1] = [$trxn_id, 'String'];
1528 }
1529
1530 if ($invoice_id) {
1531 $clause[] = "invoice_id = %2";
1532 $input[2] = [$invoice_id, 'String'];
1533 }
1534
1535 if (empty($clause)) {
1536 return FALSE;
1537 }
1538
1539 $clause = implode(' OR ', $clause);
1540 if ($id) {
1541 $clause = "( $clause ) AND id != %3";
1542 $input[3] = [$id, 'Integer'];
1543 }
1544
1545 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1546 $dao = CRM_Core_DAO::executeQuery($query, $input);
1547 $result = FALSE;
1548 while ($dao->fetch()) {
1549 $duplicates[] = $dao->id;
1550 $result = TRUE;
1551 }
1552 return $result;
1553 }
1554
1555 /**
1556 * Takes an associative array and creates a contribution_product object.
1557 *
1558 * the function extract all the params it needs to initialize the create a
1559 * contribution_product object. the params array could contain additional unused name/value
1560 * pairs
1561 *
1562 * @param array $params
1563 * (reference) an assoc array of name/value pairs.
1564 *
1565 * @return CRM_Contribute_DAO_ContributionProduct
1566 */
1567 public static function addPremium(&$params) {
1568 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1569 $contributionProduct->copyValues($params);
1570 return $contributionProduct->save();
1571 }
1572
1573 /**
1574 * Get list of contribution fields for profile.
1575 * For now we only allow custom contribution fields to be in
1576 * profile
1577 *
1578 * @param bool $addExtraFields
1579 * True if special fields needs to be added.
1580 *
1581 * @return array
1582 * the list of contribution fields
1583 */
1584 public static function getContributionFields($addExtraFields = TRUE) {
1585 $contributionFields = CRM_Contribute_DAO_Contribution::export();
1586 // @todo remove this - this line was added because payment_instrument_id was not
1587 // set to exportable - but now it is.
1588 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
1589
1590 if ($addExtraFields) {
1591 $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields());
1592 }
1593
1594 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export());
1595
1596 foreach ($contributionFields as $key => $var) {
1597 if ($key == 'contribution_contact_id') {
1598 continue;
1599 }
1600 elseif ($key == 'contribution_campaign_id') {
1601 $var['title'] = ts('Campaign');
1602 }
1603 $fields[$key] = $var;
1604 }
1605
1606 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
1607 return $fields;
1608 }
1609
1610 /**
1611 * Add extra fields specific to contribution.
1612 */
1613 public static function getSpecialContributionFields() {
1614 $extraFields = [
1615 'contribution_soft_credit_name' => [
1616 'name' => 'contribution_soft_credit_name',
1617 'title' => ts('Soft Credit Name'),
1618 'headerPattern' => '/^soft_credit_name$/i',
1619 'where' => 'civicrm_contact_d.display_name',
1620 ],
1621 'contribution_soft_credit_email' => [
1622 'name' => 'contribution_soft_credit_email',
1623 'title' => ts('Soft Credit Email'),
1624 'headerPattern' => '/^soft_credit_email$/i',
1625 'where' => 'soft_email.email',
1626 ],
1627 'contribution_soft_credit_phone' => [
1628 'name' => 'contribution_soft_credit_phone',
1629 'title' => ts('Soft Credit Phone'),
1630 'headerPattern' => '/^soft_credit_phone$/i',
1631 'where' => 'soft_phone.phone',
1632 ],
1633 'contribution_soft_credit_contact_id' => [
1634 'name' => 'contribution_soft_credit_contact_id',
1635 'title' => ts('Soft Credit Contact ID'),
1636 'headerPattern' => '/^soft_credit_contact_id$/i',
1637 'where' => 'civicrm_contribution_soft.contact_id',
1638 ],
1639 'contribution_pcp_title' => [
1640 'name' => 'contribution_pcp_title',
1641 'title' => ts('Personal Campaign Page Title'),
1642 'headerPattern' => '/^contribution_pcp_title$/i',
1643 'where' => 'contribution_pcp.title',
1644 ],
1645 ];
1646
1647 return $extraFields;
1648 }
1649
1650 /**
1651 * @param int $pageID
1652 *
1653 * @return array
1654 */
1655 public static function getCurrentandGoalAmount($pageID) {
1656 $query = "
1657 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1658 FROM civicrm_contribution_page p,
1659 civicrm_contribution c
1660 WHERE p.id = c.contribution_page_id
1661 AND p.id = %1
1662 AND c.cancel_date is null
1663 GROUP BY p.id
1664 ";
1665
1666 $config = CRM_Core_Config::singleton();
1667 $params = [1 => [$pageID, 'Integer']];
1668 $dao = CRM_Core_DAO::executeQuery($query, $params);
1669
1670 if ($dao->fetch()) {
1671 return [$dao->goal, $dao->total];
1672 }
1673 else {
1674 return [NULL, NULL];
1675 }
1676 }
1677
1678 /**
1679 * Get list of contributions which credit the passed in contact ID.
1680 *
1681 * The returned array provides details about the original contribution & donor.
1682 *
1683 * @param int $honorId
1684 * In Honor of Contact ID.
1685 *
1686 * @return array
1687 * list of contribution fields
1688 * @todo - this is a confusing function called from one place. It has a test. It would be
1689 * nice to deprecate it.
1690 *
1691 */
1692 public static function getHonorContacts($honorId) {
1693 $params = [];
1694 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1695 $honorDAO->contact_id = $honorId;
1696 $honorDAO->find();
1697
1698 $type = CRM_Contribute_PseudoConstant::financialType();
1699
1700 while ($honorDAO->fetch()) {
1701 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1702 $contributionDAO->id = $honorDAO->contribution_id;
1703
1704 if ($contributionDAO->find(TRUE)) {
1705 $params[$contributionDAO->id]['honor_type'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id);
1706 $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id;
1707 $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name');
1708 $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id];
1709 $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id;
1710 $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency);
1711 $params[$contributionDAO->id]['source'] = $contributionDAO->source;
1712 $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date;
1713 $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id, 'label');
1714 }
1715 }
1716
1717 return $params;
1718 }
1719
1720 /**
1721 * Get the sort name of a contact for a particular contribution.
1722 *
1723 * @param int $id
1724 * Id of the contribution.
1725 *
1726 * @return null|string
1727 * sort name of the contact if found
1728 */
1729 public static function sortName($id) {
1730 $id = CRM_Utils_Type::escape($id, 'Integer');
1731
1732 $query = "
1733 SELECT civicrm_contact.sort_name
1734 FROM civicrm_contribution, civicrm_contact
1735 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1736 AND civicrm_contribution.id = {$id}
1737 ";
1738 return CRM_Core_DAO::singleValueQuery($query);
1739 }
1740
1741 /**
1742 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1743 *
1744 * @param int|array $contactIDs
1745 *
1746 * @return array
1747 */
1748 public static function annual($contactIDs) {
1749 if (!is_array($contactIDs)) {
1750 // In practice I can't fine any evidence that this function is ever called with
1751 // anything other than a single contact id, but left like this due to .... fear.
1752 $contactIDs = explode(',', $contactIDs);
1753 }
1754
1755 $query = self::getAnnualQuery($contactIDs);
1756 $dao = CRM_Core_DAO::executeQuery($query);
1757 $count = 0;
1758 $amount = $average = [];
1759 while ($dao->fetch()) {
1760 if ($dao->count > 0 && $dao->amount > 0) {
1761 $count += $dao->count;
1762 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency);
1763 $average[] = CRM_Utils_Money::format($dao->average, $dao->currency);
1764 }
1765 }
1766 if ($count > 0) {
1767 return [
1768 $count,
1769 implode(',&nbsp;', $amount),
1770 implode(',&nbsp;', $average),
1771 ];
1772 }
1773 return [0, 0, 0];
1774 }
1775
1776 /**
1777 * Check if there is a contribution with the params passed in.
1778 *
1779 * Used for trxn_id,invoice_id and contribution_id
1780 *
1781 * @param array $params
1782 * An assoc array of name/value pairs.
1783 *
1784 * @return array
1785 * contribution id if success else NULL
1786 */
1787 public static function checkDuplicateIds($params) {
1788 $dao = new CRM_Contribute_DAO_Contribution();
1789
1790 $clause = [];
1791 $input = [];
1792 foreach ($params as $k => $v) {
1793 if ($v) {
1794 $clause[] = "$k = '$v'";
1795 }
1796 }
1797 $clause = implode(' AND ', $clause);
1798 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1799 $dao = CRM_Core_DAO::executeQuery($query, $input);
1800
1801 while ($dao->fetch()) {
1802 $result = $dao->id;
1803 return $result;
1804 }
1805 return NULL;
1806 }
1807
1808 /**
1809 * Get the contribution details for component export.
1810 *
1811 * @param int $exportMode
1812 * Export mode.
1813 * @param array $componentIds
1814 * Component ids.
1815 *
1816 * @return array
1817 * associated array
1818 */
1819 public static function getContributionDetails($exportMode, $componentIds) {
1820 $paymentDetails = [];
1821 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1822
1823 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1824 $componentSelect = " civicrm_participant_payment.participant_id id";
1825 $additionalClause = "
1826 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1827 AND civicrm_participant_payment.participant_id {$componentClause} )
1828 ";
1829 }
1830 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1831 $componentSelect = " civicrm_membership_payment.membership_id id";
1832 $additionalClause = "
1833 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1834 AND civicrm_membership_payment.membership_id {$componentClause} )
1835 ";
1836 }
1837 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1838 $componentSelect = " civicrm_pledge_payment.id id";
1839 $additionalClause = "
1840 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1841 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1842 ";
1843 }
1844
1845 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1846 trxn_id, {$componentSelect}
1847 FROM civicrm_contribution
1848 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1849 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1850 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1851 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1852 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1853 AND option_group_contribution_status.id = contribution_status.option_group_id )
1854 {$additionalClause}
1855 ";
1856
1857 $dao = CRM_Core_DAO::executeQuery($query);
1858
1859 while ($dao->fetch()) {
1860 $paymentDetails[$dao->id] = [
1861 'total_amount' => $dao->total_amount,
1862 'contribution_status' => $dao->status,
1863 'receive_date' => $dao->receive_date,
1864 'pay_instru' => $dao->payment_instrument,
1865 'trxn_id' => $dao->trxn_id,
1866 ];
1867 }
1868
1869 return $paymentDetails;
1870 }
1871
1872 /**
1873 * Create address associated with contribution record.
1874 *
1875 * As long as there is one or more billing field in the parameters we will create the address.
1876 *
1877 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1878 * thought).
1879 *
1880 * @param array $params
1881 * @param int $billingLocationTypeID
1882 *
1883 * @return int
1884 * address id
1885 */
1886 public static function createAddress($params, $billingLocationTypeID) {
1887 list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID);
1888 if ($hasBillingField) {
1889 $address = CRM_Core_BAO_Address::add($addressParams, FALSE);
1890 return $address->id;
1891 }
1892 return NULL;
1893
1894 }
1895
1896 /**
1897 * Delete billing address record related contribution.
1898 *
1899 * @param int $contributionId
1900 * @param int $contactId
1901 */
1902 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1903 $clauses = [];
1904 $contactJoin = NULL;
1905
1906 if ($contributionId) {
1907 $clauses[] = "cc.id = {$contributionId}";
1908 }
1909
1910 if ($contactId) {
1911 $clauses[] = "cco.id = {$contactId}";
1912 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1913 }
1914
1915 if (empty($clauses)) {
1916 CRM_Core_Error::fatal();
1917 }
1918
1919 $condition = implode(' OR ', $clauses);
1920
1921 $query = "
1922 SELECT ca.id
1923 FROM civicrm_address ca
1924 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1925 $contactJoin
1926 WHERE $condition
1927 ";
1928 $dao = CRM_Core_DAO::executeQuery($query);
1929
1930 while ($dao->fetch()) {
1931 $params = ['id' => $dao->id];
1932 CRM_Core_BAO_Block::blockDelete('Address', $params);
1933 }
1934 }
1935
1936 /**
1937 * This function check online pending contribution associated w/
1938 * Online Event Registration or Online Membership signup.
1939 *
1940 * @param int $componentId
1941 * Participant/membership id.
1942 * @param string $componentName
1943 * Event/Membership.
1944 *
1945 * @return int
1946 * pending contribution id.
1947 */
1948 public static function checkOnlinePendingContribution($componentId, $componentName) {
1949 $contributionId = NULL;
1950 if (!$componentId ||
1951 !in_array($componentName, ['Event', 'Membership'])
1952 ) {
1953 return $contributionId;
1954 }
1955
1956 if ($componentName == 'Event') {
1957 $idName = 'participant_id';
1958 $componentTable = 'civicrm_participant';
1959 $paymentTable = 'civicrm_participant_payment';
1960 $source = ts('Online Event Registration');
1961 }
1962
1963 if ($componentName == 'Membership') {
1964 $idName = 'membership_id';
1965 $componentTable = 'civicrm_membership';
1966 $paymentTable = 'civicrm_membership_payment';
1967 $source = ts('Online Contribution');
1968 }
1969
1970 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
1971
1972 $query = "
1973 SELECT component.id as {$idName},
1974 componentPayment.contribution_id as contribution_id,
1975 contribution.source source,
1976 contribution.contribution_status_id as contribution_status_id,
1977 contribution.is_pay_later as is_pay_later
1978 FROM $componentTable component
1979 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1980 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1981 WHERE component.id = {$componentId}";
1982
1983 $dao = CRM_Core_DAO::executeQuery($query);
1984
1985 while ($dao->fetch()) {
1986 if ($dao->contribution_id &&
1987 $dao->is_pay_later &&
1988 $dao->contribution_status_id == $pendingStatusId &&
1989 strpos($dao->source, $source) !== FALSE
1990 ) {
1991 $contributionId = $dao->contribution_id;
1992 }
1993 }
1994
1995 return $contributionId;
1996 }
1997
1998 /**
1999 * Update contribution as well as related objects.
2000 *
2001 * This function by-passes hooks - to address this - don't use this function.
2002 *
2003 * @param array $params
2004 * @param bool $processContributionObject
2005 *
2006 * @return array
2007 *
2008 * @throws CRM_Core_Exception
2009 * @throws \CiviCRM_API3_Exception
2010 * @deprecated
2011 *
2012 * Use api contribute.completetransaction
2013 * For failures use failPayment (preferably exposing by api in the process).
2014 *
2015 */
2016 public static function transitionComponents($params, $processContributionObject = FALSE) {
2017 // get minimum required values.
2018 $contactId = CRM_Utils_Array::value('contact_id', $params);
2019 $componentId = CRM_Utils_Array::value('component_id', $params);
2020 $componentName = CRM_Utils_Array::value('componentName', $params);
2021 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
2022 $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
2023
2024 // if we already processed contribution object pass previous status id.
2025 $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
2026
2027 $updateResult = [];
2028
2029 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2030
2031 // we process only ( Completed, Cancelled, or Failed ) contributions.
2032 if (!$contributionId ||
2033 !in_array($contributionStatusId, [
2034 array_search('Completed', $contributionStatuses),
2035 array_search('Cancelled', $contributionStatuses),
2036 array_search('Failed', $contributionStatuses),
2037 ])
2038 ) {
2039 return $updateResult;
2040 }
2041
2042 if (!$componentName || !$componentId) {
2043 // get the related component details.
2044 $componentDetails = self::getComponentDetails($contributionId);
2045 }
2046 else {
2047 $componentDetails['contact_id'] = $contactId;
2048 $componentDetails['component'] = $componentName;
2049
2050 if ($componentName == 'event') {
2051 $componentDetails['participant'] = $componentId;
2052 }
2053 else {
2054 $componentDetails['membership'] = $componentId;
2055 }
2056 }
2057
2058 if (!empty($componentDetails['contact_id'])) {
2059 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2060 $contributionId,
2061 'contact_id'
2062 );
2063 }
2064
2065 // do check for required ids.
2066 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
2067 return $updateResult;
2068 }
2069
2070 //now we are ready w/ required ids, start processing.
2071
2072 $baseIPN = new CRM_Core_Payment_BaseIPN();
2073
2074 $input = $ids = $objects = [];
2075
2076 $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
2077 $ids['contribution'] = $contributionId;
2078 $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
2079 $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
2080 $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
2081 $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
2082 $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
2083 $ids['contributionRecur'] = NULL;
2084 $ids['contributionPage'] = NULL;
2085
2086 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
2087 CRM_Core_Error::fatal();
2088 }
2089
2090 $memberships = &$objects['membership'];
2091 $participant = &$objects['participant'];
2092 $pledgePayment = &$objects['pledge_payment'];
2093 $contribution = &$objects['contribution'];
2094 $pledgeID = $oldStatus = NULL;
2095 $pledgePaymentIDs = [];
2096 if ($pledgePayment) {
2097 foreach ($pledgePayment as $key => $object) {
2098 $pledgePaymentIDs[] = $object->id;
2099 }
2100 $pledgeID = $pledgePayment[0]->pledge_id;
2101 }
2102
2103 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
2104
2105 if ($participant) {
2106 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
2107 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
2108 $participant->id,
2109 'status_id'
2110 );
2111 }
2112 // we might want to process contribution object.
2113 $processContribution = FALSE;
2114 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2115 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2116 list($updateResult, $processContribution) = self::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2117 }
2118 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2119 if (is_array($memberships)) {
2120 foreach ($memberships as $membership) {
2121 $update = TRUE;
2122 //Update Membership status if there is no other completed contribution associated with the membership.
2123 $relatedContributions = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id, TRUE);
2124 foreach ($relatedContributions as $contriId) {
2125 if ($contriId == $contributionId) {
2126 continue;
2127 }
2128 $statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
2129 if (CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
2130 $update = FALSE;
2131 }
2132 }
2133 if ($membership && $update) {
2134 $membership->status_id = array_search('Expired', $membershipStatuses);
2135 $membership->is_override = TRUE;
2136 $membership->status_override_end_date = 'null';
2137 $membership->save();
2138
2139 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
2140 if ($processContributionObject) {
2141 $processContribution = TRUE;
2142 }
2143 }
2144 }
2145 }
2146 if ($participant) {
2147 $updatedStatusId = array_search('Cancelled', $participantStatuses);
2148 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
2149
2150 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2151 if ($processContributionObject) {
2152 $processContribution = TRUE;
2153 }
2154 }
2155
2156 if ($pledgePayment) {
2157 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2158
2159 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2160 if ($processContributionObject) {
2161 $processContribution = TRUE;
2162 }
2163 }
2164 }
2165 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2166
2167 // only pending contribution related object processed.
2168 if ($previousContriStatusId &&
2169 !in_array($contributionStatuses[$previousContriStatusId], [
2170 'Pending',
2171 'Partially paid',
2172 ])
2173 ) {
2174 // this is case when we already processed contribution object.
2175 return $updateResult;
2176 }
2177 elseif (!$previousContriStatusId &&
2178 !in_array($contributionStatuses[$contribution->contribution_status_id], [
2179 'Pending',
2180 'Partially paid',
2181 ])
2182 ) {
2183 // this is case when we are going to process contribution object later.
2184 return $updateResult;
2185 }
2186
2187 if (is_array($memberships)) {
2188 foreach ($memberships as $membership) {
2189 if ($membership) {
2190 $format = '%Y%m%d';
2191
2192 //CRM-4523
2193 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
2194 $membership->membership_type_id,
2195 $membership->is_test, $membership->id
2196 );
2197
2198 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2199 // this picks up membership type changes during renewals
2200 $sql = "
2201 SELECT membership_type_id
2202 FROM civicrm_membership_log
2203 WHERE membership_id=$membership->id
2204 ORDER BY id DESC
2205 LIMIT 1;";
2206 $dao = new CRM_Core_DAO();
2207 $dao->query($sql);
2208 if ($dao->fetch()) {
2209 if (!empty($dao->membership_type_id)) {
2210 $membership->membership_type_id = $dao->membership_type_id;
2211 $membership->save();
2212 }
2213 }
2214 // else fall back to using current membership type
2215 // Figure out number of terms
2216 $numterms = 1;
2217 $lineitems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId);
2218 foreach ($lineitems as $lineitem) {
2219 if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
2220 $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
2221
2222 // in case membership_num_terms comes through as null or zero
2223 $numterms = $numterms >= 1 ? $numterms : 1;
2224 break;
2225 }
2226 }
2227
2228 // CRM-15735-to update the membership status as per the contribution receive date
2229 $joinDate = NULL;
2230 $oldStatus = $membership->status_id;
2231 if (!empty($params['receive_date'])) {
2232 $joinDate = $params['receive_date'];
2233 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
2234 $membership->end_date,
2235 $membership->join_date,
2236 $params['receive_date'],
2237 FALSE,
2238 $membership->membership_type_id,
2239 (array) $membership
2240 );
2241 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
2242 $membership->save();
2243 }
2244
2245 if ($currentMembership) {
2246 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2247 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
2248 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
2249 }
2250 else {
2251 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms);
2252 }
2253
2254 //get the status for membership.
2255 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
2256 $dates['end_date'],
2257 $dates['join_date'],
2258 'today',
2259 TRUE,
2260 $membership->membership_type_id,
2261 (array) $membership
2262 );
2263
2264 $formattedParams = [
2265 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
2266 array_search('Current', $membershipStatuses)
2267 ),
2268 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
2269 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
2270 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
2271 ];
2272
2273 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
2274
2275 $membership->copyValues($formattedParams);
2276 $membership->save();
2277
2278 //updating the membership log
2279 $membershipLog = [];
2280 $membershipLog = $formattedParams;
2281 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
2282 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
2283
2284 $membershipLog['start_date'] = $logStartDate;
2285 $membershipLog['membership_id'] = $membership->id;
2286 $membershipLog['modified_id'] = $membership->contact_id;
2287 $membershipLog['modified_date'] = date('Ymd');
2288 $membershipLog['membership_type_id'] = $membership->membership_type_id;
2289
2290 CRM_Member_BAO_MembershipLog::add($membershipLog);
2291
2292 //update related Memberships.
2293 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
2294
2295 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2296 $scheduledActivityID = CRM_Utils_Array::value('id',
2297 civicrm_api3('Activity', 'Get',
2298 [
2299 'source_record_id' => $membership->id,
2300 'activity_type_id' => $activityType,
2301 'status_id' => 'Scheduled',
2302 'options' => [
2303 'limit' => 1,
2304 'sort' => 'id DESC',
2305 ],
2306 ]
2307 )
2308 );
2309 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2310 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2311 if ($scheduledActivityID) {
2312 CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $membership->contact_id, ['id' => $scheduledActivityID]);
2313 break;
2314 }
2315 }
2316
2317 // track membership status change if any
2318 if (!empty($oldStatus) && $membership->status_id != $oldStatus) {
2319 $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
2320 CRM_Activity_BAO_Activity::addActivity($membership,
2321 'Change Membership Status',
2322 NULL,
2323 [
2324 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2325 'source_contact_id' => $membershipLog['modified_id'],
2326 'priority_id' => 'Normal',
2327 ]
2328 );
2329 }
2330
2331 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
2332 if ($processContributionObject) {
2333 $processContribution = TRUE;
2334 }
2335
2336 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
2337 }
2338 }
2339 }
2340
2341 if ($participant) {
2342 $updatedStatusId = array_search('Registered', $participantStatuses);
2343 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
2344
2345 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2346 if ($processContributionObject) {
2347 $processContribution = TRUE;
2348 }
2349 }
2350
2351 if ($pledgePayment) {
2352 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2353
2354 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2355 if ($processContributionObject) {
2356 $processContribution = TRUE;
2357 }
2358 }
2359 }
2360
2361 // process contribution object.
2362 if ($processContribution) {
2363 $contributionParams = [];
2364 $fields = [
2365 'contact_id',
2366 'total_amount',
2367 'receive_date',
2368 'is_test',
2369 'campaign_id',
2370 'payment_instrument_id',
2371 'trxn_id',
2372 'invoice_id',
2373 'financial_type_id',
2374 'contribution_status_id',
2375 'non_deductible_amount',
2376 'receipt_date',
2377 'check_number',
2378 ];
2379 foreach ($fields as $field) {
2380 if (empty($params[$field])) {
2381 continue;
2382 }
2383 $contributionParams[$field] = $params[$field];
2384 }
2385
2386 $contributionParams['id'] = $contributionId;
2387 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams);
2388 }
2389
2390 return $updateResult;
2391 }
2392
2393 /**
2394 * Returns all contribution related object ids.
2395 *
2396 * @param $contributionId
2397 *
2398 * @return array
2399 */
2400 public static function getComponentDetails($contributionId) {
2401 $componentDetails = $pledgePayment = [];
2402 if (!$contributionId) {
2403 return $componentDetails;
2404 }
2405
2406 $query = "
2407 SELECT c.id as contribution_id,
2408 c.contact_id as contact_id,
2409 c.contribution_recur_id,
2410 mp.membership_id as membership_id,
2411 m.membership_type_id as membership_type_id,
2412 pp.participant_id as participant_id,
2413 p.event_id as event_id,
2414 pgp.id as pledge_payment_id
2415 FROM civicrm_contribution c
2416 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2417 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2418 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2419 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2420 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2421 WHERE c.id = $contributionId";
2422
2423 $dao = CRM_Core_DAO::executeQuery($query);
2424 $componentDetails = [];
2425
2426 while ($dao->fetch()) {
2427 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
2428 $componentDetails['contact_id'] = $dao->contact_id;
2429 if ($dao->event_id) {
2430 $componentDetails['event'] = $dao->event_id;
2431 }
2432 if ($dao->participant_id) {
2433 $componentDetails['participant'] = $dao->participant_id;
2434 }
2435 if ($dao->membership_id) {
2436 if (!isset($componentDetails['membership'])) {
2437 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2438 }
2439 $componentDetails['membership'][] = $dao->membership_id;
2440 $componentDetails['membership_type'][] = $dao->membership_type_id;
2441 }
2442 if ($dao->pledge_payment_id) {
2443 $pledgePayment[] = $dao->pledge_payment_id;
2444 }
2445 if ($dao->contribution_recur_id) {
2446 $componentDetails['contributionRecur'] = $dao->contribution_recur_id;
2447 }
2448 }
2449
2450 if ($pledgePayment) {
2451 $componentDetails['pledge_payment'] = $pledgePayment;
2452 }
2453
2454 return $componentDetails;
2455 }
2456
2457 /**
2458 * @param int $contactId
2459 * @param bool $includeSoftCredit
2460 *
2461 * @return null|string
2462 */
2463 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2464 if (!$contactId) {
2465 return 0;
2466 }
2467 $financialTypes = CRM_Financial_BAO_FinancialType::getAllAvailableFinancialTypes();
2468 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2469 $liWhere = " AND i.financial_type_id IN (0)";
2470 if (!empty($financialTypes)) {
2471 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2472 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2473 }
2474 $contactContributionsSQL = "
2475 SELECT contribution.id AS id
2476 FROM civicrm_contribution contribution
2477 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2478 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2479 $additionalWhere
2480 AND i.id IS NULL";
2481
2482 $contactSoftCreditContributionsSQL = "
2483 SELECT contribution.id
2484 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2485 ON ( contribution.id = softContribution.contribution_id )
2486 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2487 $query = "SELECT count( x.id ) count FROM ( ";
2488 $query .= $contactContributionsSQL;
2489
2490 if ($includeSoftCredit) {
2491 $query .= " UNION ";
2492 $query .= $contactSoftCreditContributionsSQL;
2493 }
2494
2495 $query .= ") x";
2496
2497 return CRM_Core_DAO::singleValueQuery($query);
2498 }
2499
2500 /**
2501 * Repeat a transaction as part of a recurring series.
2502 *
2503 * The ideal flow is
2504 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2505 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2506 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2507 * and associated entities.
2508 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2509 * which updates the various entities and sends appropriate emails.
2510 *
2511 * Gaps in the above (@todo)
2512 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2513 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2514 * 3) Repeat transaction duplicates rather than calls Order.create
2515 * 4) Use of payment.create still limited - completetransaction is more common.
2516 * 5) the template transaction is tricky - historically we used the first contribution
2517 * linked to a recurring contribution. More recently that was changed to be the most recent.
2518 * Ideally it would be an actual template - not a contribution used as a template which
2519 * would give more appropriate flexibility. Note line_items have an entity so that table
2520 * could be used for the line item template - the difficulty is the custom fields...
2521 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2522 * to load the membership(s) referred to via line items in the template transactions. Any other
2523 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2524 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2525 * - membership_payment record
2526 * - civicrm_membership.contribution_recur_id
2527 * - input override.
2528 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2529 * of historical processors since this has been handled 'forever' - specifically for paypal.
2530 * albeit by an even nastier mechanism than the current input override.
2531 * The count is out on how correct related entities wind up in this case.
2532 *
2533 * @param CRM_Contribute_BAO_Contribution $contribution
2534 * @param array $input
2535 * @param array $contributionParams
2536 * @param int $paymentProcessorID
2537 *
2538 * @return bool
2539 * @throws CiviCRM_API3_Exception
2540 */
2541 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2542 if (!empty($contribution->id)) {
2543 return FALSE;
2544 }
2545 if (empty($contribution->id)) {
2546 // Unclear why this would only be set for repeats.
2547 if (!empty($input['amount'])) {
2548 $contribution->total_amount = $contributionParams['total_amount'] = $input['amount'];
2549 }
2550
2551 if (!empty($contributionParams['contribution_recur_id'])) {
2552 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2553 'id' => $contributionParams['contribution_recur_id'],
2554 ]);
2555 if (!empty($recurringContribution['campaign_id'])) {
2556 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2557 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2558 }
2559 if (!empty($recurringContribution['financial_type_id'])) {
2560 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2561 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2562 }
2563 }
2564 $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution(
2565 $contributionParams['contribution_recur_id'],
2566 array_intersect_key($contributionParams, [
2567 'total_amount' => TRUE,
2568 'financial_type_id' => TRUE,
2569 ])
2570 );
2571 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2572
2573 $contributionParams['status_id'] = 'Pending';
2574 if (isset($contributionParams['financial_type_id'])) {
2575 // Give precedence to passed in type.
2576 $contribution->financial_type_id = $contributionParams['financial_type_id'];
2577 }
2578 else {
2579 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2580 }
2581 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2582 $contributionParams['source'] = empty($templateContribution['source']) ? ts('Recurring contribution') : $templateContribution['source'];
2583
2584 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2585 //do not create CC or BCC emails or profile notifications.
2586 //The if is just to be safe. Not sure if we can ever arrive with this unset
2587 // but per CRM-19478 it seems it can be 'null'
2588 if (isset($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) {
2589 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id;
2590 }
2591 if (!empty($contribution->tax_amount)) {
2592 $contributionParams['tax_amount'] = $contribution->tax_amount;
2593 }
2594
2595 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2596 $contribution->id = $createContribution['id'];
2597 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id);
2598 self::handleMembershipIDOverride($contribution->id, $input);
2599 return TRUE;
2600 }
2601 }
2602
2603 /**
2604 * Get individual id for onbehalf contribution.
2605 *
2606 * @param int $contributionId
2607 * Contribution id.
2608 * @param int $contributorId
2609 * Contributor id.
2610 *
2611 * @return array
2612 * containing organization id and individual id
2613 */
2614 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2615
2616 $ids = [];
2617
2618 if (!$contributionId) {
2619 return $ids;
2620 }
2621
2622 // fetch contributor id if null
2623 if (!$contributorId) {
2624 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2625 $contributionId, 'contact_id'
2626 );
2627 }
2628
2629 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
2630 $activityTypeId = array_search('Contribution', $activityTypeIds);
2631
2632 if ($activityTypeId && $contributorId) {
2633 $activityQuery = "
2634 SELECT civicrm_activity_contact.contact_id
2635 FROM civicrm_activity_contact
2636 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2637 WHERE civicrm_activity.activity_type_id = %1
2638 AND civicrm_activity.source_record_id = %2
2639 AND civicrm_activity_contact.record_type_id = %3
2640 ";
2641
2642 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2643 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2644
2645 $params = [
2646 1 => [$activityTypeId, 'Integer'],
2647 2 => [$contributionId, 'Integer'],
2648 3 => [$sourceID, 'Integer'],
2649 ];
2650
2651 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
2652
2653 // for on behalf contribution source is individual and contributor is organization
2654 if ($sourceContactId && $sourceContactId != $contributorId) {
2655 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
2656 // get rel type id for employee of relation
2657 foreach ($relationshipTypeIds as $id => $typeVals) {
2658 if ($typeVals['name_a_b'] == 'Employee of') {
2659 $relationshipTypeId = $id;
2660 break;
2661 }
2662 }
2663
2664 $rel = new CRM_Contact_DAO_Relationship();
2665 $rel->relationship_type_id = $relationshipTypeId;
2666 $rel->contact_id_a = $sourceContactId;
2667 $rel->contact_id_b = $contributorId;
2668 if ($rel->find(TRUE)) {
2669 $ids['individual_id'] = $rel->contact_id_a;
2670 $ids['organization_id'] = $rel->contact_id_b;
2671 }
2672 }
2673 }
2674
2675 return $ids;
2676 }
2677
2678 /**
2679 * @return array
2680 */
2681 public static function getContributionDates() {
2682 $config = CRM_Core_Config::singleton();
2683 $currentMonth = date('m');
2684 $currentDay = date('d');
2685 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
2686 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
2687 (int ) $config->fiscalYearStart['d'] > $currentDay
2688 )
2689 ) {
2690 $year = date('Y') - 1;
2691 }
2692 else {
2693 $year = date('Y');
2694 }
2695 $year = ['Y' => $year];
2696 $yearDate = $config->fiscalYearStart;
2697 $yearDate = array_merge($year, $yearDate);
2698 $yearDate = CRM_Utils_Date::format($yearDate);
2699
2700 $monthDate = date('Ym') . '01';
2701
2702 $now = date('Ymd');
2703
2704 return [
2705 'now' => $now,
2706 'yearDate' => $yearDate,
2707 'monthDate' => $monthDate,
2708 ];
2709 }
2710
2711 /**
2712 * Load objects relations to contribution object.
2713 * Objects are stored in the $_relatedObjects property
2714 * In the first instance we are just moving functionality from BASEIpn -
2715 *
2716 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2717 *
2718 * Note that the unit test for the BaseIPN class tests this function
2719 *
2720 * @param array $input
2721 * Input as delivered from Payment Processor.
2722 * @param array $ids
2723 * Ids as Loaded by Payment Processor.
2724 * @param bool $loadAll
2725 * Load all related objects - even where id not passed in? (allows API to call this).
2726 *
2727 * @return bool
2728 * @throws Exception
2729 */
2730 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2731 // @todo deprecate this function - the steps should be
2732 // 1) add additional functions like 'getRelatedMemberships'
2733 // 2) switch all calls that refer to ->_relatedObjects to
2734 // using the helper functions
2735 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2736 // 4) make ->_relatedObjects protected
2737 // 5) hone up the individual functions to not use rely on this having been called
2738 // 6) deprecate like mad
2739 if ($loadAll) {
2740 $ids = array_merge($this->getComponentDetails($this->id), $ids);
2741 if (empty($ids['contact']) && isset($this->contact_id)) {
2742 $ids['contact'] = $this->contact_id;
2743 }
2744 }
2745 if (empty($this->_component)) {
2746 if (!empty($ids['event'])) {
2747 $this->_component = 'event';
2748 }
2749 else {
2750 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
2751 }
2752 }
2753
2754 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2755 // refactoring than anything else, and has unit test coverage.
2756 if (empty($this->financial_type_id)) {
2757 $this->find(TRUE);
2758 }
2759
2760 $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value(
2761 'paymentProcessor',
2762 $ids
2763 ));
2764
2765 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id) {
2766 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2767 $this->contribution_page_id,
2768 'payment_processor'
2769 );
2770 if ($paymentProcessorID) {
2771 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2772 }
2773 }
2774
2775 $ids['contributionType'] = $this->financial_type_id;
2776 $ids['financialType'] = $this->financial_type_id;
2777 if ($this->contribution_page_id) {
2778 $ids['contributionPage'] = $this->contribution_page_id;
2779 }
2780
2781 $this->loadRelatedEntitiesByID($ids);
2782
2783 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2784 $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id;
2785 }
2786
2787 if (!empty($ids['pledge_payment'])) {
2788 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2789 if (empty($paymentID)) {
2790 continue;
2791 }
2792 $payment = new CRM_Pledge_BAO_PledgePayment();
2793 $payment->id = $paymentID;
2794 if (!$payment->find(TRUE)) {
2795 throw new Exception("Could not find pledge payment record: " . $paymentID);
2796 }
2797 $this->_relatedObjects['pledge_payment'][] = $payment;
2798 }
2799 }
2800
2801 // These are probably no longer accessed from anywhere
2802 // @todo remove this line, after ensuring not used.
2803 $ids = $this->loadRelatedMembershipObjects($ids);
2804
2805 if ($this->_component != 'contribute') {
2806 // we are in event mode
2807 // make sure event exists and is valid
2808 $event = new CRM_Event_BAO_Event();
2809 $event->id = $ids['event'];
2810 if ($ids['event'] &&
2811 !$event->find(TRUE)
2812 ) {
2813 throw new Exception("Could not find event: " . $ids['event']);
2814 }
2815
2816 $this->_relatedObjects['event'] = &$event;
2817
2818 $participant = new CRM_Event_BAO_Participant();
2819 $participant->id = $ids['participant'];
2820 if ($ids['participant'] &&
2821 !$participant->find(TRUE)
2822 ) {
2823 throw new Exception("Could not find participant: " . $ids['participant']);
2824 }
2825 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2826
2827 $this->_relatedObjects['participant'] = &$participant;
2828
2829 // get the payment processor id from event - this is inaccurate see CRM-16923
2830 // in future we should look at throwing an exception here rather than an dubious guess.
2831 if (!$paymentProcessorID) {
2832 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
2833 if ($paymentProcessorID) {
2834 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2835 }
2836 }
2837 }
2838
2839 if ($paymentProcessorID) {
2840 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2841 $this->is_test ? 'test' : 'live'
2842 );
2843 $ids['paymentProcessor'] = $paymentProcessorID;
2844 $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
2845 }
2846
2847 // Add contribution id to $ids. CRM-20401
2848 $ids['contribution'] = $this->id;
2849 return TRUE;
2850 }
2851
2852 /**
2853 * Create array of message information - ie. return html version, txt version, to field
2854 *
2855 * @param array $input
2856 * Incoming information.
2857 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2858 * just check presence of recur object but maintaining legacy approach
2859 * to be careful)
2860 * @param array $ids
2861 * IDs of related objects.
2862 * @param array $values
2863 * Any values that may have already been compiled by calling process.
2864 * This is augmented by values 'gathered' by gatherMessageValues
2865 * @param bool $returnMessageText
2866 * Distinguishes between whether to send message or return.
2867 * message text. We are working towards this function ALWAYS returning message text & calling
2868 * function doing emails / pdfs with it
2869 *
2870 * @return array
2871 * messages
2872 * @throws Exception
2873 */
2874 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2875 $this->loadRelatedObjects($input, $ids);
2876
2877 if (empty($this->_component)) {
2878 $this->_component = CRM_Utils_Array::value('component', $input);
2879 }
2880
2881 //not really sure what params might be passed in but lets merge em into values
2882 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2883 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2884 if (!empty($input['receipt_date'])) {
2885 $values['receipt_date'] = $input['receipt_date'];
2886 }
2887
2888 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2889 //what does recur 'mean here - to do with payment processor return functionality but
2890 // what is the importance
2891 if (!empty($this->contribution_recur_id) && !empty($this->_relatedObjects['paymentProcessor'])) {
2892 $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']);
2893
2894 $entityID = $entity = NULL;
2895 if (isset($ids['contribution'])) {
2896 $entity = 'contribution';
2897 $entityID = $ids['contribution'];
2898 }
2899 if (!empty($ids['membership'])) {
2900 //not sure whether is is possible for this not to be an array - load related contacts loads an array but this code was expecting a string
2901 // the addition of the casting is in case it could get here & be a string. Added in 4.6 - maybe remove later? This AuthorizeNetIPN & PaypalIPN tests hit this
2902 // line having loaded an array
2903 $ids['membership'] = (array) $ids['membership'];
2904 $entity = 'membership';
2905 $entityID = $ids['membership'][0];
2906 }
2907
2908 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2909 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2910 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2911
2912 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2913 //direct mode showing billing block, so use directIPN for temporary
2914 $template->assign('contributeMode', 'directIPN');
2915 }
2916 }
2917 // todo remove strtolower - check consistency
2918 if (strtolower($this->_component) == 'event') {
2919 $eventParams = ['id' => $this->_relatedObjects['participant']->event_id];
2920 $values['event'] = [];
2921
2922 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2923
2924 //get location details
2925 $locationParams = [
2926 'entity_id' => $this->_relatedObjects['participant']->event_id,
2927 'entity_table' => 'civicrm_event',
2928 ];
2929 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2930
2931 $ufJoinParams = [
2932 'entity_table' => 'civicrm_event',
2933 'entity_id' => $ids['event'],
2934 'module' => 'CiviEvent',
2935 ];
2936
2937 list($custom_pre_id,
2938 $custom_post_ids
2939 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2940
2941 $values['custom_pre_id'] = $custom_pre_id;
2942 $values['custom_post_id'] = $custom_post_ids;
2943 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2944 //and cases involving status updation through ipn
2945 // whatever that means!
2946 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2947 // perhaps we should throw an e-notice if amount is set & force total_amount?
2948 if (!empty($input['amount'])) {
2949 $values['totalAmount'] = $input['amount'];
2950 }
2951 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2952 if ($values['event']['is_email_confirm']) {
2953 $values['is_email_receipt'] = 1;
2954 }
2955
2956 if (!empty($ids['contribution'])) {
2957 $values['contributionId'] = $ids['contribution'];
2958 }
2959
2960 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2961 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2962 );
2963 }
2964 else {
2965 $values['contribution_id'] = $this->id;
2966 if (!empty($ids['related_contact'])) {
2967 $values['related_contact'] = $ids['related_contact'];
2968 if (isset($ids['onbehalf_dupe_alert'])) {
2969 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2970 }
2971 $entityBlock = [
2972 'contact_id' => $ids['contact'],
2973 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2974 'Home', 'id', 'name'
2975 ),
2976 ];
2977 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2978 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2979 }
2980 $isTest = FALSE;
2981 if ($this->is_test) {
2982 $isTest = TRUE;
2983 }
2984 if (!empty($this->_relatedObjects['membership'])) {
2985 foreach ($this->_relatedObjects['membership'] as $membership) {
2986 if ($membership->id) {
2987 $values['membership_id'] = $membership->id;
2988 $values['isMembership'] = TRUE;
2989 $values['membership_assign'] = TRUE;
2990
2991 // need to set the membership values here
2992 $template->assign('membership_name',
2993 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2994 );
2995 $template->assign('mem_start_date', $membership->start_date);
2996 $template->assign('mem_join_date', $membership->join_date);
2997 $template->assign('mem_end_date', $membership->end_date);
2998 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2999 $template->assign('mem_status', $membership_status);
3000 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
3001 $values['is_pay_later'] = 1;
3002 }
3003 // Pass amount to floatval as string '0.00' is considered a
3004 // valid amount and includes Fee section in the mail.
3005 if (isset($values['amount'])) {
3006 $values['amount'] = floatval($values['amount']);
3007 }
3008
3009 if (!empty($this->contribution_recur_id) && $paymentObject) {
3010 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'cancel');
3011 $template->assign('cancelSubscriptionUrl', $url);
3012 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
3013 $template->assign('updateSubscriptionBillingUrl', $url);
3014 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3015 $template->assign('updateSubscriptionUrl', $url);
3016 }
3017
3018 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3019
3020 return $result;
3021 // otherwise if its about sending emails, continue sending without return, as we
3022 // don't want to exit the loop.
3023 }
3024 }
3025 }
3026 else {
3027 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3028 }
3029 }
3030 }
3031
3032 /**
3033 * Gather values for contribution mail - this function has been created
3034 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3035 * Values related to the contribution in question are gathered
3036 *
3037 * @param array $input
3038 * Input into function (probably from payment processor).
3039 * @param array $values
3040 * @param array $ids
3041 * The set of ids related to the input.
3042 *
3043 * @return array
3044 * @throws \CRM_Core_Exception
3045 */
3046 public function _gatherMessageValues($input, &$values, $ids = []) {
3047 // set display address of contributor
3048 $values['billingName'] = '';
3049 if ($this->address_id) {
3050 $addressDetails = CRM_Core_BAO_Address::getValues(['id' => $this->address_id], FALSE, 'id');
3051 $addressDetails = reset($addressDetails);
3052 $values['billingName'] = $addressDetails['name'] ?? '';
3053 }
3054 // Else we assign the billing address of the contribution contact.
3055 else {
3056 $addressDetails = (array) CRM_Core_BAO_Address::getValues(['contact_id' => $this->contact_id, 'is_billing' => 1]);
3057 $addressDetails = reset($addressDetails);
3058 }
3059 $values['address'] = $addressDetails['display'] ?? '';
3060
3061 if ($this->_component === 'contribute') {
3062 //get soft contributions
3063 $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id, TRUE);
3064 if (!empty($softContributions)) {
3065 $values['softContributions'] = $softContributions['soft_credit'];
3066 }
3067 if (isset($this->contribution_page_id)) {
3068 // This is a call we want to use less, in favour of loading related objects.
3069 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3070 if ($this->contribution_page_id) {
3071 // This is precautionary as there are some legacy flows, but it should really be
3072 // loaded by now.
3073 if (!isset($this->_relatedObjects['contributionPage'])) {
3074 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id]);
3075 }
3076 CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($values);
3077 }
3078 }
3079 // no contribution page -probably back office
3080 else {
3081 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3082 $values['title'] = 'Contribution';
3083 }
3084 // set lineItem for contribution
3085 if ($this->id) {
3086 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->id);
3087 if (!empty($lineItems)) {
3088 $firstLineItem = reset($lineItems);
3089 $priceSet = [];
3090 if (!empty($firstLineItem['price_set_id'])) {
3091 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3092 'id' => $firstLineItem['price_set_id'],
3093 'return' => 'is_quick_config, id',
3094 ]);
3095 $values['priceSetID'] = $priceSet['id'];
3096 }
3097 foreach ($lineItems as &$eachItem) {
3098 if (isset($this->_relatedObjects['membership'])
3099 && is_array($this->_relatedObjects['membership'])
3100 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
3101 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
3102 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
3103 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
3104 }
3105 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3106 // However, that does create upgrade pain so would be better to be phased in.
3107 $values['useForMember'] = empty($priceSet['is_quick_config']);
3108 }
3109 $values['lineItem'][0] = $lineItems;
3110 }
3111 }
3112
3113 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
3114 $this->id,
3115 $this->contact_id
3116 );
3117 // if this is onbehalf of contribution then set related contact
3118 if (!empty($relatedContact['individual_id'])) {
3119 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3120 }
3121 }
3122 else {
3123 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects['participant']->id, $this->id));
3124 }
3125
3126 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', NULL, $this->id);
3127
3128 $customGroup = [];
3129 foreach ($groupTree as $key => $group) {
3130 if ($key === 'info') {
3131 continue;
3132 }
3133
3134 foreach ($group['fields'] as $k => $customField) {
3135 $groupLabel = $group['title'];
3136 if (!empty($customField['customValue'])) {
3137 foreach ($customField['customValue'] as $customFieldValues) {
3138 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
3139 }
3140 }
3141 }
3142 }
3143 $values['customGroup'] = $customGroup;
3144
3145 $values['is_pay_later'] = $this->is_pay_later;
3146
3147 return $values;
3148 }
3149
3150 /**
3151 * Assign message variables to template but try to break the habit.
3152 *
3153 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3154 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3155 * multiple recurring payments for processors like IATS that use tokens.
3156 *
3157 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3158 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3159 * Note we send directly from this function in some cases because it is only partly refactored.
3160 *
3161 * Don't call this function directly as the signature will change.
3162 *
3163 * @param $values
3164 * @param $input
3165 * @param bool $returnMessageText
3166 *
3167 * @return mixed
3168 */
3169 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3170 // @todo - this should have a better separation of concerns - ie.
3171 // gatherMessageValues should build an array of values to be assigned to the template
3172 // and this function should assign them (assigning null if not set).
3173 // the way the pcpParams & honor Params section works is a baby-step towards this.
3174 $template = CRM_Core_Smarty::singleton();
3175 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
3176 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
3177 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
3178 $template->assign('billingName', $values['billingName']);
3179
3180 // For some unit tests contribution cannot contain paymentProcessor information
3181 $billingMode = empty($this->_relatedObjects['paymentProcessor']) ? CRM_Core_Payment::BILLING_MODE_NOTIFY : $this->_relatedObjects['paymentProcessor']['billing_mode'];
3182 $template->assign('contributeMode', CRM_Utils_Array::value($billingMode, CRM_Core_SelectValues::contributeMode()));
3183
3184 //assign honor information to receipt message
3185 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
3186
3187 $honorParams = [
3188 'soft_credit_type' => NULL,
3189 'honor_block_is_active' => NULL,
3190 ];
3191 if (isset($softRecord['soft_credit'])) {
3192 //if id of contribution page is present
3193 if (!empty($values['id'])) {
3194 $values['honor'] = [
3195 'honor_profile_values' => [],
3196 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3197 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3198 ];
3199
3200 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3201 $honorParams['honor_block_is_active'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3202 }
3203 else {
3204 //offline contribution
3205 $softCreditTypes = $softCredits = [];
3206 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3207 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3208 $softCredits[$key] = [
3209 'Name' => $softCredit['contact_name'],
3210 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
3211 ];
3212 }
3213 $template->assign('softCreditTypes', $softCreditTypes);
3214 $template->assign('softCredits', $softCredits);
3215 }
3216 }
3217
3218 $dao = new CRM_Contribute_DAO_ContributionProduct();
3219 $dao->contribution_id = $this->id;
3220 if ($dao->find(TRUE)) {
3221 $premiumId = $dao->product_id;
3222 $template->assign('option', $dao->product_option);
3223
3224 $productDAO = new CRM_Contribute_DAO_Product();
3225 $productDAO->id = $premiumId;
3226 $productDAO->find(TRUE);
3227 $template->assign('selectPremium', TRUE);
3228 $template->assign('product_name', $productDAO->name);
3229 $template->assign('price', $productDAO->price);
3230 $template->assign('sku', $productDAO->sku);
3231 }
3232 $template->assign('title', CRM_Utils_Array::value('title', $values));
3233 $values['amount'] = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
3234 if (!$values['amount'] && isset($this->total_amount)) {
3235 $values['amount'] = $this->total_amount;
3236 }
3237
3238 $pcpParams = [
3239 'pcpBlock' => NULL,
3240 'pcp_display_in_roll' => NULL,
3241 'pcp_roll_nickname' => NULL,
3242 'pcp_personal_note' => NULL,
3243 'title' => NULL,
3244 ];
3245
3246 if (strtolower($this->_component) == 'contribute') {
3247 //PCP Info
3248 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3249 $softDAO->contribution_id = $this->id;
3250 if ($softDAO->find(TRUE)) {
3251 $pcpParams['pcpBlock'] = TRUE;
3252 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll;
3253 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname;
3254 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note;
3255
3256 //assign the pcp page title for email subject
3257 $pcpDAO = new CRM_PCP_DAO_PCP();
3258 $pcpDAO->id = $softDAO->pcp_id;
3259 if ($pcpDAO->find(TRUE)) {
3260 $pcpParams['title'] = $pcpDAO->title;
3261 }
3262 }
3263 }
3264 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3265 $template->assign($templateKey, $templateValue);
3266 }
3267
3268 if ($this->financial_type_id) {
3269 $values['financial_type_id'] = $this->financial_type_id;
3270 }
3271
3272 $template->assign('trxn_id', $this->trxn_id);
3273 $template->assign('receive_date',
3274 CRM_Utils_Date::processDate($this->receive_date)
3275 );
3276 $values['receipt_date'] = (empty($this->receipt_date) ? NULL : $this->receipt_date);
3277 $template->assign('action', $this->is_test ? 1024 : 1);
3278 $template->assign('receipt_text',
3279 CRM_Utils_Array::value('receipt_text',
3280 $values
3281 )
3282 );
3283 $template->assign('is_monetary', 1);
3284 $template->assign('is_recur', !empty($this->contribution_recur_id));
3285 $template->assign('currency', $this->currency);
3286 $template->assign('address', CRM_Utils_Address::format($input));
3287 if (!empty($values['customGroup'])) {
3288 $template->assign('customGroup', $values['customGroup']);
3289 }
3290 if (!empty($values['softContributions'])) {
3291 $template->assign('softContributions', $values['softContributions']);
3292 }
3293 if ($this->_component == 'event') {
3294 $template->assign('title', $values['event']['title']);
3295 $participantRoles = CRM_Event_PseudoConstant::participantRole();
3296 $viewRoles = [];
3297 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
3298 $viewRoles[] = $participantRoles[$v];
3299 }
3300 $values['event']['participant_role'] = implode(', ', $viewRoles);
3301 $template->assign('event', $values['event']);
3302 $template->assign('participant', $values['participant']);
3303 $template->assign('location', $values['location']);
3304 $template->assign('customPre', $values['custom_pre_id']);
3305 $template->assign('customPost', $values['custom_post_id']);
3306
3307 $isTest = FALSE;
3308 if ($this->_relatedObjects['participant']->is_test) {
3309 $isTest = TRUE;
3310 }
3311
3312 $values['params'] = [];
3313 //to get email of primary participant.
3314 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
3315 $primaryAmount[] = [
3316 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
3317 'amount' => $this->_relatedObjects['participant']->fee_amount,
3318 ];
3319 //build an array of cId/pId of participants
3320 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
3321 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
3322 //send receipt to additional participant if exists
3323 if (count($additionalIDs)) {
3324 $template->assign('isPrimary', 0);
3325 $template->assign('customProfile', NULL);
3326 //set additionalParticipant true
3327 $values['params']['additionalParticipant'] = TRUE;
3328 foreach ($additionalIDs as $pId => $cId) {
3329 $amount = [];
3330 //to change the status pending to completed
3331 $additional = new CRM_Event_DAO_Participant();
3332 $additional->id = $pId;
3333 $additional->contact_id = $cId;
3334 $additional->find(TRUE);
3335 $additional->register_date = $this->_relatedObjects['participant']->register_date;
3336 $additional->status_id = 1;
3337 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
3338 //if additional participant dont have email
3339 //use display name.
3340 if (!$additionalParticipantInfo) {
3341 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
3342 }
3343 $amount[0] = [
3344 'label' => $additional->fee_level,
3345 'amount' => $additional->fee_amount,
3346 ];
3347 $primaryAmount[] = [
3348 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
3349 'amount' => $additional->fee_amount,
3350 ];
3351 $additional->save();
3352 $template->assign('amount', $amount);
3353 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3354 }
3355 }
3356
3357 //build an array of custom profile and assigning it to template
3358 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
3359
3360 if (count($customProfile)) {
3361 $template->assign('customProfile', $customProfile);
3362 }
3363
3364 // for primary contact
3365 $values['params']['additionalParticipant'] = FALSE;
3366 $template->assign('isPrimary', 1);
3367 $template->assign('amount', $primaryAmount);
3368 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
3369 if ($this->payment_instrument_id) {
3370 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
3371 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
3372 }
3373 // carry paylater, since we did not created billing,
3374 // so need to pull email from primary location, CRM-4395
3375 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
3376 }
3377 return $template;
3378 }
3379
3380 /**
3381 * Check whether payment processor supports
3382 * cancellation of contribution subscription
3383 *
3384 * @param int $contributionId
3385 * Contribution id.
3386 *
3387 * @param bool $isNotCancelled
3388 *
3389 * @return bool
3390 */
3391 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3392 $cacheKeyString = "$contributionId";
3393 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
3394
3395 static $supportsCancel = [];
3396
3397 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3398 $supportsCancel[$cacheKeyString] = FALSE;
3399 $isCancelled = FALSE;
3400
3401 if ($isNotCancelled) {
3402 $isCancelled = self::isSubscriptionCancelled($contributionId);
3403 }
3404
3405 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
3406 if (!empty($paymentObject)) {
3407 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3408 }
3409 }
3410 return $supportsCancel[$cacheKeyString];
3411 }
3412
3413 /**
3414 * Check whether subscription is already cancelled.
3415 *
3416 * @param int $contributionId
3417 * Contribution id.
3418 *
3419 * @return string
3420 * contribution status
3421 */
3422 public static function isSubscriptionCancelled($contributionId) {
3423 $sql = "
3424 SELECT cr.contribution_status_id
3425 FROM civicrm_contribution_recur cr
3426 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3427 WHERE con.id = %1 LIMIT 1";
3428 $params = [1 => [$contributionId, 'Integer']];
3429 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
3430 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name');
3431 if ($status == 'Cancelled') {
3432 return TRUE;
3433 }
3434 return FALSE;
3435 }
3436
3437 /**
3438 * Create all financial accounts entry.
3439 *
3440 * @param array $params
3441 * Contribution object, line item array and params for trxn.
3442 *
3443 *
3444 * @param array $financialTrxnValues
3445 *
3446 * @return null|\CRM_Core_BAO_FinancialTrxn
3447 */
3448 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3449 $skipRecords = $update = $return = $isRelatedId = FALSE;
3450
3451 $additionalParticipantId = [];
3452 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3453 $contributionStatus = empty($params['contribution_status_id']) ? NULL : $contributionStatuses[$params['contribution_status_id']];
3454
3455 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
3456 $entityId = $params['participant_id'];
3457 $entityTable = 'civicrm_participant';
3458 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
3459 }
3460 elseif (!empty($params['membership_id'])) {
3461 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3462 // are created off one contribution should be handled elsewhere
3463 $entityId = $params['membership_id'];
3464 $entityTable = 'civicrm_membership';
3465 }
3466 else {
3467 $entityId = $params['contribution']->id;
3468 $entityTable = 'civicrm_contribution';
3469 }
3470
3471 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
3472 $isRelatedId = TRUE;
3473 }
3474
3475 $entityID[] = $entityId;
3476 if (!empty($additionalParticipantId)) {
3477 $entityID += $additionalParticipantId;
3478 }
3479 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3480 if (empty($params['prevContribution'])) {
3481 $entityID = NULL;
3482 }
3483 else {
3484 $update = TRUE;
3485 }
3486
3487 $statusId = $params['contribution']->contribution_status_id;
3488 // CRM-13964 partial payment
3489 if ($contributionStatus == 'Partially paid'
3490 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3491 ) {
3492 $partialAmtPay = CRM_Utils_Rule::cleanMoney($params['partial_amount_to_pay']);
3493 $partialAmtTotal = CRM_Utils_Rule::cleanMoney($params['partial_payment_total']);
3494
3495 $fromFinancialAccountId = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3496 $statusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3497 $params['total_amount'] = $partialAmtPay;
3498
3499 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']);
3500 if (empty($balanceTrxnInfo['trxn_id'])) {
3501 // create new balance transaction record
3502 $toFinancialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3503
3504 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3505 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3506 $balanceTrxnParams['contribution_id'] = $params['contribution']->id;
3507 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis');
3508 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
3509 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
3510 $balanceTrxnParams['currency'] = $params['contribution']->currency;
3511 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id;
3512 $balanceTrxnParams['status_id'] = $statusId;
3513 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3514 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
3515 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $params);
3516 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array::value('card_type_id', $params);
3517 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3518 ($statusId == array_search('Completed', $contributionStatuses) || $statusId == array_search('Partially paid', $contributionStatuses))
3519 ) {
3520 $balanceTrxnParams['is_payment'] = 1;
3521 }
3522 if (!empty($params['payment_processor'])) {
3523 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3524 }
3525 $financialTxn = CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
3526 }
3527 }
3528
3529 // build line item array if its not set in $params
3530 if (empty($params['line_item']) || $additionalParticipantId) {
3531 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3532 }
3533
3534 if ($contributionStatus != 'Failed' &&
3535 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later)
3536 ) {
3537 $skipRecords = TRUE;
3538 $pendingStatus = [
3539 'Pending',
3540 'In Progress',
3541 ];
3542 if (in_array($contributionStatus, $pendingStatus)) {
3543 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
3544 $params['financial_type_id'],
3545 'Accounts Receivable Account is'
3546 );
3547 }
3548 elseif (!empty($params['payment_processor'])) {
3549 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3550 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3551 'id' => $params['payment_processor'],
3552 'return' => 'payment_instrument_id',
3553 ]);
3554 }
3555 elseif (!empty($params['payment_instrument_id'])) {
3556 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
3557 }
3558 else {
3559 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3560 $queryParams = [1 => [$relationTypeId, 'Integer']];
3561 $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3562 }
3563
3564 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
3565 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3566 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
3567 }
3568 //build financial transaction params
3569 $trxnParams = [
3570 'contribution_id' => $params['contribution']->id,
3571 'to_financial_account_id' => $params['to_financial_account_id'],
3572 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'),
3573 'total_amount' => $totalAmount,
3574 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
3575 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount),
3576 'currency' => $params['contribution']->currency,
3577 'trxn_id' => $params['contribution']->trxn_id,
3578 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3579 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3580 // this should really default to completed (after discussion).
3581 'status_id' => $statusId,
3582 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id),
3583 'check_number' => CRM_Utils_Array::value('check_number', $params),
3584 'pan_truncation' => CRM_Utils_Array::value('pan_truncation', $params),
3585 'card_type_id' => CRM_Utils_Array::value('card_type_id', $params),
3586 ];
3587 if ($contributionStatus == 'Refunded' || $contributionStatus == 'Chargeback' || $contributionStatus == 'Cancelled') {
3588 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date) ? $params['contribution']->cancel_date : date('YmdHis');
3589 if (isset($params['refund_trxn_id'])) {
3590 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3591 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3592 }
3593 }
3594 //CRM-16259, set is_payment flag for non pending status
3595 if (!in_array($contributionStatus, $pendingStatus)) {
3596 $trxnParams['is_payment'] = 1;
3597 }
3598 if (!empty($params['payment_processor'])) {
3599 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3600 }
3601
3602 if (isset($fromFinancialAccountId)) {
3603 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3604 }
3605
3606 // consider external values passed for recording transaction entry
3607 if (!empty($financialTrxnValues)) {
3608 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3609 }
3610 if (empty($trxnParams['payment_processor_id'])) {
3611 unset($trxnParams['payment_processor_id']);
3612 }
3613
3614 $params['trxnParams'] = $trxnParams;
3615
3616 if (!empty($params['prevContribution'])) {
3617 $updated = FALSE;
3618 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
3619 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
3620 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
3621 if (!isset($params['trxnParams']['trxn_id'])) {
3622 // Actually I have no idea why we are overwriting any values from the previous contribution.
3623 // (filling makes sense to me). However, only protecting this value as I really really know we
3624 // don't want this one overwritten.
3625 // CRM-17751.
3626 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
3627 }
3628 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
3629
3630 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
3631 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
3632 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
3633 ) {
3634 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
3635 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
3636 }
3637
3638 //if financial type is changed
3639 if (!empty($params['financial_type_id']) &&
3640 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
3641 ) {
3642 $accountRelationship = 'Income Account is';
3643 if (!empty($params['revenue_recognition_date']) || $params['prevContribution']->revenue_recognition_date) {
3644 $accountRelationship = 'Deferred Revenue Account is';
3645 }
3646 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id, $accountRelationship);
3647 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3648 if ($oldFinancialAccount != $newFinancialAccount) {
3649 $params['total_amount'] = 0;
3650 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
3651 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
3652 $params['prevContribution']->financial_type_id, $accountRelationship);
3653 }
3654 else {
3655 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
3656 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3657 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3658 }
3659 }
3660 self::updateFinancialAccounts($params, 'changeFinancialType');
3661 $params['skipLineItem'] = FALSE;
3662 foreach ($params['line_item'] as &$lineItems) {
3663 foreach ($lineItems as &$line) {
3664 $line['financial_type_id'] = $params['financial_type_id'];
3665 }
3666 }
3667 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3668 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3669 $params['financial_account_id'] = $newFinancialAccount;
3670 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3671 self::updateFinancialAccounts($params);
3672 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE);
3673 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3674 $updated = TRUE;
3675 $params['deferred_financial_account_id'] = $newFinancialAccount;
3676 }
3677 }
3678
3679 //Update contribution status
3680 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
3681 if (!isset($params['refund_trxn_id'])) {
3682 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3683 // gets preference over another so I am only 'protecting' a very specific tested flow
3684 // and letting natural justice take care of the rest.
3685 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3686 }
3687 if (!empty($params['contribution_status_id']) &&
3688 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3689 ) {
3690 //Update Financial Records
3691 $callUpdateFinancialAccounts = self::updateFinancialAccountsOnContributionStatusChange($params);
3692 if ($callUpdateFinancialAccounts) {
3693 self::updateFinancialAccounts($params, 'changedStatus');
3694 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3695 }
3696 $updated = TRUE;
3697 }
3698
3699 // change Payment Instrument for a Completed contribution
3700 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3701 // instrument is null and now new payment instrument is added along with the payment
3702 if (!$params['contribution']->payment_instrument_id) {
3703 $params['contribution']->find(TRUE);
3704 }
3705 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3706 $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params);
3707
3708 if (self::isPaymentInstrumentChange($params, $pendingStatus)) {
3709 $updated = CRM_Core_BAO_FinancialTrxn::updateFinancialAccountsOnPaymentInstrumentChange($params);
3710 }
3711
3712 //if Change contribution amount
3713 $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
3714 $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
3715 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3716 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3717 if (isset($totalAmount) &&
3718 $totalAmount != $params['prevContribution']->total_amount
3719 ) {
3720 //Update Financial Records
3721 $params['trxnParams']['from_financial_account_id'] = NULL;
3722 self::updateFinancialAccounts($params, 'changedAmount');
3723 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3724 $updated = TRUE;
3725 }
3726
3727 if (!$updated) {
3728 // Looks like we might have a data correction update.
3729 // This would be a case where a transaction id has been entered but it is incorrect &
3730 // the person goes back in & fixes it, as opposed to a new transaction.
3731 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3732 // the data fix scenario.
3733 // CRM-17751.
3734 if (isset($params['refund_trxn_id'])) {
3735 $refundIDs = CRM_Core_BAO_FinancialTrxn::getRefundTransactionIDs($params['id']);
3736 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3737 civicrm_api3('FinancialTrxn', 'create', [
3738 'id' => $refundIDs['financialTrxnId'],
3739 'trxn_id' => $params['refund_trxn_id'],
3740 ]);
3741 }
3742 }
3743 $cardType = CRM_Utils_Array::value('card_type_id', $params);
3744 $panTruncation = CRM_Utils_Array::value('pan_truncation', $params);
3745 CRM_Core_BAO_FinancialTrxn::updateCreditCardDetails($params['contribution']->id, $panTruncation, $cardType);
3746 }
3747 }
3748
3749 if (!$update) {
3750 // records finanical trxn and entity financial trxn
3751 // also make it available as return value
3752 self::recordAlwaysAccountsReceivable($trxnParams, $params);
3753 $trxnParams['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $params);
3754 $trxnParams['card_type_id'] = CRM_Utils_Array::value('card_type_id', $params);
3755 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
3756 $params['entity_id'] = $financialTxn->id;
3757 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3758 self::$_trxnIDs[] = $financialTxn->id;
3759 }
3760 }
3761 }
3762 // record line items and financial items
3763 if (empty($params['skipLineItem'])) {
3764 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
3765 }
3766
3767 // create batch entry if batch_id is passed and
3768 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3769 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3770 $entityParams = [
3771 'batch_id' => $params['batch_id'],
3772 'entity_table' => 'civicrm_financial_trxn',
3773 'entity_id' => $financialTxn->id,
3774 ];
3775 CRM_Batch_BAO_EntityBatch::create($entityParams);
3776 }
3777
3778 // when a fee is charged
3779 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
3780 CRM_Core_BAO_FinancialTrxn::recordFees($params);
3781 }
3782
3783 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3784 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3785 ) {
3786 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3787 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
3788 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
3789 }
3790 unset($params['line_item']);
3791 self::$_trxnIDs = NULL;
3792 return $return;
3793 }
3794
3795 /**
3796 * Update all financial accounts entry.
3797 *
3798 * @param array $params
3799 * Contribution object, line item array and params for trxn.
3800 *
3801 * @param string $context
3802 * Update scenarios.
3803 *
3804 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3805 * adds unpredictability.
3806 *
3807 */
3808 public static function updateFinancialAccounts(&$params, $context = NULL) {
3809 $trxnID = NULL;
3810 $inputParams = $params;
3811 $isARefund = self::isContributionUpdateARefund($params['prevContribution']->contribution_status_id, $params['contribution']->contribution_status_id);
3812
3813 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
3814 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3815 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount);
3816 }
3817
3818 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
3819 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3820 $params['entity_id'] = $trxn->id;
3821
3822 $itemParams['entity_table'] = 'civicrm_line_item';
3823 $trxnIds['id'] = $params['entity_id'];
3824 $previousLineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($params['contribution']->id);
3825 foreach ($params['line_item'] as $fieldId => $fields) {
3826 $params = self::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3827 }
3828 }
3829
3830 /**
3831 * Is this contribution status a reversal.
3832 *
3833 * If so we would expect to record a negative value in the financial_trxn table.
3834 *
3835 * @param int $status_id
3836 *
3837 * @return bool
3838 */
3839 public static function isContributionStatusNegative($status_id) {
3840 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3841 return in_array(CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3842 }
3843
3844 /**
3845 * Check status validation on update of a contribution.
3846 *
3847 * @param array $values
3848 * Previous form values before submit.
3849 *
3850 * @param array $fields
3851 * The input form values.
3852 *
3853 * @param array $errors
3854 * List of errors.
3855 *
3856 * @return bool
3857 */
3858 public static function checkStatusValidation($values, &$fields, &$errors) {
3859 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
3860 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3861 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3862 return FALSE;
3863 }
3864 }
3865 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3866 $checkStatus = [
3867 'Cancelled' => ['Completed', 'Refunded'],
3868 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3869 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3870 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3871 'Refunded' => ['Cancelled', 'Completed'],
3872 'Partially paid' => ['Completed'],
3873 'Pending refund' => ['Completed', 'Refunded'],
3874 ];
3875
3876 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3877 CRM_Utils_Array::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3878 ) {
3879 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3880 1 => $contributionStatuses[$values['contribution_status_id']],
3881 2 => $contributionStatuses[$fields['contribution_status_id']],
3882 ]);
3883 }
3884 }
3885
3886 /**
3887 * Delete contribution of contact.
3888 *
3889 * CRM-12155
3890 *
3891 * @param int $contactId
3892 * Contact id.
3893 *
3894 */
3895 public static function deleteContactContribution($contactId) {
3896 $contribution = new CRM_Contribute_DAO_Contribution();
3897 $contribution->contact_id = $contactId;
3898 $contribution->find();
3899 while ($contribution->fetch()) {
3900 self::deleteContribution($contribution->id);
3901 }
3902 }
3903
3904 /**
3905 * Get options for a given contribution field.
3906 *
3907 * @param string $fieldName
3908 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3909 * @param array $props whatever is known about this dao object.
3910 *
3911 * @return array|bool
3912 * @see CRM_Core_DAO::buildOptions
3913 *
3914 */
3915 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3916 $className = __CLASS__;
3917 $params = [];
3918 if (isset($props['orderColumn'])) {
3919 $params['orderColumn'] = $props['orderColumn'];
3920 }
3921 switch ($fieldName) {
3922 // This field is not part of this object but the api supports it
3923 case 'payment_processor':
3924 $className = 'CRM_Contribute_BAO_ContributionPage';
3925 // Filter results by contribution page
3926 if (!empty($props['contribution_page_id'])) {
3927 $page = civicrm_api('contribution_page', 'getsingle', [
3928 'version' => 3,
3929 'id' => ($props['contribution_page_id']),
3930 ]);
3931 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
3932 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3933 }
3934 break;
3935
3936 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3937 case 'honor_type_id':
3938 $className = 'CRM_Contribute_BAO_ContributionSoft';
3939 $fieldName = 'soft_credit_type_id';
3940 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3941 break;
3942
3943 case 'contribution_status_id':
3944 if ($context !== 'validate') {
3945 $params['condition'] = "v.name <> 'Template'";
3946 }
3947 }
3948 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
3949 }
3950
3951 /**
3952 * Validate financial type.
3953 *
3954 * CRM-13231
3955 *
3956 * @param int $financialTypeId
3957 * Financial Type id.
3958 *
3959 * @param string $relationName
3960 *
3961 * @return array|bool
3962 */
3963 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3964 $financialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeId, $relationName);
3965
3966 if (!$financialAccount) {
3967 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
3968 }
3969 return FALSE;
3970 }
3971
3972 /**
3973 * @param int $targetCid
3974 * @param $activityType
3975 * @param string $title
3976 * @param int $contributionId
3977 * @param string $totalAmount
3978 * @param string $currency
3979 * @param string $trxn_date
3980 *
3981 * @throws \CRM_Core_Exception
3982 * @throws \CiviCRM_API3_Exception
3983 */
3984 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3985 $paymentAmount = CRM_Utils_Money::format($totalAmount, $currency);
3986 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3987 $date = CRM_Utils_Date::isoToMysql($trxn_date);
3988 // source record id would be the contribution id
3989 $srcRecId = $contributionId;
3990
3991 // activity params
3992 $activityParams = [
3993 'source_contact_id' => $targetCid,
3994 'source_record_id' => $srcRecId,
3995 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3996 'subject' => $subject,
3997 'activity_date_time' => $date,
3998 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3999 'skipRecentView' => TRUE,
4000 ];
4001
4002 // create activity with target contacts
4003 $session = CRM_Core_Session::singleton();
4004 $id = $session->get('userID');
4005 if ($id) {
4006 $activityParams['source_contact_id'] = $id;
4007 $activityParams['target_contact_id'][] = $targetCid;
4008 }
4009 civicrm_api3('Activity', 'create', $activityParams);
4010 }
4011
4012 /**
4013 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4014 *
4015 * @param int $id
4016 * @param $component
4017 * @param bool $getTrxnInfo
4018 * @param bool $usingLineTotal
4019 *
4020 * @return mixed
4021 */
4022 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
4023 // @todo deprecate passing in component - always call with contribution.
4024 if ($component == 'event') {
4025 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4026
4027 if (!$contributionId) {
4028 if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4029 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4030 $id = $primaryParticipantId;
4031 }
4032 if (!$contributionId) {
4033 return;
4034 }
4035 }
4036 }
4037 elseif ($component == 'membership') {
4038 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4039 }
4040 else {
4041 $contributionId = $id;
4042 }
4043
4044 $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
4045 $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL;
4046 if (!$baseTrxnId) {
4047 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
4048 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4049 }
4050 if (empty($total['total_amount']) || $usingLineTotal) {
4051 $total = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
4052 }
4053 else {
4054 $baseTrxnId = $total['trxn_id'];
4055 $total = $total['total_amount'];
4056 }
4057
4058 $paymentBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionId, $total);
4059
4060 $contribution = civicrm_api3('Contribution', 'getsingle', [
4061 'id' => $contributionId,
4062 'return' => [
4063 'currency',
4064 'is_pay_later',
4065 'contribution_status_id',
4066 'financial_type_id',
4067 ],
4068 ]);
4069
4070 $info['payLater'] = $contribution['is_pay_later'];
4071 $info['contribution_status'] = $contribution['contribution_status'];
4072 $info['currency'] = $contribution['currency'];
4073
4074 $financialTypeId = $contribution['financial_type_id'];
4075 $feeFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
4076
4077 $info['total'] = $total;
4078 $info['paid'] = $total - $paymentBalance;
4079 $info['balance'] = $paymentBalance;
4080 $info['id'] = $id;
4081 $info['component'] = $component;
4082 $rows = [];
4083 if ($getTrxnInfo && $baseTrxnId) {
4084 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4085 $sql = "
4086 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4087 ft.total_amount,
4088 ft.payment_instrument_id,
4089 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
4090
4091 FROM civicrm_contribution con
4092 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4093 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4094 AND ft.to_financial_account_id != %2
4095 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4096 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4097 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4098
4099 WHERE con.id = %1 AND ft.is_payment = 1
4100 GROUP BY ft.id";
4101 $queryParams = [
4102 1 => [$contributionId, 'Integer'],
4103 2 => [$feeFinancialAccount, 'Integer'],
4104 ];
4105 $resultDAO = CRM_Core_DAO::executeQuery($sql, $queryParams);
4106 $statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label');
4107
4108 while ($resultDAO->fetch()) {
4109 $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
4110 $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
4111 if ($resultDAO->card_type_id) {
4112 $creditCardType = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id);
4113 $pantruncation = '';
4114 if ($resultDAO->pan_truncation) {
4115 $pantruncation = ": {$resultDAO->pan_truncation}";
4116 }
4117 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4118 }
4119
4120 // show payment edit link only for payments done via backoffice form
4121 $paymentEditLink = '';
4122 if (empty($resultDAO->payment_processor_id) && CRM_Core_Permission::check('edit contributions')) {
4123 $links = [
4124 CRM_Core_Action::UPDATE => [
4125 'name' => "<i class='crm-i fa-pencil'></i>",
4126 'url' => 'civicrm/payment/edit',
4127 'class' => 'medium-popup',
4128 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4129 'title' => ts('Edit Payment'),
4130 ],
4131 ];
4132 $paymentEditLink = CRM_Core_Action::formLink(
4133 $links,
4134 CRM_Core_Action::mask([CRM_Core_Permission::EDIT]),
4135 [
4136 'id' => $resultDAO->id,
4137 'contribution_id' => $contributionId,
4138 ]
4139 );
4140 }
4141
4142 $val = [
4143 'id' => $resultDAO->id,
4144 'total_amount' => $resultDAO->total_amount,
4145 'financial_type' => $resultDAO->financial_account,
4146 'payment_instrument' => $paidByLabel,
4147 'receive_date' => $resultDAO->trxn_date,
4148 'trxn_id' => $resultDAO->trxn_id,
4149 'status' => $statuses[$resultDAO->status_id],
4150 'currency' => $resultDAO->currency,
4151 'action' => $paymentEditLink,
4152 ];
4153 if ($paidByName == 'Check') {
4154 $val['check_number'] = $resultDAO->check_number;
4155 }
4156 $rows[] = $val;
4157 }
4158 $info['transaction'] = $rows;
4159 }
4160
4161 $info['payment_links'] = self::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4162 return $info;
4163 }
4164
4165 /**
4166 * Get the outstanding balance on a contribution.
4167 *
4168 * @param int $contributionId
4169 * @param float $contributionTotal
4170 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4171 *
4172 * @return float
4173 */
4174 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4175 if ($contributionTotal === NULL) {
4176 $contributionTotal = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
4177 }
4178
4179 return (float) CRM_Utils_Money::subtractCurrencies(
4180 $contributionTotal,
4181 CRM_Core_BAO_FinancialTrxn::getTotalPayments($contributionId, TRUE),
4182 CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4183 );
4184 }
4185
4186 /**
4187 * Get the tax amount (misnamed function).
4188 *
4189 * @param array $params
4190 * @param bool $isLineItem
4191 *
4192 * @return array
4193 */
4194 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4195 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
4196
4197 // This function should be only called after standardisation (removal of
4198 // thousand separator & using a decimal point for cents separator.
4199 // However, we don't know if that is always true :-(
4200 // There is a deprecation notice tho :-)
4201 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4202 // Update contribution.
4203 if (!empty($params['id'])) {
4204 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4205 // there are no tax implications - early return.
4206 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4207 return $params;
4208 }
4209 if (empty($params['prevContribution'])) {
4210 $params['prevContribution'] = self::getOriginalContribution($params['id']);
4211 }
4212
4213 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4214 if (!isset($params[$field])) {
4215 if ($field == 'total_amount' && $params['prevContribution']->tax_amount) {
4216 // Tax amount gets added back on later....
4217 $params['total_amount'] = $params['prevContribution']->total_amount -
4218 $params['prevContribution']->tax_amount;
4219 }
4220 else {
4221 $params[$field] = $params['prevContribution']->$field;
4222 if ($params[$field] != $params['prevContribution']->$field) {
4223 }
4224 }
4225 }
4226 }
4227
4228 self::calculateMissingAmountParams($params, $params['id']);
4229 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4230 // Assign tax Amount on update of contribution
4231 if (!empty($params['prevContribution']->tax_amount)) {
4232 $params['tax_amount'] = 'null';
4233 CRM_Price_BAO_LineItem::getLineItemArray($params, [$params['id']]);
4234 foreach ($params['line_item'] as $setID => $priceField) {
4235 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4236 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4237 }
4238 }
4239 }
4240 }
4241 }
4242
4243 // New Contribution and update of contribution with tax rate financial type
4244 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4245 empty($params['skipLineItem']) && !$isLineItem
4246 ) {
4247 $taxRateParams = $taxRates[$params['financial_type_id']];
4248 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount(CRM_Utils_Array::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4249 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4250
4251 // Get Line Item on update of contribution
4252 if (isset($params['id'])) {
4253 CRM_Price_BAO_LineItem::getLineItemArray($params, [$params['id']]);
4254 }
4255 else {
4256 CRM_Price_BAO_LineItem::getLineItemArray($params);
4257 }
4258 foreach ($params['line_item'] as $setID => $priceField) {
4259 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4260 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4261 }
4262 }
4263 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $params) + $params['tax_amount'];
4264 }
4265 elseif (isset($params['api.line_item.create'])) {
4266 // Update total amount of contribution using lineItem
4267 $taxAmountArray = [];
4268 foreach ($params['api.line_item.create'] as $key => $value) {
4269 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4270 $taxRate = $taxRates[$value['financial_type_id']];
4271 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
4272 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4273 }
4274 }
4275 $params['tax_amount'] = array_sum($taxAmountArray);
4276 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
4277 }
4278 else {
4279 // update line item of contrbution
4280 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4281 $taxRate = $taxRates[$params['financial_type_id']];
4282 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4283 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4284 }
4285 }
4286 return $params;
4287 }
4288
4289 /**
4290 * Check financial type validation on update of a contribution.
4291 *
4292 * @param int $financialTypeId
4293 * Value of latest Financial Type.
4294 *
4295 * @param int $contributionId
4296 * Contribution Id.
4297 *
4298 * @param array $errors
4299 * List of errors.
4300 *
4301 * @return void
4302 */
4303 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4304 if (!empty($financialTypeId)) {
4305 $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4306 if ($oldFinancialTypeId == $financialTypeId) {
4307 return;
4308 }
4309 }
4310 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4311 $params = [
4312 '1' => [$contributionId, 'Integer'],
4313 ];
4314 $result = CRM_Core_DAO::executeQuery($sql, $params);
4315 if ($result->N > 1) {
4316 $errors['financial_type_id'] = ts('One or more line items have a different financial type than the contribution. Editing the financial type is not yet supported in this situation.');
4317 }
4318 }
4319
4320 /**
4321 * Update related pledge payment payments.
4322 *
4323 * This function has been refactored out of the back office contribution form and may
4324 * still overlap with other functions.
4325 *
4326 * @param string $action
4327 * @param int $pledgePaymentID
4328 * @param int $contributionID
4329 * @param bool $adjustTotalAmount
4330 * @param float $total_amount
4331 * @param float $original_total_amount
4332 * @param int $contribution_status_id
4333 * @param int $original_contribution_status_id
4334 */
4335 public static function updateRelatedPledge(
4336 $action,
4337 $pledgePaymentID,
4338 $contributionID,
4339 $adjustTotalAmount,
4340 $total_amount,
4341 $original_total_amount,
4342 $contribution_status_id,
4343 $original_contribution_status_id
4344 ) {
4345 if (!$pledgePaymentID && $action & CRM_Core_Action::ADD && !$contributionID) {
4346 return;
4347 }
4348
4349 if ($pledgePaymentID) {
4350 //store contribution id in payment record.
4351 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4352 }
4353 else {
4354 $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4355 $contributionID,
4356 'id',
4357 'contribution_id'
4358 );
4359 }
4360
4361 if (!$pledgePaymentID) {
4362 return;
4363 }
4364 $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4365 $contributionID,
4366 'pledge_id',
4367 'contribution_id'
4368 );
4369
4370 $updatePledgePaymentStatus = FALSE;
4371
4372 // If either the status or the amount has changed we update the pledge status.
4373 if ($action & CRM_Core_Action::ADD) {
4374 $updatePledgePaymentStatus = TRUE;
4375 }
4376 elseif ($action & CRM_Core_Action::UPDATE && (($original_contribution_status_id != $contribution_status_id) ||
4377 ($original_total_amount != $total_amount))
4378 ) {
4379 $updatePledgePaymentStatus = TRUE;
4380 }
4381
4382 if ($updatePledgePaymentStatus) {
4383 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID,
4384 [$pledgePaymentID],
4385 $contribution_status_id,
4386 NULL,
4387 $total_amount,
4388 $adjustTotalAmount
4389 );
4390 }
4391 }
4392
4393 /**
4394 * Compute the stats values
4395 *
4396 * @param string $stat either 'mode' or 'median'
4397 * @param string $sql
4398 * @param string $alias of civicrm_contribution
4399 *
4400 * @return array|null
4401 * @deprecated
4402 *
4403 */
4404 public static function computeStats($stat, $sql, $alias = NULL) {
4405 CRM_Core_Error::deprecatedFunctionWarning('computeStats is now deprecated');
4406 return [];
4407 }
4408
4409 /**
4410 * Is there only one line item attached to the contribution.
4411 *
4412 * @param int $id
4413 * Contribution ID.
4414 *
4415 * @return bool
4416 * @throws \CiviCRM_API3_Exception
4417 */
4418 public static function isSingleLineItem($id) {
4419 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4420 return ($lineItemCount == 1);
4421 }
4422
4423 /**
4424 * Complete an order.
4425 *
4426 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4427 *
4428 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4429 *
4430 * Moving it out of the BaseIPN class is just the first step.
4431 *
4432 * @param array $input
4433 * @param array $ids
4434 * @param array $objects
4435 * @param CRM_Core_Transaction $transaction
4436 * @param CRM_Contribute_BAO_Contribution $contribution
4437 * @param bool $isPostPaymentCreate
4438 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4439 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4440 * transitioning related elements).
4441 *
4442 * @return array
4443 * @throws \CRM_Core_Exception
4444 * @throws \CiviCRM_API3_Exception
4445 */
4446 public static function completeOrder($input, &$ids, $objects, $transaction, $contribution, $isPostPaymentCreate = FALSE) {
4447 $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
4448 // The previous details are used when calculating line items so keep it before any code that 'does something'
4449 if (!empty($contribution->id)) {
4450 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(['id' => $contribution->id]);
4451 }
4452 $inputContributionWhiteList = [
4453 'fee_amount',
4454 'net_amount',
4455 'trxn_id',
4456 'check_number',
4457 'payment_instrument_id',
4458 'is_test',
4459 'campaign_id',
4460 'receive_date',
4461 'receipt_date',
4462 'contribution_status_id',
4463 'card_type_id',
4464 'pan_truncation',
4465 ];
4466 if (self::isSingleLineItem($primaryContributionID)) {
4467 $inputContributionWhiteList[] = 'financial_type_id';
4468 }
4469
4470 $participant = CRM_Utils_Array::value('participant', $objects);
4471 $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
4472 $recurringContributionID = (empty($recurContrib->id)) ? NULL : $recurContrib->id;
4473 $event = CRM_Utils_Array::value('event', $objects);
4474
4475 $paymentProcessorId = '';
4476 if (isset($objects['paymentProcessor'])) {
4477 if (is_array($objects['paymentProcessor'])) {
4478 $paymentProcessorId = $objects['paymentProcessor']['id'];
4479 }
4480 else {
4481 $paymentProcessorId = $objects['paymentProcessor']->id;
4482 }
4483 }
4484
4485 $completedContributionStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4486
4487 $contributionParams = array_merge([
4488 'contribution_status_id' => $completedContributionStatusID,
4489 'source' => self::getRecurringContributionDescription($contribution, $event),
4490 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4491 ));
4492
4493 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4494 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency)) {
4495 $contributionParams['currency'] = $objects['first_contribution']->currency;
4496 }
4497
4498 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4499
4500 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4501 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4502 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects['paymentProcessor']['payment_instrument_id'])) {
4503 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects['paymentProcessor']['payment_instrument_id'];
4504 }
4505
4506 if ($recurringContributionID) {
4507 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4508 }
4509 $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
4510
4511 if (empty($contributionParams['receive_date']) && $changeDate) {
4512 $contributionParams['receive_date'] = $changeDate;
4513 }
4514
4515 self::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4516 $contributionParams['financial_type_id'] = $contribution->financial_type_id;
4517
4518 $values = [];
4519 if (isset($input['is_email_receipt'])) {
4520 $values['is_email_receipt'] = $input['is_email_receipt'];
4521 }
4522
4523 if ($input['component'] == 'contribute') {
4524 if ($contribution->contribution_page_id) {
4525 // Figure out what we gain from this.
4526 // Note that we may have overwritten the is_email_receipt input, fix that below.
4527 CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
4528 }
4529 elseif ($recurContrib && $recurringContributionID) {
4530 $values['amount'] = $recurContrib->amount;
4531 $values['financial_type_id'] = $objects['contributionType']->id;
4532 $values['title'] = $source = ts('Offline Recurring Contribution');
4533 }
4534
4535 if (isset($input['is_email_receipt'])) {
4536 // CRM-19601 - we may have overwritten this above.
4537 $values['is_email_receipt'] = $input['is_email_receipt'];
4538 }
4539 elseif ($recurContrib && $recurringContributionID) {
4540 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4541 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4542 // dev/core#1245 this maybe not the desired effect because the default value for is_email_receipt is set to 0 rather than 1 in
4543 // Instance that had the table added via an upgrade in 4.1
4544 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
4545 // https://lab.civicrm.org/dev/core/issues/1245
4546 $values['is_email_receipt'] = $recurContrib->is_email_receipt;
4547 }
4548
4549 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4550 self::updateMembershipBasedOnCompletionOfContribution(
4551 $contribution,
4552 $primaryContributionID,
4553 $changeDate
4554 );
4555 }
4556 }
4557 else {
4558 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4559 if ($event->is_email_confirm) {
4560 // @todo this should be set by the function that sends the mail after sending.
4561 $contributionParams['receipt_date'] = $changeDate;
4562 }
4563 $participantParams['id'] = $participant->id;
4564 $participantParams['status_id'] = 'Registered';
4565 civicrm_api3('Participant', 'create', $participantParams);
4566 }
4567 }
4568
4569 $contributionParams['id'] = $contribution->id;
4570 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4571
4572 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4573 // unsetting it here does NOT cause any other contribution test to fail!
4574 unset($contributionParams['financial_type_id']);
4575 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4576
4577 // Add new soft credit against current $contribution.
4578 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
4579 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
4580 }
4581
4582 if (empty($contribution->_relatedObjects['participant']) && !empty($contribution->_relatedObjects['membership'])) {
4583 // @fixme Can we remove this if altogether? - we removed the participant if / else and left relatedObjects['participant'] to ensure behaviour didn't change but it is probably not required.
4584 // @todo - use getRelatedMemberships instead
4585 $contribution->contribution_status_id = $contributionParams['contribution_status_id'];
4586 $contribution->trxn_id = CRM_Utils_Array::value('trxn_id', $input);
4587 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
4588 }
4589
4590 CRM_Core_Error::debug_log_message("Contribution record updated successfully");
4591 $transaction->commit();
4592
4593 CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution->id, $recurringContributionID,
4594 $contributionParams['contribution_status_id'], $input['amount']);
4595
4596 // create an activity record
4597 if ($input['component'] == 'contribute') {
4598 //CRM-4027
4599 $targetContactID = NULL;
4600 if (!empty($ids['related_contact'])) {
4601 $targetContactID = $contribution->contact_id;
4602 $contribution->contact_id = $ids['related_contact'];
4603 }
4604 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
4605 }
4606
4607 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4608 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4609 if (!array_key_exists('is_email_receipt', $values) ||
4610 $values['is_email_receipt'] == 1
4611 ) {
4612 civicrm_api3('Contribution', 'sendconfirmation', [
4613 'id' => $contribution->id,
4614 'payment_processor_id' => $paymentProcessorId,
4615 ]);
4616 CRM_Core_Error::debug_log_message("Receipt sent");
4617 }
4618
4619 CRM_Core_Error::debug_log_message("Success: Database updated");
4620 return $contributionResult;
4621 }
4622
4623 /**
4624 * Send receipt from contribution.
4625 *
4626 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4627 *
4628 * Note that the compose message part has been moved to contribution
4629 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4630 *
4631 * @param array $input
4632 * Incoming data from Payment processor.
4633 * @param array $ids
4634 * Related object IDs.
4635 * @param int $contributionID
4636 * @param array $values
4637 * Values related to objects that have already been loaded.
4638 * @param bool $returnMessageText
4639 * Should text be returned instead of sent. This.
4640 * is because the function is also used to generate pdfs
4641 *
4642 * @return array
4643 * @throws \CRM_Core_Exception
4644 * @throws \CiviCRM_API3_Exception
4645 * @throws \Exception
4646 */
4647 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4648 $returnMessageText = FALSE) {
4649
4650 $contribution = new CRM_Contribute_BAO_Contribution();
4651 $contribution->id = $contributionID;
4652 if (!$contribution->find(TRUE)) {
4653 throw new CRM_Core_Exception('Contribution does not exist');
4654 }
4655 $contribution->loadRelatedObjects($input, $ids, TRUE);
4656 // set receipt from e-mail and name in value
4657 if (!$returnMessageText) {
4658 list($values['receipt_from_name'], $values['receipt_from_email']) = self::generateFromEmailAndName($input, $contribution);
4659 }
4660 $values['contribution_status'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id);
4661 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4662 if ((!isset($input['receipt_update']) || $input['receipt_update']) && empty($contribution->receipt_date)) {
4663 civicrm_api3('Contribution', 'create', [
4664 'receipt_date' => 'now',
4665 'id' => $contribution->id,
4666 ]);
4667 }
4668 return $return;
4669 }
4670
4671 /**
4672 * Generate From email and from name in an array values
4673 *
4674 * @param array $input
4675 * @param \CRM_Contribute_BAO_Contribution $contribution
4676 *
4677 * @return array
4678 */
4679 public static function generateFromEmailAndName($input, $contribution) {
4680 // Use input value if supplied.
4681 if (!empty($input['receipt_from_email'])) {
4682 return [
4683 CRM_Utils_Array::value('receipt_from_name', $input, ''),
4684 $input['receipt_from_email'],
4685 ];
4686 }
4687 // if we are still empty see if we can use anything from a contribution page.
4688 $pageValues = [];
4689 if (!empty($contribution->contribution_page_id)) {
4690 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id]);
4691 }
4692 // if we are still empty see if we can use anything from a contribution page.
4693 if (!empty($pageValues['receipt_from_email'])) {
4694 return [
4695 CRM_Utils_Array::value('receipt_from_name', $pageValues),
4696 $pageValues['receipt_from_email'],
4697 ];
4698 }
4699 // If we are still empty fall back to the domain or logged in user information.
4700 return CRM_Core_BAO_Domain::getDefaultReceiptFrom();
4701 }
4702
4703 /**
4704 * Generate credit note id with next avaible number
4705 *
4706 * @return string
4707 * Credit Note Id.
4708 *
4709 * @throws \CiviCRM_API3_Exception
4710 */
4711 public static function createCreditNoteId() {
4712
4713 $creditNoteNum = CRM_Core_DAO::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL");
4714 $creditNoteId = NULL;
4715
4716 do {
4717 $creditNoteNum++;
4718 $creditNoteId = Civi::settings()->get('credit_notes_prefix') . '' . $creditNoteNum;
4719 $result = civicrm_api3('Contribution', 'getcount', [
4720 'sequential' => 1,
4721 'creditnote_id' => $creditNoteId,
4722 ]);
4723 } while ($result > 0);
4724
4725 return $creditNoteId;
4726 }
4727
4728 /**
4729 * Load related memberships.
4730 *
4731 * @param array $ids
4732 *
4733 * @return array $ids
4734 *
4735 * @throws Exception
4736 * @deprecated
4737 *
4738 * Note that in theory it should be possible to retrieve these from the line_item table
4739 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4740 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4741 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4742 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4743 *
4744 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4745 *
4746 */
4747 public function loadRelatedMembershipObjects($ids = []) {
4748 $query = "
4749 SELECT membership_id
4750 FROM civicrm_membership_payment
4751 WHERE contribution_id = %1 ";
4752 $params = [1 => [$this->id, 'Integer']];
4753 $ids['membership'] = (array) CRM_Utils_Array::value('membership', $ids, []);
4754
4755 $dao = CRM_Core_DAO::executeQuery($query, $params);
4756 while ($dao->fetch()) {
4757 if ($dao->membership_id && !in_array($dao->membership_id, $ids['membership'])) {
4758 $ids['membership'][$dao->membership_id] = $dao->membership_id;
4759 }
4760 }
4761
4762 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4763 foreach ($ids['membership'] as $id) {
4764 if (!empty($id)) {
4765 $membership = new CRM_Member_BAO_Membership();
4766 $membership->id = $id;
4767 if (!$membership->find(TRUE)) {
4768 throw new Exception("Could not find membership record: $id");
4769 }
4770 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
4771 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
4772 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
4773 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
4774 }
4775 }
4776 }
4777 return $ids;
4778 }
4779
4780 /**
4781 * This function is used to record partial payments for contribution
4782 *
4783 * @param array $contribution
4784 *
4785 * @param array $params
4786 *
4787 * @return CRM_Financial_DAO_FinancialTrxn
4788 */
4789 public static function recordPartialPayment($contribution, $params) {
4790 CRM_Core_Error::deprecatedFunctionWarning('use payment create api');
4791 $balanceTrxnParams['to_financial_account_id'] = self::getToFinancialAccount($contribution, $params);
4792 $balanceTrxnParams['from_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($contribution['financial_type_id'], 'Accounts Receivable Account is');
4793 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4794 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4795 $balanceTrxnParams['trxn_date'] = CRM_Utils_Array::value('trxn_date', $params, CRM_Utils_Array::value('contribution_receive_date', $params, date('YmdHis')));
4796 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
4797 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('total_amount', $params);
4798 $balanceTrxnParams['currency'] = $contribution['currency'];
4799 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array::value('contribution_trxn_id', $params, NULL);
4800 $balanceTrxnParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
4801 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4802 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
4803 $balanceTrxnParams['is_payment'] = 1;
4804
4805 if (!empty($params['payment_processor'])) {
4806 // I can't find evidence this is passed in - I was gonna just remove it but decided to deprecate as I see self::getToFinancialAccount
4807 // also anticipates it.
4808 CRM_Core_Error::deprecatedFunctionWarning('passing payment_processor is deprecated - use payment_processor_id');
4809 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4810 }
4811 return CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
4812 }
4813
4814 /**
4815 * Get the description (source field) for the recurring contribution.
4816 *
4817 * @param CRM_Contribute_BAO_Contribution $contribution
4818 * @param CRM_Event_DAO_Event|null $event
4819 *
4820 * @return string
4821 * @throws \CiviCRM_API3_Exception
4822 */
4823 protected static function getRecurringContributionDescription($contribution, $event) {
4824 if (!empty($contribution->source)) {
4825 return $contribution->source;
4826 }
4827 elseif (!empty($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) {
4828 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4829 'id' => $contribution->contribution_page_id,
4830 'return' => 'title',
4831 ]);
4832 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4833 }
4834 elseif ($event) {
4835 return ts('Online Event Registration') . ': ' . $event->title;
4836 }
4837 elseif (!empty($contribution->contribution_recur_id)) {
4838 return 'recurring contribution';
4839 }
4840 return '';
4841 }
4842
4843 /**
4844 * Function to add payments for contribution for Partially Paid status
4845 *
4846 * @deprecated this is known to be flawed and possibly buggy.
4847 *
4848 * Replace with Order.create->Payment.create flow.
4849 *
4850 * @param array $contribution
4851 *
4852 * @throws \CiviCRM_API3_Exception
4853 */
4854 public static function addPayments($contribution) {
4855 // get financial trxn which is a payment
4856 $ftSql = "SELECT ft.id, ft.total_amount
4857 FROM civicrm_financial_trxn ft
4858 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4859 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4860
4861 $ftDao = CRM_Core_DAO::executeQuery($ftSql, [
4862 1 => [
4863 $contribution->id,
4864 'Integer',
4865 ],
4866 ]);
4867 $ftDao->fetch();
4868
4869 // store financial item Proportionaly.
4870 $trxnParams = [
4871 'total_amount' => $ftDao->total_amount,
4872 'contribution_id' => $contribution->id,
4873 ];
4874 self::assignProportionalLineItems($trxnParams, $ftDao->id, $contribution->total_amount);
4875 }
4876
4877 /**
4878 * Function use to store line item proportionally in in entity financial trxn table
4879 *
4880 * @param array $trxnParams
4881 *
4882 * @param int $trxnId
4883 *
4884 * @param float $contributionTotalAmount
4885 *
4886 * @throws \CiviCRM_API3_Exception
4887 */
4888 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4889 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($trxnParams['contribution_id']);
4890 if (!empty($lineItems)) {
4891 // get financial item
4892 list($ftIds, $taxItems) = self::getLastFinancialItemIds($trxnParams['contribution_id']);
4893 $entityParams = [
4894 'contribution_total_amount' => $contributionTotalAmount,
4895 'trxn_total_amount' => $trxnParams['total_amount'],
4896 'trxn_id' => $trxnId,
4897 ];
4898 self::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4899 }
4900 }
4901
4902 /**
4903 * Checks if line items total amounts
4904 * match the contribution total amount.
4905 *
4906 * @param array $params
4907 * array of order params.
4908 *
4909 * @throws \API_Exception
4910 */
4911 public static function checkLineItems(&$params) {
4912 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
4913 $lineItemAmount = 0;
4914
4915 foreach ($params['line_items'] as &$lineItems) {
4916 foreach ($lineItems['line_item'] as &$item) {
4917 if (empty($item['financial_type_id'])) {
4918 $item['financial_type_id'] = $params['financial_type_id'];
4919 }
4920 $lineItemAmount += $item['line_total'] + CRM_Utils_Array::value('tax_amount', $item, 0.00);
4921 }
4922 }
4923
4924 if (!isset($totalAmount)) {
4925 $params['total_amount'] = $lineItemAmount;
4926 }
4927 else {
4928 $currency = CRM_Utils_Array::value('currency', $params, '');
4929
4930 if (empty($currency)) {
4931 $currency = CRM_Core_Config::singleton()->defaultCurrency;
4932 }
4933
4934 if (!CRM_Utils_Money::equals($totalAmount, $lineItemAmount, $currency)) {
4935 throw new CRM_Contribute_Exception_CheckLineItemsException();
4936 }
4937 }
4938 }
4939
4940 /**
4941 * Get the financial account for the item associated with the new transaction.
4942 *
4943 * @param array $params
4944 * @param int $default
4945 *
4946 * @return int
4947 */
4948 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4949
4950 if (!empty($params['financial_account_id'])) {
4951 return $params['financial_account_id'];
4952 }
4953
4954 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['contribution_status_id'], 'name');
4955 $preferredAccountsRelationships = [
4956 'Refunded' => 'Credit/Contra Revenue Account is',
4957 'Chargeback' => 'Chargeback Account is',
4958 ];
4959
4960 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4961 $financialTypeID = !empty($params['financial_type_id']) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
4962 return CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
4963 $financialTypeID,
4964 $preferredAccountsRelationships[$contributionStatus]
4965 );
4966 }
4967
4968 return $default;
4969 }
4970
4971 /**
4972 * ContributionPage values were being imposed onto values.
4973 *
4974 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4975 * REALLY didn't want superimposed. The rest are left there in their overkill out
4976 * of cautiousness.
4977 *
4978 * The rationale for making this explicit is that it was a case of carefully set values being
4979 * seemingly randonly overwritten without much care. In general I think array randomly setting
4980 * variables en mass is risky.
4981 *
4982 * @param array $values
4983 *
4984 * @return array
4985 */
4986 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4987 $contributionPageValues = [];
4988 CRM_Contribute_BAO_ContributionPage::setValues(
4989 $this->contribution_page_id,
4990 $contributionPageValues
4991 );
4992 $valuesToCopy = [
4993 // These are the values that I believe to be useful.
4994 'id',
4995 'title',
4996 'pay_later_receipt',
4997 'pay_later_text',
4998 'receipt_from_email',
4999 'receipt_from_name',
5000 'receipt_text',
5001 'custom_pre_id',
5002 'custom_post_id',
5003 'honoree_profile_id',
5004 'onbehalf_profile_id',
5005 'honor_block_is_active',
5006 // Kinda might be - but would be on the contribution...
5007 'campaign_id',
5008 'currency',
5009 // Included for 'fear of regression' but can't justify any use for these....
5010 'intro_text',
5011 'payment_processor',
5012 'financial_type_id',
5013 'amount_block_is_active',
5014 'bcc_receipt',
5015 'cc_receipt',
5016 'created_date',
5017 'created_id',
5018 'default_amount_id',
5019 'end_date',
5020 'footer_text',
5021 'goal_amount',
5022 'initial_amount_help_text',
5023 'initial_amount_label',
5024 'intro_text',
5025 'is_allow_other_amount',
5026 'is_billing_required',
5027 'is_confirm_enabled',
5028 'is_credit_card_only',
5029 'is_monetary',
5030 'is_partial_payment',
5031 'is_recur_installments',
5032 'is_recur_interval',
5033 'is_share',
5034 'max_amount',
5035 'min_amount',
5036 'min_initial_amount',
5037 'recur_frequency_unit',
5038 'start_date',
5039 'thankyou_footer',
5040 'thankyou_text',
5041 'thankyou_title',
5042
5043 ];
5044 foreach ($valuesToCopy as $valueToCopy) {
5045 if (isset($contributionPageValues[$valueToCopy])) {
5046 if ($valueToCopy === 'title') {
5047 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils::getContributionPageTitle($this->contribution_page_id);
5048 }
5049 else {
5050 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5051 }
5052 }
5053 }
5054 return $values;
5055 }
5056
5057 /**
5058 * Get values of CiviContribute Settings
5059 * and check if its enabled or not.
5060 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5061 * in serialized form. Usually this should be stored as flat settings for each form fields
5062 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5063 * settings we will live with an inconsistency because it's too hard to change for now.
5064 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5065 *
5066 *
5067 * @param string $name
5068 *
5069 * @return string
5070 *
5071 */
5072 public static function checkContributeSettings($name) {
5073 $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
5074 return CRM_Utils_Array::value($name, $contributeSettings);
5075 }
5076
5077 /**
5078 * This function process contribution related objects.
5079 *
5080 * @param int $contributionId
5081 * @param int $statusId
5082 * @param int|null $previousStatusId
5083 *
5084 * @param string $receiveDate
5085 *
5086 * @return null|string
5087 */
5088 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5089 $statusMsg = NULL;
5090 if (!$contributionId || !$statusId) {
5091 return $statusMsg;
5092 }
5093
5094 $params = [
5095 'contribution_id' => $contributionId,
5096 'contribution_status_id' => $statusId,
5097 'previous_contribution_status_id' => $previousStatusId,
5098 'receive_date' => $receiveDate,
5099 ];
5100
5101 $updateResult = CRM_Contribute_BAO_Contribution::transitionComponents($params);
5102
5103 if (!is_array($updateResult) ||
5104 !($updatedComponents = CRM_Utils_Array::value('updatedComponents', $updateResult)) ||
5105 !is_array($updatedComponents) ||
5106 empty($updatedComponents)
5107 ) {
5108 return $statusMsg;
5109 }
5110
5111 // get the user display name.
5112 $sql = "
5113 SELECT display_name as displayName
5114 FROM civicrm_contact
5115 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5116 WHERE civicrm_contribution.id = {$contributionId}";
5117 $userDisplayName = CRM_Core_DAO::singleValueQuery($sql);
5118
5119 // get the status message for user.
5120 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5121
5122 if ($componentName == 'CiviMember') {
5123 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
5124 CRM_Member_PseudoConstant::membershipStatus()
5125 );
5126
5127 $statusNameMsgPart = 'updated';
5128 switch ($updatedStatusName) {
5129 case 'Cancelled':
5130 case 'Expired':
5131 $statusNameMsgPart = $updatedStatusName;
5132 break;
5133 }
5134
5135 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
5136 1 => $userDisplayName,
5137 2 => $statusNameMsgPart,
5138 ]);
5139 }
5140
5141 if ($componentName == 'CiviEvent') {
5142 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
5143 CRM_Event_PseudoConstant::participantStatus()
5144 );
5145 if ($updatedStatusName == 'Cancelled') {
5146 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
5147 }
5148 elseif ($updatedStatusName == 'Registered') {
5149 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
5150 }
5151 }
5152
5153 if ($componentName == 'CiviPledge') {
5154 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
5155 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
5156 );
5157 if ($updatedStatusName == 'Cancelled') {
5158 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
5159 }
5160 elseif ($updatedStatusName == 'Failed') {
5161 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
5162 }
5163 elseif ($updatedStatusName == 'Completed') {
5164 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
5165 }
5166 }
5167 }
5168
5169 return $statusMsg;
5170 }
5171
5172 /**
5173 * Get the contribution as it is in the database before being updated.
5174 *
5175 * @param int $contributionID
5176 *
5177 * @return \CRM_Contribute_BAO_Contribution|null
5178 */
5179 private static function getOriginalContribution($contributionID) {
5180 return self::getValues(['id' => $contributionID]);
5181 }
5182
5183 /**
5184 * Get the amount for the financial item row.
5185 *
5186 * Helper function to start to break down recordFinancialTransactions for readability.
5187 *
5188 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5189 *
5190 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5191 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5192 * of that function
5193 *
5194 * @param array $params
5195 * Params as passed to contribution.create
5196 *
5197 * @param string $context
5198 * changeFinancialType| changedAmount
5199 * @param array $lineItemDetails
5200 * Line items.
5201 * @param bool $isARefund
5202 * Is this a refund / negative transaction.
5203 * @param int $previousLineItemTotal
5204 *
5205 * @return float
5206 * @todo move recordFinancialAccounts & helper functions to their own class?
5207 *
5208 */
5209 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5210 if ($context == 'changedAmount') {
5211 $lineTotal = $lineItemDetails['line_total'];
5212 if ($lineTotal != $previousLineItemTotal) {
5213 $lineTotal -= $previousLineItemTotal;
5214 }
5215 return $lineTotal;
5216 }
5217 elseif ($context == 'changeFinancialType') {
5218 return -$lineItemDetails['line_total'];
5219 }
5220 elseif ($context == 'changedStatus') {
5221 $cancelledTaxAmount = 0;
5222 if ($isARefund) {
5223 $cancelledTaxAmount = CRM_Utils_Array::value('tax_amount', $lineItemDetails, '0.00');
5224 }
5225 return self::getMultiplier($params['contribution']->contribution_status_id, $context) * ((float) $lineItemDetails['line_total'] + (float) $cancelledTaxAmount);
5226 }
5227 elseif ($context === NULL) {
5228 // erm, yes because? but, hey, it's tested.
5229 return $lineItemDetails['line_total'];
5230 }
5231 elseif (empty($lineItemDetails['line_total'])) {
5232 // follow legacy code path
5233 Civi::log()
5234 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5235 return $params['total_amount'];
5236 }
5237 else {
5238 return self::getMultiplier($params['contribution']->contribution_status_id, $context) * ((float) $lineItemDetails['line_total']);
5239 }
5240 }
5241
5242 /**
5243 * Get the multiplier for adjusting rows.
5244 *
5245 * If we are dealing with a refund or cancellation then it will be a negative
5246 * amount to reflect the negative transaction.
5247 *
5248 * If we are changing Financial Type it will be a negative amount to
5249 * adjust down the old type.
5250 *
5251 * @param int $contribution_status_id
5252 * @param string $context
5253 *
5254 * @return int
5255 */
5256 protected static function getMultiplier($contribution_status_id, $context) {
5257 if ($context == 'changeFinancialType' || self::isContributionStatusNegative($contribution_status_id)) {
5258 return -1;
5259 }
5260 return 1;
5261 }
5262
5263 /**
5264 * Does this transaction reflect a payment instrument change.
5265 *
5266 * @param array $params
5267 * @param array $pendingStatuses
5268 *
5269 * @return bool
5270 */
5271 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5272 $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id);
5273
5274 if (array_key_exists('payment_instrument_id', $params)) {
5275 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
5276 !CRM_Utils_System::isNull($params['payment_instrument_id'])
5277 ) {
5278 //check if status is changed from Pending to Completed
5279 // do not update payment instrument changes for Pending to Completed
5280 if (!($contributionStatus == 'Completed' &&
5281 in_array($params['prevContribution']->contribution_status_id, $pendingStatuses))
5282 ) {
5283 return TRUE;
5284 }
5285 }
5286 elseif ((!CRM_Utils_System::isNull($params['payment_instrument_id']) &&
5287 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
5288 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5289 ) {
5290 return TRUE;
5291 }
5292 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
5293 $params['contribution']->check_number != $params['prevContribution']->check_number
5294 ) {
5295 // another special case when check number is changed, create new financial records
5296 // create financial trxn with negative amount
5297 return TRUE;
5298 }
5299 }
5300 return FALSE;
5301 }
5302
5303 /**
5304 * Update the memberships associated with a contribution if it has been completed.
5305 *
5306 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5307 * load them in this function. Code clean up would compensate for any minor performance implication.
5308 *
5309 * @param \CRM_Contribute_BAO_Contribution $contribution
5310 * @param int $primaryContributionID
5311 * @param string $changeDate
5312 *
5313 * @throws \CRM_Core_Exception
5314 * @throws \CiviCRM_API3_Exception
5315 */
5316 public static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5317 $memberships = self::getRelatedMemberships($contribution->id);
5318 foreach ($memberships as $membership) {
5319 $membershipParams = [
5320 'id' => $membership['id'],
5321 'contact_id' => $membership['contact_id'],
5322 'is_test' => $membership['is_test'],
5323 'membership_type_id' => $membership['membership_type_id'],
5324 'membership_activity_status' => 'Completed',
5325 ];
5326
5327 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'],
5328 $membershipParams['membership_type_id'],
5329 $membershipParams['is_test'],
5330 $membershipParams['id']
5331 );
5332
5333 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5334 // this picks up membership type changes during renewals
5335 // @todo this is almost certainly an obsolete sql call, the pre-change
5336 // membership is accessible via $this->_relatedObjects
5337 $sql = "
5338 SELECT membership_type_id
5339 FROM civicrm_membership_log
5340 WHERE membership_id={$membershipParams['id']}
5341 ORDER BY id DESC
5342 LIMIT 1;";
5343 $dao = CRM_Core_DAO::executeQuery($sql);
5344 if ($dao->fetch()) {
5345 if (!empty($dao->membership_type_id)) {
5346 $membershipParams['membership_type_id'] = $dao->membership_type_id;
5347 }
5348 }
5349 if (empty($membership['end_date']) || (int) $membership['status_id'] !== CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5350 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5351 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5352 // The api assumes num_terms is a special sauce for 'is_renewal' so we need to not pass it when updating a pending to completed.
5353 // @todo once apiv4 ships with core switch to that & find sanity.
5354 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5355 $membershipParams['membership_type_id'],
5356 $primaryContributionID
5357 );
5358 }
5359 // @todo remove all this stuff in favour of letting the api call further down handle in
5360 // (it is a duplication of what the api does).
5361 $dates = array_fill_keys([
5362 'join_date',
5363 'start_date',
5364 'end_date',
5365 ], NULL);
5366 if ($currentMembership) {
5367 /*
5368 * Fixed FOR CRM-4433
5369 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5370 * when Contribution mode is notify and membership is for renewal )
5371 */
5372 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5373
5374 // @todo - we should pass membership_type_id instead of null here but not
5375 // adding as not sure of testing
5376 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'],
5377 $changeDate, NULL, $membershipParams['num_terms']
5378 );
5379 $dates['join_date'] = $currentMembership['join_date'];
5380 }
5381
5382 //get the status for membership.
5383 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
5384 $dates['end_date'],
5385 $dates['join_date'],
5386 'today',
5387 TRUE,
5388 $membershipParams['membership_type_id'],
5389 $membershipParams
5390 );
5391
5392 unset($dates['end_date']);
5393 $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
5394 //we might be renewing membership,
5395 //so make status override false.
5396 $membershipParams['is_override'] = FALSE;
5397 $membershipParams['status_override_end_date'] = 'null';
5398
5399 //CRM-17723 - reset static $relatedContactIds array()
5400 // @todo move it to Civi Statics.
5401 $var = TRUE;
5402 CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
5403 civicrm_api3('Membership', 'create', $membershipParams);
5404 }
5405 }
5406
5407 /**
5408 * Get payment links as they relate to a contribution.
5409 *
5410 * If a payment can be made then include a payment link & if a refund is appropriate
5411 * then a refund link.
5412 *
5413 * @param int $id
5414 * @param float $balance
5415 * @param string $contributionStatus
5416 *
5417 * @return array
5418 * $actionLinks Links array containing:
5419 * -url
5420 * -title
5421 */
5422 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5423 if ($contributionStatus === 'Failed' || !CRM_Core_Permission::check('edit contributions')) {
5424 // In general the balance is the best way to determine if a payment can be added or not,
5425 // but not for Failed contributions, where we don't accept additional payments at the moment.
5426 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5427 // do accept more payments agains them.
5428 return [];
5429 }
5430 $actionLinks = [];
5431 if ((int) $balance > 0) {
5432 if (CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()) {
5433 $actionLinks[] = [
5434 'url' => CRM_Utils_System::url('civicrm/payment', [
5435 'action' => 'add',
5436 'reset' => 1,
5437 'id' => $id,
5438 'mode' => 'live',
5439 ]),
5440 'title' => ts('Submit Credit Card payment'),
5441 ];
5442 }
5443 $actionLinks[] = [
5444 'url' => CRM_Utils_System::url('civicrm/payment', [
5445 'action' => 'add',
5446 'reset' => 1,
5447 'id' => $id,
5448 ]),
5449 'title' => ts('Record Payment'),
5450 ];
5451 }
5452 elseif ((int) $balance < 0) {
5453 $actionLinks[] = [
5454 'url' => CRM_Utils_System::url('civicrm/payment', [
5455 'action' => 'add',
5456 'reset' => 1,
5457 'id' => $id,
5458 ]),
5459 'title' => ts('Record Refund'),
5460 ];
5461 }
5462 return $actionLinks;
5463 }
5464
5465 /**
5466 * Get a query to determine the amount donated by the contact/s in the current financial year.
5467 *
5468 * @param array $contactIDs
5469 *
5470 * @return string
5471 */
5472 public static function getAnnualQuery($contactIDs) {
5473 $contactIDs = implode(',', $contactIDs);
5474 $config = CRM_Core_Config::singleton();
5475 $currentMonth = date('m');
5476 $currentDay = date('d');
5477 if (
5478 (int) $config->fiscalYearStart['M'] > $currentMonth ||
5479 (
5480 (int) $config->fiscalYearStart['M'] == $currentMonth &&
5481 (int) $config->fiscalYearStart['d'] > $currentDay
5482 )
5483 ) {
5484 $year = date('Y') - 1;
5485 }
5486 else {
5487 $year = date('Y');
5488 }
5489 $nextYear = $year + 1;
5490
5491 if ($config->fiscalYearStart) {
5492 $newFiscalYearStart = $config->fiscalYearStart;
5493 if ($newFiscalYearStart['M'] < 10) {
5494 // This is just a clumsy way of adding padding.
5495 // @todo next round look for a nicer way.
5496 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5497 }
5498 if ($newFiscalYearStart['d'] < 10) {
5499 // This is just a clumsy way of adding padding.
5500 // @todo next round look for a nicer way.
5501 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5502 }
5503 $config->fiscalYearStart = $newFiscalYearStart;
5504 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
5505 }
5506 else {
5507 // First of January.
5508 $monthDay = '0101';
5509 }
5510 $startDate = "$year$monthDay";
5511 $endDate = "$nextYear$monthDay";
5512
5513 $whereClauses = [
5514 'contact_id' => 'IN (' . $contactIDs . ')',
5515 'is_test' => ' = 0',
5516 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5517 ];
5518 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5519 CRM_Financial_BAO_FinancialType::addACLClausesToWhereClauses($whereClauses);
5520
5521 $clauses = [];
5522 foreach ($whereClauses as $key => $clause) {
5523 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5524 }
5525 $whereClauseString = implode(' AND ', $clauses);
5526
5527 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5528 // this group by + having on contribution_status_id improves performance
5529 $query = "
5530 SELECT COUNT(*) as count,
5531 SUM(total_amount) as amount,
5532 AVG(total_amount) as average,
5533 currency
5534 FROM civicrm_contribution b
5535 WHERE " . $whereClauseString . "
5536 GROUP BY currency, contribution_status_id
5537 HAVING $havingClause
5538 ";
5539 return $query;
5540 }
5541
5542 /**
5543 * Assign Test Value.
5544 *
5545 * @param string $fieldName
5546 * @param array $fieldDef
5547 * @param int $counter
5548 */
5549 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5550 if ($fieldName == 'tax_amount') {
5551 $this->{$fieldName} = "0.00";
5552 }
5553 elseif ($fieldName == 'net_amount') {
5554 $this->{$fieldName} = "2.00";
5555 }
5556 elseif ($fieldName == 'total_amount') {
5557 $this->{$fieldName} = "3.00";
5558 }
5559 elseif ($fieldName == 'fee_amount') {
5560 $this->{$fieldName} = "1.00";
5561 }
5562 else {
5563 parent::assignTestValues($fieldName, $fieldDef, $counter);
5564 }
5565 }
5566
5567 /**
5568 * Check if contribution has participant/membership payment.
5569 *
5570 * @param int $contributionId
5571 * Contribution ID
5572 *
5573 * @return bool
5574 */
5575 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5576 // get line item for contribution
5577 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId);
5578 // check if line item is for membership or participant
5579 foreach ($lineItems as $items) {
5580 if ($items['entity_table'] == 'civicrm_participant') {
5581 $flag = FALSE;
5582 break;
5583 }
5584 elseif ($items['entity_table'] == 'civicrm_membership') {
5585 $flag = FALSE;
5586 }
5587 else {
5588 $flag = TRUE;
5589 break;
5590 }
5591 }
5592 return $flag;
5593 }
5594
5595 /**
5596 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5597 *
5598 * @param array $trxnParams
5599 * Financial trxn params
5600 * @param array $contributionParams
5601 * Contribution Params
5602 *
5603 * @return null
5604 */
5605 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5606 if (!Civi::settings()->get('always_post_to_accounts_receivable')) {
5607 return NULL;
5608 }
5609 $statusId = $contributionParams['contribution']->contribution_status_id;
5610 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
5611 $contributionStatus = empty($statusId) ? NULL : $contributionStatuses[$statusId];
5612 $previousContributionStatus = empty($contributionParams['prevContribution']) ? NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id];
5613 // Return if contribution status is not completed.
5614 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5615 || (!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5616 && $contributionParams['prevContribution']->is_pay_later == 0
5617 )))
5618 ) {
5619 return NULL;
5620 }
5621
5622 $params = $trxnParams;
5623 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $contributionParams) ? $contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id;
5624 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5625 $params['to_financial_account_id'] = $arAccountId;
5626 $params['status_id'] = array_search('Pending', $contributionStatuses);
5627 $params['is_payment'] = FALSE;
5628 $trxn = CRM_Core_BAO_FinancialTrxn::create($params);
5629 self::$_trxnIDs[] = $trxn->id;
5630 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5631 }
5632
5633 /**
5634 * Calculate financial item amount when contribution is updated.
5635 *
5636 * @param array $params
5637 * contribution params
5638 * @param array $amountParams
5639 *
5640 * @param string $context
5641 *
5642 * @return float
5643 */
5644 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5645 if (!empty($params['is_quick_config'])) {
5646 $amount = $amountParams['item_amount'];
5647 if (!$amount) {
5648 $amount = $params['total_amount'];
5649 if ($context === NULL) {
5650 $amount -= CRM_Utils_Array::value('tax_amount', $params, 0);
5651 }
5652 }
5653 }
5654 else {
5655 $amount = $amountParams['line_total'];
5656 if ($context == 'changedAmount') {
5657 $amount -= $amountParams['previous_line_total'];
5658 }
5659 $amount *= $amountParams['diff'];
5660 }
5661 return $amount;
5662 }
5663
5664 /**
5665 * Retrieve Sales Tax Financial Accounts.
5666 *
5667 *
5668 * @return array
5669 *
5670 */
5671 public static function getSalesTaxFinancialAccounts() {
5672 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5673 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5674 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5675 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5676 $queryParams = [1 => [$accountRel, 'Integer']];
5677 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
5678 $financialAccount = [];
5679 while ($dao->fetch()) {
5680 $financialAccount[$dao->id] = $dao->id;
5681 }
5682 return $financialAccount;
5683 }
5684
5685 /**
5686 * Create tax entry in civicrm_entity_financial_trxn table.
5687 *
5688 * @param array $entityParams
5689 *
5690 * @param array $eftParams
5691 *
5692 * @throws \CiviCRM_API3_Exception
5693 */
5694 public static function createProportionalEntry($entityParams, $eftParams) {
5695 $paid = 0;
5696 if ($entityParams['contribution_total_amount'] != 0) {
5697 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5698 }
5699 // Record Entity Financial Trxn; CRM-20145
5700 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils::formatAmount($paid);
5701 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5702 }
5703
5704 /**
5705 * Create array of last financial item id's.
5706 *
5707 * @param int $contributionId
5708 *
5709 * @return array
5710 */
5711 public static function getLastFinancialItemIds($contributionId) {
5712 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5713 FROM civicrm_financial_item fi
5714 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5715 WHERE li.contribution_id = %1";
5716 $dao = CRM_Core_DAO::executeQuery($sql, [
5717 1 => [
5718 $contributionId,
5719 'Integer',
5720 ],
5721 ]);
5722 $ftIds = $taxItems = [];
5723 $salesTaxFinancialAccount = self::getSalesTaxFinancialAccounts();
5724 while ($dao->fetch()) {
5725 /* if sales tax item*/
5726 if (in_array($dao->financial_account_id, $salesTaxFinancialAccount)) {
5727 $taxItems[$dao->price_field_value_id] = [
5728 'financial_item_id' => $dao->id,
5729 'amount' => $dao->tax_amount,
5730 ];
5731 }
5732 else {
5733 $ftIds[$dao->price_field_value_id] = $dao->id;
5734 }
5735 }
5736 return [$ftIds, $taxItems];
5737 }
5738
5739 /**
5740 * Create proportional entries in civicrm_entity_financial_trxn.
5741 *
5742 * @param array $entityParams
5743 *
5744 * @param array $lineItems
5745 *
5746 * @param array $ftIds
5747 *
5748 * @param array $taxItems
5749 *
5750 * @throws \CiviCRM_API3_Exception
5751 */
5752 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5753 $eftParams = [
5754 'entity_table' => 'civicrm_financial_item',
5755 'financial_trxn_id' => $entityParams['trxn_id'],
5756 ];
5757 foreach ($lineItems as $key => $value) {
5758 if ($value['qty'] == 0) {
5759 continue;
5760 }
5761 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5762 $entityParams['line_item_amount'] = $value['line_total'];
5763 self::createProportionalEntry($entityParams, $eftParams);
5764 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5765 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5766 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5767 self::createProportionalEntry($entityParams, $eftParams);
5768 }
5769 }
5770 }
5771
5772 /**
5773 * Load entities related to the contribution into $this->_relatedObjects.
5774 *
5775 * @param array $ids
5776 *
5777 * @throws \CRM_Core_Exception
5778 */
5779 protected function loadRelatedEntitiesByID($ids) {
5780 $entities = [
5781 'contact' => 'CRM_Contact_BAO_Contact',
5782 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5783 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5784 'financialType' => 'CRM_Financial_BAO_FinancialType',
5785 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5786 ];
5787 foreach ($entities as $entity => $bao) {
5788 if (!empty($ids[$entity])) {
5789 $this->_relatedObjects[$entity] = new $bao();
5790 $this->_relatedObjects[$entity]->id = $ids[$entity];
5791 if (!$this->_relatedObjects[$entity]->find(TRUE)) {
5792 throw new CRM_Core_Exception($entity . ' could not be loaded');
5793 }
5794 }
5795 }
5796 }
5797
5798 /**
5799 * Should an email receipt be sent for this contribution when complete.
5800 *
5801 * @param array $input
5802 *
5803 * @return mixed
5804 */
5805 protected function isEmailReceipt($input) {
5806 if (isset($input['is_email_receipt'])) {
5807 return $input['is_email_receipt'];
5808 }
5809 if (!empty($this->_relatedObjects['contribution_page_id'])) {
5810 return $this->_relatedObjects['contribution_page_id']->is_email_receipt;
5811 }
5812 return TRUE;
5813 }
5814
5815 /**
5816 * Function to replace contribution tokens.
5817 *
5818 * @param array $contributionIds
5819 *
5820 * @param string $subject
5821 *
5822 * @param array $subjectToken
5823 *
5824 * @param string $text
5825 *
5826 * @param string $html
5827 *
5828 * @param array $messageToken
5829 *
5830 * @param bool $escapeSmarty
5831 *
5832 * @return array
5833 * @throws \CiviCRM_API3_Exception
5834 */
5835 public static function replaceContributionTokens(
5836 $contributionIds,
5837 $subject,
5838 $subjectToken,
5839 $text,
5840 $html,
5841 $messageToken,
5842 $escapeSmarty
5843 ) {
5844 if (empty($contributionIds)) {
5845 return [];
5846 }
5847 $contributionDetails = [];
5848 foreach ($contributionIds as $id) {
5849 $result = self::getContributionTokenValues($id, $messageToken);
5850 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5851 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5852 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5853 }
5854 return $contributionDetails;
5855 }
5856
5857 /**
5858 * Get the contribution fields for $id and display labels where
5859 * appropriate (if the token is present).
5860 *
5861 * @param int $id
5862 * @param array $messageToken
5863 * @return array
5864 */
5865 public static function getContributionTokenValues($id, $messageToken) {
5866 if (empty($id)) {
5867 return [];
5868 }
5869 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5870 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5871 if (!empty($messageToken)) {
5872 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5873 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5874 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField::displayValue($result['values'][$id][$fieldName], $fieldName);
5875 }
5876 }
5877 }
5878 return $result;
5879 }
5880
5881 /**
5882 * Get invoice_number for contribution.
5883 *
5884 * @param int $contributionID
5885 *
5886 * @return string
5887 */
5888 public static function getInvoiceNumber($contributionID) {
5889 if ($invoicePrefix = self::checkContributeSettings('invoice_prefix')) {
5890 return $invoicePrefix . $contributionID;
5891 }
5892
5893 return NULL;
5894 }
5895
5896 /**
5897 * Load the values needed for the event message.
5898 *
5899 * @param int $eventID
5900 * @param int $participantID
5901 * @param int|null $contributionID
5902 *
5903 * @return array
5904 * @throws \CRM_Core_Exception
5905 */
5906 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5907
5908 $eventParams = [
5909 'id' => $eventID,
5910 ];
5911 $values = ['event' => []];
5912
5913 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
5914 // add custom fields for event
5915 $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', NULL, $eventID);
5916
5917 $eventCustomGroup = [];
5918 foreach ($eventGroupTree as $key => $group) {
5919 if ($key === 'info') {
5920 continue;
5921 }
5922
5923 foreach ($group['fields'] as $k => $customField) {
5924 $groupLabel = $group['title'];
5925 if (!empty($customField['customValue'])) {
5926 foreach ($customField['customValue'] as $customFieldValues) {
5927 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
5928 }
5929 }
5930 }
5931 }
5932 $values['event']['customGroup'] = $eventCustomGroup;
5933
5934 //get participant details
5935 $participantParams = [
5936 'id' => $participantID,
5937 ];
5938
5939 $values['participant'] = [];
5940
5941 CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds);
5942 // add custom fields for event
5943 $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID);
5944 $participantCustomGroup = [];
5945 foreach ($participantGroupTree as $key => $group) {
5946 if ($key === 'info') {
5947 continue;
5948 }
5949
5950 foreach ($group['fields'] as $k => $customField) {
5951 $groupLabel = $group['title'];
5952 if (!empty($customField['customValue'])) {
5953 foreach ($customField['customValue'] as $customFieldValues) {
5954 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
5955 }
5956 }
5957 }
5958 }
5959 $values['participant']['customGroup'] = $participantCustomGroup;
5960
5961 //get location details
5962 $locationParams = [
5963 'entity_id' => $eventID,
5964 'entity_table' => 'civicrm_event',
5965 ];
5966 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
5967
5968 $ufJoinParams = [
5969 'entity_table' => 'civicrm_event',
5970 'entity_id' => $eventID,
5971 'module' => 'CiviEvent',
5972 ];
5973
5974 list($custom_pre_id,
5975 $custom_post_ids
5976 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
5977
5978 $values['custom_pre_id'] = $custom_pre_id;
5979 $values['custom_post_id'] = $custom_post_ids;
5980
5981 // set lineItem for event contribution
5982 if ($contributionID) {
5983 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($contributionID);
5984 if (!empty($participantIds)) {
5985 foreach ($participantIds as $pIDs) {
5986 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
5987 if (!CRM_Utils_System::isNull($lineItem)) {
5988 $values['lineItem'][] = $lineItem;
5989 }
5990 }
5991 }
5992 }
5993 return $values;
5994 }
5995
5996 }