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