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