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