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