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