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