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