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