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