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