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