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