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