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