3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Contribute_BAO_Query
extends CRM_Core_BAO_Query
{
35 public static $_contribOrSoftCredit = "only_contribs";
37 public static $_contribRecurPayment = NULL;
40 * Function get the searchable fields for contribution.
42 * This is basically the contribution fields plus some related entity fields.
44 * @param bool $checkPermission
47 * Associative array of contribution fields
49 public static function getFields($checkPermission = TRUE) {
50 if (!isset(\Civi
::$statics[__CLASS__
]) ||
!isset(\Civi
::$statics[__CLASS__
]['fields']) ||
!isset(\Civi
::$statics[__CLASS__
]['fields']['contribution'])) {
51 // Adding fields with some care as those without unique names could clobber others.
52 // Refer to CRM_Contribute_Form_SearchTest for existing tests ... and to add more!
53 $testedRecurFields = array_fill_keys(['contribution_recur_trxn_id', 'contribution_recur_processor_id', 'contribution_recur_payment_processor_id'], 1);
54 $recurFields = array_intersect_key(CRM_Contribute_DAO_ContributionRecur
::fields(), $testedRecurFields);
55 $fields = array_merge($recurFields, CRM_Contribute_BAO_Contribution
::exportableFields($checkPermission));
56 CRM_Contribute_BAO_Contribution
::appendPseudoConstantsToFields($fields);
57 unset($fields['contribution_contact_id']);
58 \Civi
::$statics[__CLASS__
]['fields']['contribution'] = $fields;
60 return \Civi
::$statics[__CLASS__
]['fields']['contribution'];
64 * If contributions are involved, add the specific contribute fields.
66 * @param CRM_Contact_BAO_Query $query
68 public static function select(&$query) {
69 // if contribute mode add contribution id
70 if ($query->_mode
& CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
71 $query->_select
['contribution_id'] = "civicrm_contribution.id as contribution_id";
72 $query->_element
['contribution_id'] = 1;
73 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
76 // get accounting code
77 if (!empty($query->_returnProperties
['accounting_code'])) {
78 $query->_select
['accounting_code'] = "civicrm_financial_account.accounting_code as accounting_code";
79 $query->_element
['accounting_code'] = 1;
80 $query->_tables
['civicrm_accounting_code'] = 1;
81 $query->_tables
['civicrm_financial_account'] = 1;
84 if (!empty($query->_returnProperties
['contribution_note'])) {
85 $query->_select
['contribution_note'] = "civicrm_note.note as contribution_note";
86 $query->_element
['contribution_note'] = 1;
87 $query->_tables
['contribution_note'] = 1;
88 $query->_tables
['civicrm_contribution'] = 1;
91 if (!empty($query->_returnProperties
['contribution_batch'])) {
92 $query->_select
['contribution_batch'] = "civicrm_batch.title as contribution_batch";
93 $query->_element
['contribution_batch'] = 1;
94 $query->_tables
['civicrm_financial_trxn'] = 1;
95 $query->_tables
['contribution_batch'] = 1;
98 if (!empty($query->_returnProperties
['contribution_campaign_title'])) {
99 $query->_select
['contribution_campaign_title'] = "civicrm_campaign.title as contribution_campaign_title";
100 $query->_element
['contribution_campaign_title'] = $query->_tables
['civicrm_campaign'] = 1;
103 self
::addSoftCreditFields($query);
109 * @param CRM_Contact_BAO_Query $query
111 public static function where(&$query) {
112 self
::initializeAnySoftCreditClause($query);
113 foreach (array_keys($query->_params
) as $id) {
114 if (empty($query->_params
[$id][0])) {
117 if (substr($query->_params
[$id][0], 0, 13) == 'contribution_' ||
substr($query->_params
[$id][0], 0, 10) == 'financial_' ||
substr($query->_params
[$id][0], 0, 8) == 'payment_') {
118 if ($query->_mode
== CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
119 $query->_useDistinct
= TRUE;
123 $query->_params
[$id][0] == 'contribution_type_id' ||
124 $query->_params
[$id][0] == 'contribution_type'
126 CRM_Core_Session
::setStatus(
127 ts('The contribution type criteria is now obsolete, please update your smart group'),
134 self
::whereClauseSingle($query->_params
[$id], $query);
140 * Get where clause for a single value.
142 * @param array $values
143 * @param CRM_Contact_BAO_Query $query
145 * @throws \CiviCRM_API3_Exception
146 * @throws \CRM_Core_Exception
148 public static function whereClauseSingle(&$values, &$query) {
149 list($name, $op, $value, $grouping, $wildcard) = $values;
152 $fields = self
::getFields();
154 if (!empty($value) && !is_array($value)) {
155 $quoteValue = "\"$value\"";
158 $recurrringFields = CRM_Contribute_BAO_ContributionRecur
::getRecurringFields();
159 unset($recurrringFields['contribution_recur_payment_made']);
160 foreach ($recurrringFields as $dateField => $dateFieldTitle) {
161 if (self
::buildDateWhere($values, $query, $name, $dateField, $dateFieldTitle)) {
165 // These are legacy names.
166 // @todo enotices when these are hit so we can start to elimnate them.
168 'financial_type' => 'financial_type_id',
169 'contribution_page' => 'contribution_page_id',
170 'payment_instrument' => 'payment_instrument_id',
171 // or payment_instrument_id?
172 'contribution_payment_instrument' => 'contribution_payment_instrument_id',
173 'contribution_status' => 'contribution_status_id',
176 $name = isset($fieldAliases[$name]) ?
$fieldAliases[$name] : $name;
178 if (in_array($name, $fieldAliases)) {
179 $qillName = array_search($name, $fieldAliases);
181 $pseudoExtraParam = [];
184 case 'contribution_date':
185 case 'contribution_date_low':
186 case 'contribution_date_low_time':
187 case 'contribution_date_high':
188 case 'contribution_date_high_time':
189 CRM_Core_Error
::deprecatedFunctionWarning('search by receive_date');
190 // process to / from date
191 $query->dateQueryBuilder($values,
192 'civicrm_contribution', 'contribution_date', 'receive_date', ts('Contribution Date')
196 case 'contribution_amount':
197 case 'contribution_amount_low':
198 case 'contribution_amount_high':
199 // process min/max amount
200 $query->numberRangeBuilder($values,
201 'civicrm_contribution', 'contribution_amount',
202 'total_amount', 'Contribution Amount',
207 case 'contribution_thankyou_date_is_not_null':
210 $query->_qill
[$grouping][] = ts('Contribution Thank-you Sent');
214 $query->_qill
[$grouping][] = ts('Contribution Thank-you Not Sent');
216 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause("civicrm_contribution.thankyou_date", $op);
217 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
220 case 'contribution_receipt_date_is_not_null':
223 $query->_qill
[$grouping][] = ts('Contribution Receipt Sent');
227 $query->_qill
[$grouping][] = ts('Contribution Receipt Not Sent');
229 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause("civicrm_contribution.receipt_date", $op);
230 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
233 case 'contribution_cancel_date':
234 case 'contribution_cancel_date_low':
235 case 'contribution_cancel_date_low_time':
236 case 'contribution_cancel_date_high':
237 case 'contribution_cancel_date_high_time':
238 // process to / from date
239 $query->dateQueryBuilder($values,
240 'civicrm_contribution', 'contribution_cancel_date', 'cancel_date', ts('Cancelled / Refunded Date')
244 case 'financial_type_id':
246 case 'invoice_number':
247 case 'payment_instrument_id':
248 case 'contribution_payment_instrument_id':
249 case 'contribution_page_id':
250 case 'contribution_status_id':
251 case 'contribution_id':
252 case 'contribution_currency_type':
253 case 'contribution_currency':
254 case 'contribution_source':
255 case 'contribution_trxn_id':
256 case 'contribution_check_number':
257 case 'contribution_contact_id':
258 case (strpos($name, '_amount') !== FALSE):
259 case (strpos($name, '_date') !== FALSE && $name != 'contribution_fulfilled_date'):
260 case 'contribution_campaign_id':
262 $fieldNamesNotToStripContributionFrom = [
263 'contribution_currency_type',
264 'contribution_status_id',
265 'contribution_page_id',
267 // @todo these are mostly legacy params. Find a better way to deal with them.
268 if (!in_array($name, $fieldNamesNotToStripContributionFrom)
270 if (!isset($fields[$name])) {
271 $qillName = str_replace('contribution_', '', $qillName);
273 $name = str_replace('contribution_', '', $name);
275 if (in_array($name, ['contribution_currency', 'contribution_currency_type'])) {
276 $qillName = $name = 'currency';
277 $pseudoExtraParam = ['labelColumn' => 'name'];
280 $dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type
::typeToString($fields[$qillName]['type']) : 'String';
282 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause("civicrm_contribution.$name", $op, $value, $dataType);
283 list($op, $value) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contribute_DAO_Contribution', $name, $value, $op, $pseudoExtraParam);
284 if (!($name == 'id' && $value == 0)) {
285 $query->_qill
[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
287 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
290 case 'contribution_pcp_made_through_id':
291 case 'contribution_soft_credit_type_id':
293 if ($name == 'contribution_pcp_made_through_id') {
294 $qillName = $name = 'pcp_id';
295 $fields[$name] = ['title' => ts('Personal Campaign Page'), 'type' => 2];
297 if ($name == 'contribution_soft_credit_type_id') {
298 $qillName = str_replace('_id', '', $qillName);
299 $fields[$qillName]['type'] = $fields[$qillName]['data_type'];
300 $name = str_replace('contribution_', '', $name);
302 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause("civicrm_contribution_soft.$name",
303 $op, $value, CRM_Utils_Type
::typeToString($fields[$qillName]['type'])
305 list($op, $value) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contribute_DAO_ContributionSoft', $name, $value, $op);
306 $query->_qill
[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
307 $query->_tables
['civicrm_contribution_soft'] = $query->_whereTables
['civicrm_contribution_soft'] = 1;
310 case 'contribution_or_softcredits':
311 if ($value == 'only_scredits') {
312 $query->_where
[$grouping][] = "contribution_search_scredit_combined.scredit_id IS NOT NULL";
313 $query->_qill
[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits Only');
314 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
315 $query->_tables
['civicrm_contribution_soft'] = $query->_whereTables
['civicrm_contribution_soft'] = 1;
317 elseif ($value == 'both_related') {
318 $query->_where
[$grouping][] = "contribution_search_scredit_combined.filter_id IS NOT NULL";
319 $query->_qill
[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits with related Hard Credit');
320 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
321 $query->_tables
['civicrm_contribution_soft'] = $query->_whereTables
['civicrm_contribution_soft'] = 1;
323 elseif ($value == 'both') {
324 $query->_qill
[$grouping][] = ts('Contributions OR Soft Credits? - Both');
325 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
326 $query->_tables
['civicrm_contribution_soft'] = $query->_whereTables
['civicrm_contribution_soft'] = 1;
328 // default option: $value == 'only_contribs'
331 case 'contribution_is_test':
332 // By default is Contribution Search form we choose is_test = 0 in otherwords always show active contribution
333 // so in case if any one choose any Yes/No avoid the default clause otherwise it will be conflict in whereClause
334 $key = array_search('civicrm_contribution.is_test = 0', $query->_where
[$grouping]);
336 unset($query->_where
[$grouping][$key]);
338 case 'contribution_test':
339 // We dont want to include all tests for sql OR CRM-7827
340 if (!$value ||
$query->getOperator() != 'OR') {
341 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause("civicrm_contribution.is_test", $op, $value, "Boolean");
343 $query->_qill
[$grouping][] = ts("Only Display Test Contributions");
345 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
349 case 'contribution_is_pay_later':
350 case 'contribution_pay_later':
351 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause("civicrm_contribution.is_pay_later", $op, $value, "Boolean");
353 $query->_qill
[$grouping][] = ts("Find Pay Later Contributions");
356 $query->_qill
[$grouping][] = ts("Exclude Pay Later Contributions");
358 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
361 case 'contribution_recurring':
363 $query->_where
[$grouping][] = "civicrm_contribution.contribution_recur_id IS NOT NULL";
364 $query->_qill
[$grouping][] = ts("Find Recurring Contributions");
365 $query->_tables
['civicrm_contribution_recur'] = $query->_whereTables
['civicrm_contribution_recur'] = 1;
368 $query->_where
[$grouping][] = "civicrm_contribution.contribution_recur_id IS NULL";
369 $query->_qill
[$grouping][] = ts("Exclude Recurring Contributions");
373 case 'contribution_recur_id':
374 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause("civicrm_contribution.contribution_recur_id",
375 $op, $value, "Integer"
377 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
380 case 'contribution_recur_payment_processor_id':
381 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause("civicrm_contribution_recur.payment_processor_id", $op, $value, "String");
382 $paymentProcessors = civicrm_api3('PaymentProcessor', 'get', []);
383 $paymentProcessorNames = [];
384 foreach ($value as $paymentProcessorId) {
385 $paymentProcessorNames[] = $paymentProcessors['values'][$paymentProcessorId]['name'];
387 $query->_qill
[$grouping][] = ts("Recurring Contribution Payment Processor %1 %2", [1 => $op, 2 => implode(', ', $paymentProcessorNames)]);
388 $query->_tables
['civicrm_contribution_recur'] = $query->_whereTables
['civicrm_contribution_recur'] = 1;
391 case 'contribution_recur_processor_id':
392 case 'contribution_recur_trxn_id':
393 $spec = $fields[$name];
394 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($spec['where'],
395 $op, $value, "String"
397 $query->_qill
[$grouping][] = ts("Recurring Contribution %1 %2 '%3'", [1 => $fields[$name]['title'], 2 => $op, 3 => $value]);
398 $query->_tables
[$spec['table_name']] = $query->_whereTables
[$spec['table_name']] = 1;
401 case 'contribution_recur_payment_made':
402 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause("civicrm_contribution_recur.id", 'IS NOT EMPTY');
404 $query->_qill
[$grouping][] = ts("Recurring contributions with at least one payment");
405 self
::$_contribRecurPayment = TRUE;
408 $query->_qill
[$grouping][] = ts("All recurring contributions regardless of payments");
409 self
::$_contribRecurPayment = FALSE;
411 $query->_tables
['civicrm_contribution_recur'] = $query->_whereTables
['civicrm_contribution_recur'] = 1;
414 case 'contribution_recur_contribution_status_id':
415 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause("civicrm_contribution_recur.contribution_status_id", $op, $value, 'String');
416 list($op, $value) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contribute_DAO_ContributionRecur', 'contribution_status_id', $value, $op, $pseudoExtraParam);
417 $query->_qill
[$grouping][] = ts("Recurring Contribution Status %1 '%2'", [1 => $op, 2 => $value]);
418 $query->_tables
['civicrm_contribution_recur'] = $query->_whereTables
['civicrm_contribution_recur'] = 1;
421 case 'contribution_note':
422 $value = CRM_Core_DAO
::escapeString($value);
427 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause('civicrm_note.note', $op, $value, "String");
428 $query->_qill
[$grouping][] = ts('Contribution Note %1 %2', [1 => $op, 2 => $quoteValue]);
429 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = $query->_whereTables
['contribution_note'] = 1;
432 case 'contribution_membership_id':
433 $query->_where
[$grouping][] = " civicrm_membership.id $op $value";
434 $query->_tables
['contribution_membership'] = $query->_whereTables
['contribution_membership'] = 1;
438 case 'contribution_participant_id':
439 $query->_where
[$grouping][] = " civicrm_participant.id $op $value";
440 $query->_tables
['contribution_participant'] = $query->_whereTables
['contribution_participant'] = 1;
443 case 'contribution_pcp_display_in_roll':
444 $query->_where
[$grouping][] = " civicrm_contribution_soft.pcp_display_in_roll $op '$value'";
446 $query->_qill
[$grouping][] = ts("Personal Campaign Page Honor Roll");
449 $query->_qill
[$grouping][] = ts("NOT Personal Campaign Page Honor Roll");
451 $query->_tables
['civicrm_contribution_soft'] = $query->_whereTables
['civicrm_contribution_soft'] = 1;
454 case 'contribution_batch_id':
455 list($qillOp, $qillValue) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Batch_BAO_EntityBatch', 'batch_id', $value, $op);
456 $query->_qill
[$grouping][] = ts('Batch Name %1 %2', [1 => $qillOp, 2 => $qillValue]);
457 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause('civicrm_entity_batch.batch_id', $op, $value);
458 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
459 $query->_tables
['civicrm_financial_trxn'] = $query->_whereTables
['civicrm_financial_trxn'] = 1;
460 $query->_tables
['contribution_batch'] = $query->_whereTables
['contribution_batch'] = 1;
463 case 'contribution_product_id':
464 // CRM-16713 - contribution search by premiums on 'Find Contribution' form.
466 list($operator, $productValue) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contribute_DAO_Product', $name, $value, $op);
467 $query->_qill
[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $operator, 3 => $productValue]);
468 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause("civicrm_product.id", $op, $value);
469 $query->_tables
['civicrm_product'] = $query->_whereTables
['civicrm_product'] = 1;
472 case 'contribution_is_payment':
473 $query->_where
[$grouping][] = " civicrm_financial_trxn.is_payment $op $value";
474 $query->_tables
['civicrm_financial_trxn'] = $query->_whereTables
['civicrm_financial_trxn'] = 1;
477 case 'financial_trxn_card_type_id':
478 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause('civicrm_financial_trxn.card_type_id', $op, $value);
479 $query->_tables
['civicrm_financial_trxn'] = $query->_whereTables
['civicrm_financial_trxn'] = 1;
480 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
481 list($op, $value) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Financial_DAO_FinancialTrxn', 'card_type_id', $value, $op);
482 $query->_qill
[$grouping][] = ts('Card Type %1 %2', [1 => $op, 2 => $value]);
485 case 'financial_trxn_pan_truncation':
486 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause('civicrm_financial_trxn.pan_truncation', $op, $value);
487 $query->_tables
['civicrm_financial_trxn'] = $query->_whereTables
['civicrm_financial_trxn'] = 1;
488 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
489 list($op, $value) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Financial_DAO_FinancialTrxn', 'pan_truncation', $value, $op);
490 $query->_qill
[$grouping][] = ts('Card Number %1 %2', [1 => $op, 2 => $value]);
494 //all other elements are handle in this case
495 $fldName = substr($name, 13);
496 if (!isset($fields[$fldName])) {
498 CRM_Core_Session
::setStatus(ts(
499 'We did not recognize the search field: %1. Please check and fix your contribution related smart groups.',
505 $whereTable = $fields[$fldName];
506 if (!is_array($value)) {
507 $value = trim($value);
510 $dataType = "String";
511 if (!empty($whereTable['type'])) {
512 $dataType = CRM_Utils_Type
::typeToString($whereTable['type']);
515 $query->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($whereTable['where'], $op, $value, $dataType);
516 $query->_qill
[$grouping][] = "$whereTable[title] $op $quoteValue";
517 list($tableName) = explode('.', $whereTable['where'], 2);
518 $query->_tables
[$tableName] = $query->_whereTables
[$tableName] = 1;
519 if ($tableName == 'civicrm_contribution_product') {
520 $query->_tables
['civicrm_product'] = $query->_whereTables
['civicrm_product'] = 1;
521 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
524 $query->_tables
['civicrm_contribution'] = $query->_whereTables
['civicrm_contribution'] = 1;
532 * @param string $name
533 * @param string $mode
534 * @param string $side
536 * @return NULL|string
538 public static function from($name, $mode, $side) {
541 case 'civicrm_contribution':
542 $from = " $side JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id ";
543 if (in_array(self
::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
544 // switch the from table if its only soft credit search
545 $from = " $side JOIN contribution_search_scredit_combined ON contribution_search_scredit_combined.contact_id = contact_a.id ";
546 $from .= " $side JOIN civicrm_contribution ON civicrm_contribution.id = contribution_search_scredit_combined.id ";
547 $from .= " $side JOIN civicrm_contribution_soft ON civicrm_contribution_soft.id = contribution_search_scredit_combined.scredit_id";
551 case 'civicrm_contribution_recur':
553 // 'Made payment for the recurring contributions?' is ticked yes
554 $from = " $side JOIN civicrm_contribution_recur ON contact_a.id = civicrm_contribution_recur.contact_id ";
555 if (self
::$_contribRecurPayment == TRUE) {
556 $from .= " INNER JOIN civicrm_contribution cr ON cr.contribution_recur_id = civicrm_contribution_recur.id ";
560 $from = " $side JOIN civicrm_contribution_recur ON civicrm_contribution.contribution_recur_id = civicrm_contribution_recur.id ";
564 case 'civicrm_financial_type':
565 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
566 $from = " INNER JOIN civicrm_financial_type ON civicrm_contribution.financial_type_id = civicrm_financial_type.id ";
569 $from = " $side JOIN civicrm_financial_type ON civicrm_contribution.financial_type_id = civicrm_financial_type.id ";
573 case 'civicrm_financial_account':
574 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
575 $from = " $side JOIN civicrm_financial_account ON contact_a.id = civicrm_financial_account.contact_id ";
579 case 'civicrm_accounting_code':
580 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
581 $from = " $side JOIN civicrm_entity_financial_account ON civicrm_entity_financial_account.entity_id = civicrm_contribution.financial_type_id AND civicrm_entity_financial_account.entity_table = 'civicrm_financial_type' ";
582 $from .= " INNER JOIN civicrm_financial_account ON civicrm_financial_account.id = civicrm_entity_financial_account.financial_account_id ";
583 $from .= " INNER JOIN civicrm_option_value cov ON cov.value = civicrm_entity_financial_account.account_relationship AND cov.name = 'Income Account is' ";
584 $from .= " INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id AND cog.name = 'account_relationship' ";
588 case 'civicrm_contribution_page':
589 $from = " $side JOIN civicrm_contribution_page ON civicrm_contribution.contribution_page_id = civicrm_contribution_page.id";
592 case 'civicrm_product':
593 $from = " $side JOIN civicrm_contribution_product ON civicrm_contribution_product.contribution_id = civicrm_contribution.id";
594 $from .= " $side JOIN civicrm_product ON civicrm_contribution_product.product_id =civicrm_product.id ";
597 case 'contribution_softcredit_type':
598 $from = " $side JOIN civicrm_option_group option_group_contribution_softcredit_type ON
599 (option_group_contribution_softcredit_type.name = 'soft_credit_type')";
600 $from .= " $side JOIN civicrm_option_value contribution_softcredit_type ON
601 ( civicrm_contribution_soft.soft_credit_type_id = contribution_softcredit_type.value
602 AND option_group_contribution_softcredit_type.id = contribution_softcredit_type.option_group_id )";
605 case 'contribution_note':
606 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contribution' AND
607 civicrm_contribution.id = civicrm_note.entity_id )";
610 case 'contribution_membership':
611 $from = " $side JOIN civicrm_membership_payment ON civicrm_membership_payment.contribution_id = civicrm_contribution.id";
612 $from .= " $side JOIN civicrm_membership ON civicrm_membership_payment.membership_id = civicrm_membership.id ";
615 case 'civicrm_campaign':
616 //CRM-16764 - get survey clause from campaign bao
617 if (!CRM_Campaign_BAO_Query
::$_applySurveyClause) {
618 $from = " $side JOIN civicrm_campaign ON civicrm_campaign.id = civicrm_contribution.campaign_id";
622 case 'contribution_participant':
623 $from = " $side JOIN civicrm_participant_payment ON civicrm_participant_payment.contribution_id = civicrm_contribution.id";
624 $from .= " $side JOIN civicrm_participant ON civicrm_participant_payment.participant_id = civicrm_participant.id ";
627 case 'civicrm_contribution_soft':
628 if (!in_array(self
::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
629 $from = " $side JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id";
633 case 'civicrm_contribution_soft_contact':
634 if (in_array(self
::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
635 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution.contact_id = civicrm_contact_d.id )
636 AND contribution_search_scredit_combined.scredit_id IS NOT NULL";
639 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution_soft.contact_id = civicrm_contact_d.id )";
643 case 'civicrm_contribution_soft_email':
644 $from .= " $side JOIN civicrm_email as soft_email ON (civicrm_contact_d.id = soft_email.contact_id )";
647 case 'civicrm_contribution_soft_phone':
648 $from .= " $side JOIN civicrm_phone as soft_phone ON (civicrm_contact_d.id = soft_phone.contact_id )";
651 case 'contribution_batch':
652 $from .= " $side JOIN civicrm_entity_batch ON ( civicrm_entity_batch.entity_table = 'civicrm_financial_trxn'
653 AND civicrm_financial_trxn.id = civicrm_entity_batch.entity_id )";
655 $from .= " $side JOIN civicrm_batch ON civicrm_entity_batch.batch_id = civicrm_batch.id";
658 case 'civicrm_financial_trxn':
659 $from .= " $side JOIN civicrm_entity_financial_trxn ON (
660 civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution'
661 AND civicrm_contribution.id = civicrm_entity_financial_trxn.entity_id )";
663 $from .= " $side JOIN civicrm_financial_trxn ON (
664 civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id )";
671 * Initialise the soft credit clause.
673 * @param CRM_Contact_BAO_Query $query
675 public static function initializeAnySoftCreditClause(&$query) {
676 // @todo have a generic initialize on all components that gets called every query
677 // & rename this to match that fn name.
678 if ($query->_mode
& CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
679 if (self
::isSoftCreditOptionEnabled($query->_params
)) {
680 unset($query->_distinctComponentClause
);
681 $query->_rowCountClause
= " count(civicrm_contribution.id)";
682 $query->_groupByComponentClause
= " GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.contact_id, contribution_search_scredit_combined.scredit_id ";
685 $query->_distinctComponentClause
= ' civicrm_contribution.id';
691 * Check if soft credits are enables.
693 * @param array $queryParams
697 public static function isSoftCreditOptionEnabled($queryParams = []) {
698 static $tempTableFilled = FALSE;
699 if (!empty($queryParams)) {
700 foreach (array_keys($queryParams) as $id) {
701 if (empty($queryParams[$id][0])) {
704 if ($queryParams[$id][0] == 'contribution_or_softcredits') {
705 self
::$_contribOrSoftCredit = $queryParams[$id][2];
709 if (in_array(self
::$_contribOrSoftCredit,
710 ["only_scredits", "both_related", "both"])) {
711 if (!$tempTableFilled) {
712 // build a temp table which is union of contributions and soft credits
713 // note: group-by in first part ensures uniqueness in counts
715 CREATE TEMPORARY TABLE IF NOT EXISTS contribution_search_scredit_combined AS
716 SELECT con.id as id, con.contact_id, cso.id as filter_id, NULL as scredit_id
717 FROM civicrm_contribution con
718 LEFT JOIN civicrm_contribution_soft cso ON con.id = cso.contribution_id
719 GROUP BY id, contact_id, scredit_id, cso.id
721 SELECT scredit.contribution_id as id, scredit.contact_id, scredit.id as filter_id, scredit.id as scredit_id
722 FROM civicrm_contribution_soft as scredit";
723 CRM_Core_DAO
::executeQuery($tempQuery);
724 $tempTableFilled = TRUE;
732 * Get return properties for soft credits.
734 * @param bool $isExportMode
738 public static function softCreditReturnProperties($isExportMode = FALSE) {
740 'contribution_soft_credit_name' => 1,
741 'contribution_soft_credit_amount' => 1,
742 'contribution_soft_credit_type' => 1,
745 $properties['contribution_soft_credit_contact_id'] = 1;
746 $properties['contribution_soft_credit_contribution_id'] = 1;
752 * Get the list of fields required to populate the selector.
754 * The default return properties array returns far too many fields for 'everyday use. Every field you add to this array
755 * kills a small kitten so add carefully.
757 * @param array $queryParams
760 public static function selectorReturnProperties($queryParams) {
763 'contact_sub_type' => 1,
765 'financial_type' => 1,
766 'contribution_source' => 1,
770 'thankyou_date' => 1,
772 // Without this value here we get an e-notice BUT the value does not appear to be rendered anywhere.
773 'contribution_campaign_id' => 1,
774 'contribution_status_id' => 1,
775 // @todo return this & fix query to do pseudoconstant thing.
776 'contribution_status' => 1,
779 'contribution_recur_id' => 1,
781 if (self
::isSiteHasProducts()) {
782 $properties['product_name'] = 1;
783 $properties['contribution_product_id'] = 1;
785 if (self
::isSoftCreditOptionEnabled($queryParams)) {
786 $properties = array_merge($properties, self
::softCreditReturnProperties());
793 * Do any products exist in this site's database.
797 public static function isSiteHasProducts() {
798 if (!isset(\Civi
::$statics[__CLASS__
]['has_products'])) {
799 \Civi
::$statics[__CLASS__
]['has_products'] = (bool) CRM_Core_DAO
::singleValueQuery('SELECT id FROM civicrm_contribution_product LIMIT 1');
801 return \Civi
::$statics[__CLASS__
]['has_products'];
805 * Function you should avoid.
807 * This function returns default properties for contribution queries. However, they are
808 * far more than are required in 'most' cases and you should always try to return the return properties
809 * you actually require.
811 * It would be nice to throw an e-notice when this is called but it would trash the tests :-(.
814 * @param bool $includeCustomFields
818 public static function defaultReturnProperties($mode, $includeCustomFields = TRUE) {
820 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
825 'contact_sub_type' => 1,
831 'financial_type' => 1,
833 'contribution_source' => 1,
837 'thankyou_date' => 1,
839 'contribution_cancel_date' => 1,
843 'accounting_code' => 1,
845 'payment_instrument' => 1,
847 'payment_instrument_id' => 1,
849 'contribution_check_number' => 1,
851 'non_deductible_amount' => 1,
860 'invoice_number' => 1,
864 'cancel_reason' => 1,
878 'contribution_status' => 1,
880 'contribution_status_id' => 1,
882 'contribution_recur_id' => 1,
886 'contribution_note' => 1,
888 'contribution_batch' => 1,
890 'contribution_campaign_title' => 1,
892 'contribution_campaign_id' => 1,
896 if (self
::isSiteHasProducts()) {
897 $properties['fulfilled_date'] = 1;
898 $properties['product_name'] = 1;
899 $properties['contribution_product_id'] = 1;
900 $properties['product_option'] = 1;
901 $properties['sku'] = 1;
902 $properties['contribution_start_date'] = 1;
903 $properties['contribution_end_date'] = 1;
905 if (self
::isSoftCreditOptionEnabled()) {
906 $properties = array_merge($properties, self
::softCreditReturnProperties());
908 if ($includeCustomFields) {
909 // also get all the custom contribution properties
910 $fields = CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution');
911 if (!empty($fields)) {
912 foreach ($fields as $name => $dontCare) {
913 $properties[$name] = 1;
922 * Get the metadata for fields to be included on the search form.
924 * @throws \CiviCRM_API3_Exception
926 public static function getSearchFieldMetadata() {
928 'contribution_source',
932 'contribution_cancel_date',
934 $metadata = civicrm_api3('Contribution', 'getfields', [])['values'];
935 return array_intersect_key($metadata, array_flip($fields));
939 * Add all the elements shared between contribute search and advnaced search.
941 * @param \CRM_Contribute_Form_Search $form
943 * @throws \CRM_Core_Exception
944 * @throws \CiviCRM_API3_Exception
946 public static function buildSearchForm(&$form) {
948 $form->addSearchFieldMetadata(['Contribution' => self
::getSearchFieldMetadata()]);
949 $form->addFormFieldsFromMetadata();
951 $form->add('text', 'contribution_amount_low', ts('From'), ['size' => 8, 'maxlength' => 8]);
952 $form->addRule('contribution_amount_low', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money
::format('9.99', ' ')]), 'money');
954 $form->add('text', 'contribution_amount_high', ts('To'), ['size' => 8, 'maxlength' => 8]);
955 $form->addRule('contribution_amount_high', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money
::format('99.99', ' ')]), 'money');
957 // Adding select option for curreny type -- CRM-4711
958 $form->add('select', 'contribution_currency_type',
963 CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'currency', ['labelColumn' => 'name']),
964 FALSE, ['class' => 'crm-select2']
968 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, CRM_Core_Action
::VIEW
);
969 $form->addSelect('financial_type_id',
970 ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => $financialTypes]
973 $form->add('select', 'contribution_page_id',
974 ts('Contribution Page'),
975 CRM_Contribute_PseudoConstant
::contributionPage(),
976 FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]
979 // use contribution_payment_instrument_id instead of payment_instrument_id
980 // Contribution Edit form (pop-up on contribution/Contact(display Result as Contribution) open on search form),
981 // then payment method change action not working properly because of same html ID present two time on one page
982 $form->addSelect('contribution_payment_instrument_id',
983 ['entity' => 'contribution', 'field' => 'payment_instrument_id', 'multiple' => 'multiple', 'label' => ts('Payment Method'), 'option_url' => NULL, 'placeholder' => ts('- any -')]
987 'contribution_pcp_made_through_id',
988 ts('Personal Campaign Page'),
989 CRM_Contribute_PseudoConstant
::pcPage(), FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]);
991 $statusValues = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id');
992 $form->add('select', 'contribution_status_id',
993 ts('Contribution Status'), $statusValues,
994 FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']
997 // Add fields for thank you and receipt
998 $form->addYesNo('contribution_thankyou_date_is_not_null', ts('Thank-you sent?'), TRUE);
999 $form->addYesNo('contribution_receipt_date_is_not_null', ts('Receipt sent?'), TRUE);
1001 $form->addYesNo('contribution_pay_later', ts('Contribution is Pay Later?'), TRUE);
1002 $form->addYesNo('contribution_recurring', ts('Contribution is Recurring?'), TRUE);
1004 $form->addYesNo('contribution_test', ts('Contribution is a Test?'), TRUE);
1006 // Add field for transaction ID search
1007 $form->addElement('text', 'contribution_trxn_id', ts("Transaction ID"));
1008 $form->addElement('text', 'contribution_check_number', ts('Check Number'));
1010 // Add field for pcp display in roll search
1011 $form->addYesNo('contribution_pcp_display_in_roll', ts('Personal Campaign Page Honor Roll?'), TRUE);
1013 // Soft credit related fields
1015 'only_contribs' => ts('Contributions Only'),
1016 'only_scredits' => ts('Soft Credits Only'),
1017 'both_related' => ts('Soft Credits with related Hard Credit'),
1018 'both' => ts('Both'),
1020 $form->add('select', 'contribution_or_softcredits', ts('Contributions OR Soft Credits?'), $options, FALSE, ['class' => "crm-select2"]);
1022 'contribution_soft_credit_type_id',
1024 'entity' => 'contribution_soft',
1025 'field' => 'soft_credit_type_id',
1027 'context' => 'search',
1031 $form->addField('financial_trxn_card_type_id', ['entity' => 'FinancialTrxn', 'name' => 'card_type_id', 'action' => 'get']);
1033 $form->add('text', 'financial_trxn_pan_truncation', ts('Card Number'), [
1036 'autocomplete' => 'off',
1039 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
1040 // CRM-16713 - contribution search by premiums on 'Find Contribution' form.
1041 $form->add('select', 'contribution_product_id',
1043 CRM_Contribute_PseudoConstant
::products(),
1045 'class' => 'crm-select2',
1046 'multiple' => 'multiple',
1047 'placeholder' => ts('- any -'),
1052 self
::addCustomFormFields($form, ['Contribution']);
1054 CRM_Campaign_BAO_Campaign
::addCampaignInComponentSearch($form, 'contribution_campaign_id');
1057 $batches = CRM_Contribute_PseudoConstant
::batch();
1059 if (!empty($batches)) {
1060 $form->add('select', 'contribution_batch_id',
1063 '' => ts('- any -'),
1065 'IS NULL' => ts('None'),
1067 FALSE, ['class' => 'crm-select2']
1071 $form->assign('validCiviContribute', TRUE);
1072 $form->setDefaults(['contribution_test' => 0]);
1074 CRM_Contribute_BAO_ContributionRecur
::recurringContribution($form);
1080 * @todo better function comment needed - what IS the point of this?
1082 * @param array $tables
1084 public static function tableNames(&$tables) {
1085 // Add contribution table
1086 if (!empty($tables['civicrm_product'])) {
1087 $tables = array_merge(['civicrm_contribution' => 1], $tables);
1090 if (!empty($tables['civicrm_contribution_product']) && empty($tables['civicrm_product'])) {
1091 $tables['civicrm_product'] = 1;
1096 * Add the where for dates.
1098 * @param array $values
1099 * Array of query values.
1100 * @param object $query
1102 * @param string $name
1103 * Query field that is set.
1104 * @param string $field
1105 * Name of field to be set.
1106 * @param string $title
1107 * Title of the field.
1111 public static function buildDateWhere(&$values, $query, $name, $field, $title) {
1112 $fieldPart = strpos($name, $field);
1113 if ($fieldPart === FALSE) {
1116 // we only have recurring dates using this ATM so lets' short cut to find the table name
1117 $table = 'contribution_recur';
1118 $fieldName = explode($table . '_', $field);
1119 $query->dateQueryBuilder($values,
1120 'civicrm_' . $table, $field, $fieldName[1], $title
1126 * Add the soft credit fields to the select fields.
1128 * Extracted into separate function to improve readability of main select function.
1132 private static function addSoftCreditFields(&$query) {
1133 $includeSoftCredits = self
::isSoftCreditOptionEnabled($query->_params
);
1134 if (!empty($query->_returnProperties
['contribution_soft_credit_name'])) {
1135 if ($includeSoftCredits) {
1136 $query->_select
['contribution_soft_credit_name'] = "civicrm_contact_d.sort_name as contribution_soft_credit_name";
1137 // also include contact id. Will help build hyperlinks
1138 $query->_select
['contribution_soft_credit_contact_id'] = "civicrm_contact_d.id as contribution_soft_credit_contact_id";
1140 $query->_element
['contribution_soft_credit_name'] = 1;
1141 $query->_element
['contribution_soft_credit_contact_id'] = 1;
1143 $query->_tables
['civicrm_contribution'] = 1;
1144 $query->_tables
['civicrm_contribution_soft'] = 1;
1145 $query->_tables
['civicrm_contribution_soft_contact'] = 1;
1148 if (!empty($query->_returnProperties
['contribution_soft_credit_contact_id'])) {
1149 $query->_tables
['civicrm_contribution'] = 1;
1150 $query->_tables
['civicrm_contribution_soft'] = 1;
1151 $query->_tables
['civicrm_contribution_soft_contact'] = 1;
1154 if (!empty($query->_returnProperties
['contribution_soft_credit_amount'])) {
1155 if ($includeSoftCredits) {
1156 $query->_select
['contribution_soft_credit_amount'] = "civicrm_contribution_soft.amount as contribution_soft_credit_amount";
1158 $query->_element
['contribution_soft_credit_amount'] = 1;
1159 $query->_tables
['civicrm_contribution'] = 1;
1160 $query->_tables
['civicrm_contribution_soft'] = 1;
1163 if (!empty($query->_returnProperties
['contribution_soft_credit_type'])) {
1164 if ($includeSoftCredits) {
1165 $query->_select
['contribution_soft_credit_type'] = "contribution_softcredit_type.label as contribution_soft_credit_type";
1167 $query->_element
['contribution_soft_credit_type'] = 1;
1168 $query->_tables
['civicrm_contribution'] = 1;
1169 $query->_tables
['contribution_softcredit_type'] = 1;
1172 if (!empty($query->_returnProperties
['contribution_soft_credit_contribution_id'])) {
1173 if ($includeSoftCredits) {
1174 $query->_select
['contribution_soft_credit_contribution_id'] = "civicrm_contribution_soft.contribution_id as contribution_soft_credit_contribution_id";
1176 $query->_element
['contribution_soft_credit_contribution_id'] = 1;
1177 $query->_tables
['civicrm_contribution'] = 1;
1178 $query->_tables
['civicrm_contribution_soft'] = 1;
1181 if (!empty($query->_returnProperties
['contribution_soft_credit_email'])) {
1182 $query->_select
['contribution_soft_credit_email'] = "soft_email.email as contribution_soft_credit_email";
1183 $query->_element
['contribution_soft_credit_email'] = 1;
1184 $query->_tables
['civicrm_contribution'] = 1;
1185 $query->_tables
['civicrm_contribution_soft'] = 1;
1186 $query->_tables
['civicrm_contribution_soft_contact'] = 1;
1187 $query->_tables
['civicrm_contribution_soft_email'] = 1;
1190 if (!empty($query->_returnProperties
['contribution_soft_credit_phone'])) {
1191 $query->_select
['contribution_soft_credit_email'] = "soft_phone.phone as contribution_soft_credit_phone";
1192 $query->_element
['contribution_soft_credit_phone'] = 1;
1193 $query->_tables
['civicrm_contribution'] = 1;
1194 $query->_tables
['civicrm_contribution_soft'] = 1;
1195 $query->_tables
['civicrm_contribution_soft_contact'] = 1;
1196 $query->_tables
['civicrm_contribution_soft_phone'] = 1;
1199 if (!empty($query->_returnProperties
['contribution_soft_credit_pcp_id'])) {
1200 $query->_select
['contribution_soft_credit_pcp_id'] = "civicrm_contribution_soft.pcp_id as contribution_soft_credit_pcp_id";
1201 $query->_element
['contribution_soft_credit_pcp_id'] = 1;
1202 $query->_tables
['civicrm_contribution'] = 1;
1203 $query->_tables
['civicrm_contribution_soft'] = 1;