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