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