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