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