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