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