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