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