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