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