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