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