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