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