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