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