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