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