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