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