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