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