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