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