Merge pull request #14590 from colemanw/i18nApi
[civicrm-core.git] / CRM / Contribute / BAO / Query.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035 32 */
86a0d21e 33class CRM_Contribute_BAO_Query extends CRM_Core_BAO_Query {
6a488035 34
1330f57a 35 public static $_contribOrSoftCredit = "only_contribs";
3dbf477c 36
1330f57a 37 public static $_contribRecurPayment = NULL;
95974e8e 38
6a488035 39 /**
8f165fa5 40 * Function get the searchable fields for contribution.
41 *
42 * This is basically the contribution fields plus some related entity fields.
6a488035 43 *
e9ff5391 44 * @param bool $checkPermission
45 *
a6c01b45 46 * @return array
e9ff5391 47 * Associative array of contribution fields
6a488035 48 */
0ed9f379 49 public static function getFields($checkPermission = TRUE) {
23faf53d 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));
a0090e6b 56 CRM_Contribute_BAO_Contribution::appendPseudoConstantsToFields($fields);
6a488035 57 unset($fields['contribution_contact_id']);
33a766c6 58 \Civi::$statics[__CLASS__]['fields']['contribution'] = $fields;
6a488035 59 }
33a766c6 60 return \Civi::$statics[__CLASS__]['fields']['contribution'];
6a488035
TO
61 }
62
63 /**
7fe37828 64 * If contributions are involved, add the specific contribute fields.
6a488035 65 *
35e6241a 66 * @param CRM_Contact_BAO_Query $query
6a488035 67 */
00be9182 68 public static function select(&$query) {
6a488035
TO
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;
74 }
75
6a488035 76 // get accounting code
a7488080 77 if (!empty($query->_returnProperties['accounting_code'])) {
353ffa53 78 $query->_select['accounting_code'] = "civicrm_financial_account.accounting_code as accounting_code";
6a488035
TO
79 $query->_element['accounting_code'] = 1;
80 $query->_tables['civicrm_accounting_code'] = 1;
81 $query->_tables['civicrm_financial_account'] = 1;
82 }
39b795ba 83
a7488080 84 if (!empty($query->_returnProperties['contribution_note'])) {
6a488035
TO
85 $query->_select['contribution_note'] = "civicrm_note.note as contribution_note";
86 $query->_element['contribution_note'] = 1;
87 $query->_tables['contribution_note'] = 1;
739189e4 88 $query->_tables['civicrm_contribution'] = 1;
6a488035
TO
89 }
90
a7488080 91 if (!empty($query->_returnProperties['contribution_batch'])) {
6a488035
TO
92 $query->_select['contribution_batch'] = "civicrm_batch.title as contribution_batch";
93 $query->_element['contribution_batch'] = 1;
898bfdcd 94 $query->_tables['civicrm_financial_trxn'] = 1;
6a488035
TO
95 $query->_tables['contribution_batch'] = 1;
96 }
97
9ebd3386 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;
101 }
739a8336 102
686df921 103 self::addSoftCreditFields($query);
6a488035
TO
104 }
105
186c9c17 106 /**
35e6241a
EM
107 * Get where clause.
108 *
109 * @param CRM_Contact_BAO_Query $query
186c9c17 110 */
00be9182 111 public static function where(&$query) {
f654cacf 112 self::initializeAnySoftCreditClause($query);
6a488035 113 foreach (array_keys($query->_params) as $id) {
a7488080 114 if (empty($query->_params[$id][0])) {
6a488035
TO
115 continue;
116 }
afa0b07c 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_') {
6a488035
TO
118 if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
119 $query->_useDistinct = TRUE;
120 }
39b795ba
DL
121 // CRM-12065
122 if (
123 $query->_params[$id][0] == 'contribution_type_id' ||
124 $query->_params[$id][0] == 'contribution_type'
125 ) {
126 CRM_Core_Session::setStatus(
127 ts('The contribution type criteria is now obsolete, please update your smart group'),
128 '',
129 'alert'
130 );
131 continue;
132 }
133
6a488035
TO
134 self::whereClauseSingle($query->_params[$id], $query);
135 }
136 }
6a488035
TO
137 }
138
186c9c17 139 /**
35e6241a
EM
140 * Get where clause for a single value.
141 *
142 * @param array $values
143 * @param CRM_Contact_BAO_Query $query
7123f88c 144 *
145 * @throws \CiviCRM_API3_Exception
146 * @throws \CRM_Core_Exception
186c9c17 147 */
00be9182 148 public static function whereClauseSingle(&$values, &$query) {
6a488035
TO
149 list($name, $op, $value, $grouping, $wildcard) = $values;
150
dbc6f6d6 151 $quoteValue = NULL;
9d5c7f14 152 $fields = self::getFields();
163b1da9
KJ
153
154 if (!empty($value) && !is_array($value)) {
6a488035
TO
155 $quoteValue = "\"$value\"";
156 }
157
24782d26 158 $recurrringFields = CRM_Contribute_BAO_ContributionRecur::getRecurringFields();
159 unset($recurrringFields['contribution_recur_payment_made']);
160 foreach ($recurrringFields as $dateField => $dateFieldTitle) {
22e263ad 161 if (self::buildDateWhere($values, $query, $name, $dateField, $dateFieldTitle)) {
a91e698a 162 return;
163 }
164 }
e38abf14 165 // These are legacy names.
166 // @todo enotices when these are hit so we can start to elimnate them.
be2fb01f 167 $fieldAliases = [
e38abf14 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',
be2fb01f 174 ];
4fc150ab 175
e38abf14 176 $name = isset($fieldAliases[$name]) ? $fieldAliases[$name] : $name;
3123273f 177 $qillName = $name;
4fc150ab 178 if (in_array($name, $fieldAliases)) {
179 $qillName = array_search($name, $fieldAliases);
180 }
be2fb01f 181 $pseudoExtraParam = [];
3123273f 182
6a488035
TO
183 switch ($name) {
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':
0ae18acf 189 CRM_Core_Error::deprecatedFunctionWarning('search by receive_date');
6a488035
TO
190 // process to / from date
191 $query->dateQueryBuilder($values,
70c907d4 192 'civicrm_contribution', 'contribution_date', 'receive_date', ts('Contribution Date')
6a488035
TO
193 );
194 return;
195
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',
203 NULL
204 );
205 return;
206
6a488035
TO
207 case 'contribution_thankyou_date_is_not_null':
208 if ($value) {
209 $op = "IS NOT NULL";
210 $query->_qill[$grouping][] = ts('Contribution Thank-you Sent');
211 }
212 else {
213 $op = "IS NULL";
214 $query->_qill[$grouping][] = ts('Contribution Thank-you Not Sent');
215 }
216 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.thankyou_date", $op);
217 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
218 return;
219
220 case 'contribution_receipt_date_is_not_null':
221 if ($value) {
222 $op = "IS NOT NULL";
223 $query->_qill[$grouping][] = ts('Contribution Receipt Sent');
224 }
225 else {
226 $op = "IS NULL";
227 $query->_qill[$grouping][] = ts('Contribution Receipt Not Sent');
228 }
229 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.receipt_date", $op);
230 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
231 return;
40c655aa 232
70c907d4
LS
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')
241 );
242 return;
243
4ca8b3e8 244 case 'financial_type_id':
b5a37491 245 case 'invoice_id':
9cad3ff4 246 case 'invoice_number':
8fb22579
PN
247 case 'payment_instrument_id':
248 case 'contribution_payment_instrument_id':
3c151c70 249 case 'contribution_page_id':
7051f2e5 250 case 'contribution_status_id':
3c151c70 251 case 'contribution_id':
252 case 'contribution_currency_type':
253 case 'contribution_currency':
254 case 'contribution_source':
3c151c70 255 case 'contribution_trxn_id':
3a6eb174 256 case 'contribution_check_number':
994567a3 257 case 'contribution_contact_id':
3c151c70 258 case (strpos($name, '_amount') !== FALSE):
77b647b6 259 case (strpos($name, '_date') !== FALSE && $name != 'contribution_fulfilled_date'):
6f56dc34 260 case 'contribution_campaign_id':
3123273f 261
be2fb01f 262 $fieldNamesNotToStripContributionFrom = [
93548514 263 'contribution_currency_type',
264 'contribution_status_id',
265 'contribution_page_id',
be2fb01f 266 ];
93548514 267 // @todo these are mostly legacy params. Find a better way to deal with them.
268 if (!in_array($name, $fieldNamesNotToStripContributionFrom)
3c151c70 269 ) {
3123273f 270 if (!isset($fields[$name])) {
3c151c70 271 $qillName = str_replace('contribution_', '', $qillName);
dbc6f6d6 272 }
3123273f 273 $name = str_replace('contribution_', '', $name);
5bbd985a 274 }
be2fb01f 275 if (in_array($name, ['contribution_currency', 'contribution_currency_type'])) {
3c151c70 276 $qillName = $name = 'currency';
be2fb01f 277 $pseudoExtraParam = ['labelColumn' => 'name'];
3c151c70 278 }
5bbd985a 279
3c151c70 280 $dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
281
282 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.$name", $op, $value, $dataType);
9ab34172 283 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_Contribution', $name, $value, $op, $pseudoExtraParam);
6822e118 284 if (!($name == 'id' && $value == 0)) {
be2fb01f 285 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
6822e118 286 }
6a488035
TO
287 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
288 return;
289
6a488035 290 case 'contribution_pcp_made_through_id':
3c151c70 291 case 'contribution_soft_credit_type_id':
292 $qillName = $name;
293 if ($name == 'contribution_pcp_made_through_id') {
294 $qillName = $name = 'pcp_id';
be2fb01f 295 $fields[$name] = ['title' => ts('Personal Campaign Page'), 'type' => 2];
3c151c70 296 }
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);
301 }
302 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_soft.$name",
303 $op, $value, CRM_Utils_Type::typeToString($fields[$qillName]['type'])
304 );
9ab34172 305 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_ContributionSoft', $name, $value, $op);
be2fb01f 306 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
6a488035
TO
307 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
308 return;
309
36bf52ef
DS
310 case 'contribution_or_softcredits':
311 if ($value == 'only_scredits') {
3dbf477c 312 $query->_where[$grouping][] = "contribution_search_scredit_combined.scredit_id IS NOT NULL";
36bf52ef 313 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits Only');
ed81a415 314 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
36bf52ef 315 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
0db6c3e1 316 }
4c9b6178 317 elseif ($value == 'both_related') {
3dbf477c 318 $query->_where[$grouping][] = "contribution_search_scredit_combined.filter_id IS NOT NULL";
4f3846df 319 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits with related Hard Credit');
ed81a415 320 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
3dbf477c 321 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
0db6c3e1 322 }
4c9b6178 323 elseif ($value == 'both') {
36bf52ef 324 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Both');
ed81a415 325 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
36bf52ef
DS
326 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
327 }
328 // default option: $value == 'only_contribs'
329 return;
330
6a488035 331 case 'contribution_is_test':
3a6eb174 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]);
335 if (!empty($key)) {
336 unset($query->_where[$grouping][$key]);
337 }
6a488035 338 case 'contribution_test':
4b58de38
CW
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");
342 if ($value) {
343 $query->_qill[$grouping][] = ts("Only Display Test Contributions");
344 }
345 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
6a488035 346 }
6a488035
TO
347 return;
348
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");
352 if ($value) {
353 $query->_qill[$grouping][] = ts("Find Pay Later Contributions");
354 }
355 else {
356 $query->_qill[$grouping][] = ts("Exclude Pay Later Contributions");
357 }
358 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
359 return;
360
361 case 'contribution_recurring':
362 if ($value) {
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;
366 }
367 else {
368 $query->_where[$grouping][] = "civicrm_contribution.contribution_recur_id IS NULL";
369 $query->_qill[$grouping][] = ts("Exclude Recurring Contributions");
370 }
371 return;
372
373 case 'contribution_recur_id':
374 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.contribution_recur_id",
375 $op, $value, "Integer"
376 );
377 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
378 return;
379
5951bdaa 380 case 'contribution_recur_payment_processor_id':
64127e03 381 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_recur.payment_processor_id", $op, $value, "String");
be2fb01f
CW
382 $paymentProcessors = civicrm_api3('PaymentProcessor', 'get', []);
383 $paymentProcessorNames = [];
64127e03
MWMC
384 foreach ($value as $paymentProcessorId) {
385 $paymentProcessorNames[] = $paymentProcessors['values'][$paymentProcessorId]['name'];
386 }
be2fb01f 387 $query->_qill[$grouping][] = ts("Recurring Contribution Payment Processor %1 %2", [1 => $op, 2 => implode(', ', $paymentProcessorNames)]);
64127e03
MWMC
388 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
389 return;
390
391 case 'contribution_recur_processor_id':
95974e8e 392 case 'contribution_recur_trxn_id':
23faf53d 393 $spec = $fields[$name];
394 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($spec['where'],
95974e8e
DG
395 $op, $value, "String"
396 );
23faf53d 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;
95974e8e
DG
399 return;
400
401 case 'contribution_recur_payment_made':
402 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_recur.id", 'IS NOT EMPTY');
5aae2a90 403 if ($value == 2) {
95974e8e
DG
404 $query->_qill[$grouping][] = ts("Recurring contributions with at least one payment");
405 self::$_contribRecurPayment = TRUE;
406 }
407 else {
408 $query->_qill[$grouping][] = ts("All recurring contributions regardless of payments");
409 self::$_contribRecurPayment = FALSE;
410 }
411 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
5af1389d
VH
412 return;
413
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);
be2fb01f 417 $query->_qill[$grouping][] = ts("Recurring Contribution Status %1 '%2'", [1 => $op, 2 => $value]);
5af1389d 418 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
95974e8e
DG
419 return;
420
6a488035 421 case 'contribution_note':
d817ca8d 422 $value = CRM_Core_DAO::escapeString($value);
6a488035
TO
423 if ($wildcard) {
424 $value = "%$value%";
425 $op = 'LIKE';
426 }
d817ca8d 427 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_note.note', $op, $value, "String");
be2fb01f 428 $query->_qill[$grouping][] = ts('Contribution Note %1 %2', [1 => $op, 2 => $quoteValue]);
6a488035
TO
429 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = $query->_whereTables['contribution_note'] = 1;
430 return;
431
432 case 'contribution_membership_id':
433 $query->_where[$grouping][] = " civicrm_membership.id $op $value";
434 $query->_tables['contribution_membership'] = $query->_whereTables['contribution_membership'] = 1;
435
436 return;
437
438 case 'contribution_participant_id':
439 $query->_where[$grouping][] = " civicrm_participant.id $op $value";
440 $query->_tables['contribution_participant'] = $query->_whereTables['contribution_participant'] = 1;
441 return;
442
443 case 'contribution_pcp_display_in_roll':
444 $query->_where[$grouping][] = " civicrm_contribution_soft.pcp_display_in_roll $op '$value'";
445 if ($value) {
446 $query->_qill[$grouping][] = ts("Personal Campaign Page Honor Roll");
447 }
448 else {
449 $query->_qill[$grouping][] = ts("NOT Personal Campaign Page Honor Roll");
450 }
451 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
452 return;
453
6a488035 454 case 'contribution_batch_id':
3086e282 455 list($qillOp, $qillValue) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Batch_BAO_EntityBatch', 'batch_id', $value, $op);
be2fb01f 456 $query->_qill[$grouping][] = ts('Batch Name %1 %2', [1 => $qillOp, 2 => $qillValue]);
3086e282 457 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_entity_batch.batch_id', $op, $value);
39b795ba 458 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
898bfdcd 459 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
6a488035
TO
460 $query->_tables['contribution_batch'] = $query->_whereTables['contribution_batch'] = 1;
461 return;
462
6ffab5b7
WA
463 case 'contribution_product_id':
464 // CRM-16713 - contribution search by premiums on 'Find Contribution' form.
465 $qillName = $name;
466 list($operator, $productValue) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_Product', $name, $value, $op);
be2fb01f 467 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $operator, 3 => $productValue]);
6ffab5b7
WA
468 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_product.id", $op, $value);
469 $query->_tables['civicrm_product'] = $query->_whereTables['civicrm_product'] = 1;
470 return;
471
d42c359d
PN
472 case 'contribution_is_payment':
473 $query->_where[$grouping][] = " civicrm_financial_trxn.is_payment $op $value";
898bfdcd
PN
474 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
475 return;
476
d72b084a 477 case 'financial_trxn_card_type_id':
478 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_financial_trxn.card_type_id', $op, $value);
898bfdcd
PN
479 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
480 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
d72b084a 481 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Financial_DAO_FinancialTrxn', 'card_type_id', $value, $op);
be2fb01f 482 $query->_qill[$grouping][] = ts('Card Type %1 %2', [1 => $op, 2 => $value]);
d42c359d
PN
483 return;
484
c6ba3619
E
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);
be2fb01f 490 $query->_qill[$grouping][] = ts('Card Number %1 %2', [1 => $op, 2 => $value]);
c6ba3619
E
491 return;
492
6a488035
TO
493 default:
494 //all other elements are handle in this case
353ffa53 495 $fldName = substr($name, 13);
ec8c4582
DL
496 if (!isset($fields[$fldName])) {
497 // CRM-12597
498 CRM_Core_Session::setStatus(ts(
fb5b081b 499 'We did not recognize the search field: %1. Please check and fix your contribution related smart groups.',
be2fb01f 500 [1 => $fldName]
ec8c4582
DL
501 )
502 );
503 return;
504 }
6a488035 505 $whereTable = $fields[$fldName];
927898c5 506 if (!is_array($value)) {
507 $value = trim($value);
508 }
6a488035 509
3c151c70 510 $dataType = "String";
511 if (!empty($whereTable['type'])) {
512 $dataType = CRM_Utils_Type::typeToString($whereTable['type']);
6a488035
TO
513 }
514
2b3e31ac 515 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($whereTable['where'], $op, $value, $dataType);
6a488035 516 $query->_qill[$grouping][] = "$whereTable[title] $op $quoteValue";
2b3e31ac 517 list($tableName) = explode('.', $whereTable['where'], 2);
6a488035
TO
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;
522 }
523 else {
524 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
525 }
526 }
527 }
528
186c9c17 529 /**
35e6241a
EM
530 * Get from clause.
531 *
100fef9d 532 * @param string $name
35e6241a
EM
533 * @param string $mode
534 * @param string $side
186c9c17 535 *
e60f24eb 536 * @return NULL|string
186c9c17 537 */
00be9182 538 public static function from($name, $mode, $side) {
6a488035
TO
539 $from = NULL;
540 switch ($name) {
353ffa53
TO
541 case 'civicrm_contribution':
542 $from = " $side JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id ";
be2fb01f 543 if (in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
353ffa53
TO
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";
548 }
549 break;
6a488035
TO
550
551 case 'civicrm_contribution_recur':
86845f9b 552 if ($mode == 1) {
95974e8e 553 // 'Made payment for the recurring contributions?' is ticked yes
1415b394 554 $from = " $side JOIN civicrm_contribution_recur ON contact_a.id = civicrm_contribution_recur.contact_id ";
24782d26 555 if (self::$_contribRecurPayment == TRUE) {
5aae2a90 556 $from .= " INNER JOIN civicrm_contribution cr ON cr.contribution_recur_id = civicrm_contribution_recur.id ";
95974e8e 557 }
86845f9b 558 }
559 else {
560 $from = " $side JOIN civicrm_contribution_recur ON civicrm_contribution.contribution_recur_id = civicrm_contribution_recur.id ";
561 }
6a488035
TO
562 break;
563
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 ";
567 }
568 else {
569 $from = " $side JOIN civicrm_financial_type ON civicrm_contribution.financial_type_id = civicrm_financial_type.id ";
570 }
571 break;
572
6ef17211 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 ";
576 }
577 break;
578
6a488035 579 case 'civicrm_accounting_code':
6ef17211 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' ";
585 }
39b795ba 586 break;
6a488035
TO
587
588 case 'civicrm_contribution_page':
3c151c70 589 $from = " $side JOIN civicrm_contribution_page ON civicrm_contribution.contribution_page_id = civicrm_contribution_page.id";
6a488035
TO
590 break;
591
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 ";
595 break;
596
36bf52ef 597 case 'contribution_softcredit_type':
353ffa53 598 $from = " $side JOIN civicrm_option_group option_group_contribution_softcredit_type ON
36bf52ef 599 (option_group_contribution_softcredit_type.name = 'soft_credit_type')";
77b97be7 600 $from .= " $side JOIN civicrm_option_value contribution_softcredit_type ON
36bf52ef
DS
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 )";
603 break;
604
6a488035
TO
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 )";
608 break;
609
6a488035
TO
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 ";
613 break;
614
9ebd3386 615 case 'civicrm_campaign':
38310a51 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";
619 }
9ebd3386 620 break;
621
6a488035
TO
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 ";
625 break;
626
627 case 'civicrm_contribution_soft':
be2fb01f 628 if (!in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
3dbf477c
DS
629 $from = " $side JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id";
630 }
6a488035
TO
631 break;
632
633 case 'civicrm_contribution_soft_contact':
be2fb01f 634 if (in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
77b97be7 635 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution.contact_id = civicrm_contact_d.id )
3dbf477c 636 AND contribution_search_scredit_combined.scredit_id IS NOT NULL";
0db6c3e1
TO
637 }
638 else {
3dbf477c
DS
639 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution_soft.contact_id = civicrm_contact_d.id )";
640 }
6a488035
TO
641 break;
642
643 case 'civicrm_contribution_soft_email':
644 $from .= " $side JOIN civicrm_email as soft_email ON (civicrm_contact_d.id = soft_email.contact_id )";
645 break;
646
647 case 'civicrm_contribution_soft_phone':
648 $from .= " $side JOIN civicrm_phone as soft_phone ON (civicrm_contact_d.id = soft_phone.contact_id )";
649 break;
39b795ba 650
6a488035 651 case 'contribution_batch':
61412579 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 )";
654
6a488035
TO
655 $from .= " $side JOIN civicrm_batch ON civicrm_entity_batch.batch_id = civicrm_batch.id";
656 break;
898bfdcd
PN
657
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 )";
662
663 $from .= " $side JOIN civicrm_financial_trxn ON (
664 civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id )";
665 break;
6a488035
TO
666 }
667 return $from;
668 }
669
186c9c17 670 /**
35e6241a
EM
671 * Initialise the soft credit clause.
672 *
673 * @param CRM_Contact_BAO_Query $query
186c9c17 674 */
00be9182 675 public static function initializeAnySoftCreditClause(&$query) {
5928ea72 676 // @todo have a generic initialize on all components that gets called every query
677 // & rename this to match that fn name.
9ae25b56 678 if ($query->_mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
679 if (self::isSoftCreditOptionEnabled($query->_params)) {
ed81a415 680 unset($query->_distinctComponentClause);
f654cacf 681 $query->_rowCountClause = " count(civicrm_contribution.id)";
ed81a415 682 $query->_groupByComponentClause = " GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.contact_id, contribution_search_scredit_combined.scredit_id ";
36bf52ef 683 }
9ae25b56 684 else {
685 $query->_distinctComponentClause = ' civicrm_contribution.id';
686 }
f654cacf
DS
687 }
688 }
689
186c9c17 690 /**
35e6241a
EM
691 * Check if soft credits are enables.
692 *
186c9c17
EM
693 * @param array $queryParams
694 *
695 * @return bool
696 */
be2fb01f 697 public static function isSoftCreditOptionEnabled($queryParams = []) {
f654cacf
DS
698 static $tempTableFilled = FALSE;
699 if (!empty($queryParams)) {
700 foreach (array_keys($queryParams) as $id) {
701 if (empty($queryParams[$id][0])) {
702 continue;
703 }
38e1cb31
DS
704 if ($queryParams[$id][0] == 'contribution_or_softcredits') {
705 self::$_contribOrSoftCredit = $queryParams[$id][2];
706 }
f654cacf
DS
707 }
708 }
77b97be7 709 if (in_array(self::$_contribOrSoftCredit,
be2fb01f 710 ["only_scredits", "both_related", "both"])) {
353ffa53
TO
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
714 $tempQuery = "
77b97be7
EM
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
3dbf477c 717 FROM civicrm_contribution con
4f3846df 718 LEFT JOIN civicrm_contribution_soft cso ON con.id = cso.contribution_id
e5cceea5 719 GROUP BY id, contact_id, scredit_id, cso.id
3dbf477c 720 UNION ALL
77b97be7 721 SELECT scredit.contribution_id as id, scredit.contact_id, scredit.id as filter_id, scredit.id as scredit_id
3dbf477c 722 FROM civicrm_contribution_soft as scredit";
353ffa53
TO
723 CRM_Core_DAO::executeQuery($tempQuery);
724 $tempTableFilled = TRUE;
f654cacf 725 }
353ffa53
TO
726 return TRUE;
727 }
36bf52ef
DS
728 return FALSE;
729 }
730
186c9c17 731 /**
35e6241a
EM
732 * Get return properties for soft credits.
733 *
186c9c17
EM
734 * @param bool $isExportMode
735 *
736 * @return array
737 */
353ffa53 738 public static function softCreditReturnProperties($isExportMode = FALSE) {
be2fb01f 739 $properties = [
353ffa53 740 'contribution_soft_credit_name' => 1,
4f3846df 741 'contribution_soft_credit_amount' => 1,
353ffa53 742 'contribution_soft_credit_type' => 1,
be2fb01f 743 ];
4f3846df 744 if ($isExportMode) {
5850d2e9 745 $properties['contribution_soft_credit_contact_id'] = 1;
4f3846df
DS
746 $properties['contribution_soft_credit_contribution_id'] = 1;
747 }
748 return $properties;
749 }
750
186c9c17 751 /**
c7940124 752 * Get the list of fields required to populate the selector.
753 *
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.
b4bb60fc
OH
756 *
757 * @param array $queryParams
758 * @return array
c7940124 759 */
b4bb60fc 760 public static function selectorReturnProperties($queryParams) {
be2fb01f 761 $properties = [
c7940124 762 'contact_type' => 1,
763 'contact_sub_type' => 1,
764 'sort_name' => 1,
765 'financial_type' => 1,
766 'contribution_source' => 1,
767 'is_test' => 1,
768 'receive_date' => 1,
769 'is_pay_later' => 1,
770 'thankyou_date' => 1,
771 'total_amount' => 1,
5deb2f24 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,
c7940124 774 'contribution_status_id' => 1,
775 // @todo return this & fix query to do pseudoconstant thing.
776 'contribution_status' => 1,
9a59ce91 777 'currency' => 1,
1eae0d75 778 'cancel_date' => 1,
2e80df5b 779 'contribution_recur_id' => 1,
be2fb01f 780 ];
c8dd6301 781 if (self::isSiteHasProducts()) {
782 $properties['product_name'] = 1;
783 $properties['contribution_product_id'] = 1;
784 }
b4bb60fc 785 if (self::isSoftCreditOptionEnabled($queryParams)) {
8f7c2652 786 $properties = array_merge($properties, self::softCreditReturnProperties());
787 }
788
789 return $properties;
c7940124 790 }
791
c8dd6301 792 /**
793 * Do any products exist in this site's database.
794 *
795 * @return bool
796 */
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');
800 }
801 return \Civi::$statics[__CLASS__]['has_products'];
802 }
803
c7940124 804 /**
805 * Function you should avoid.
806 *
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.
810 *
811 * It would be nice to throw an e-notice when this is called but it would trash the tests :-(.
812 *
813 * @param int $mode
186c9c17
EM
814 * @param bool $includeCustomFields
815 *
e60f24eb 816 * @return array|NULL
186c9c17 817 */
00be9182 818 public static function defaultReturnProperties($mode, $includeCustomFields = TRUE) {
6a488035
TO
819 $properties = NULL;
820 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
be2fb01f 821 $properties = [
5928ea72 822 // add
6a488035 823 'contact_type' => 1,
5928ea72 824 // fields
6a488035 825 'contact_sub_type' => 1,
5928ea72 826 // to
6a488035 827 'sort_name' => 1,
5928ea72 828 //this
6a488035 829 'display_name' => 1,
5928ea72 830 // array
6a488035 831 'financial_type' => 1,
5928ea72 832 // to
6a488035 833 'contribution_source' => 1,
5928ea72 834 // strangle
6a488035 835 'receive_date' => 1,
5928ea72 836 // site
6a488035 837 'thankyou_date' => 1,
5928ea72 838 // performance
6e7cc0f5 839 'contribution_cancel_date' => 1,
5928ea72 840 // and
6a488035 841 'total_amount' => 1,
5928ea72 842 // torture
6a488035 843 'accounting_code' => 1,
5928ea72 844 // small
afa0b07c 845 'payment_instrument' => 1,
5928ea72 846 // kittens
3a6eb174 847 'payment_instrument_id' => 1,
5928ea72 848 // argh
7bc1d4da 849 'contribution_check_number' => 1,
5928ea72 850 // no
6a488035 851 'non_deductible_amount' => 1,
5928ea72 852 // not
6a488035 853 'fee_amount' => 1,
5928ea72 854 // another
6a488035 855 'net_amount' => 1,
5928ea72 856 // expensive
6a488035 857 'trxn_id' => 1,
5928ea72 858 // join
6a488035 859 'invoice_id' => 1,
802c1c41 860 'invoice_number' => 1,
5928ea72 861 // added
6a488035 862 'currency' => 1,
5928ea72 863 // to
6a488035 864 'cancel_reason' => 1,
5928ea72 865 //every
6a488035 866 'receipt_date' => 1,
5928ea72 867 // query
5928ea72 868 //whether
5928ea72 869 // or
5928ea72 870 // not
5928ea72 871 // the
5928ea72 872 // field
5928ea72 873 // is
6a488035 874 'is_test' => 1,
5928ea72 875 // actually
6a488035 876 'is_pay_later' => 1,
5928ea72 877 // required
6a488035 878 'contribution_status' => 1,
5928ea72 879 // instead
6a488035 880 'contribution_status_id' => 1,
5928ea72 881 // of
6a488035 882 'contribution_recur_id' => 1,
5928ea72 883 // adding
6a488035 884 'amount_level' => 1,
5928ea72 885 // here
6a488035 886 'contribution_note' => 1,
5928ea72 887 // set
6a488035 888 'contribution_batch' => 1,
5928ea72 889 // return properties
9ebd3386 890 'contribution_campaign_title' => 1,
5928ea72 891 // on
36bf52ef 892 'contribution_campaign_id' => 1,
5928ea72 893 // calling
5928ea72 894 //function
be2fb01f 895 ];
c8dd6301 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;
904 }
d4e2b978 905 if (self::isSoftCreditOptionEnabled()) {
4f3846df 906 $properties = array_merge($properties, self::softCreditReturnProperties());
36bf52ef 907 }
6a488035
TO
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;
914 }
915 }
916 }
917 }
918 return $properties;
919 }
920
7123f88c 921 /**
922 * Get the metadata for fields to be included on the search form.
923 *
924 * @throws \CiviCRM_API3_Exception
925 */
926 public static function getSearchFieldMetadata() {
927 $fields = [
928 'contribution_source',
929 'cancel_reason',
930 'invoice_number',
6e7cc0f5
SL
931 'receive_date',
932 'contribution_cancel_date',
7123f88c 933 ];
934 $metadata = civicrm_api3('Contribution', 'getfields', [])['values'];
935 return array_intersect_key($metadata, array_flip($fields));
936 }
937
6a488035 938 /**
fe482240 939 * Add all the elements shared between contribute search and advnaced search.
6a488035 940 *
7123f88c 941 * @param \CRM_Contribute_Form_Search $form
942 *
943 * @throws \CRM_Core_Exception
944 * @throws \CiviCRM_API3_Exception
6a488035 945 */
00be9182 946 public static function buildSearchForm(&$form) {
6a488035 947
7123f88c 948 $form->addSearchFieldMetadata(['Contribution' => self::getSearchFieldMetadata()]);
949 $form->addFormFieldsFromMetadata();
6a488035 950
be2fb01f
CW
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');
6a488035 953
be2fb01f
CW
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');
6a488035
TO
956
957 // Adding select option for curreny type -- CRM-4711
958 $form->add('select', 'contribution_currency_type',
959 ts('Currency Type'),
be2fb01f 960 [
7c550ca0 961 '' => ts('- any -'),
be2fb01f
CW
962 ] +
963 CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', ['labelColumn' => 'name']),
964 FALSE, ['class' => 'crm-select2']
6a488035
TO
965 );
966
1f0d8c92 967 // CRM-13848
573fd305 968 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::VIEW);
15cf9198 969 $form->addSelect('financial_type_id',
be2fb01f 970 ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => $financialTypes]
6a488035
TO
971 );
972
973 $form->add('select', 'contribution_page_id',
974 ts('Contribution Page'),
ab345ca5 975 CRM_Contribute_PseudoConstant::contributionPage(),
be2fb01f 976 FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]
6a488035
TO
977 );
978
6e219d15
SP
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',
be2fb01f 983 ['entity' => 'contribution', 'field' => 'payment_instrument_id', 'multiple' => 'multiple', 'label' => ts('Payment Method'), 'option_url' => NULL, 'placeholder' => ts('- any -')]
6a488035
TO
984 );
985
1517c3e8 986 $form->add('select',
987 'contribution_pcp_made_through_id',
988 ts('Personal Campaign Page'),
be2fb01f 989 CRM_Contribute_PseudoConstant::pcPage(), FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]);
6a488035 990
2b65bb8c 991 $statusValues = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id');
2b65bb8c 992 $form->add('select', 'contribution_status_id',
993 ts('Contribution Status'), $statusValues,
be2fb01f 994 FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']
3c151c70 995 );
6a488035
TO
996
997 // Add fields for thank you and receipt
8a4f27dc
CW
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);
6a488035 1000
8a4f27dc
CW
1001 $form->addYesNo('contribution_pay_later', ts('Contribution is Pay Later?'), TRUE);
1002 $form->addYesNo('contribution_recurring', ts('Contribution is Recurring?'), TRUE);
b32bc653 1003
8a4f27dc 1004 $form->addYesNo('contribution_test', ts('Contribution is a Test?'), TRUE);
6a488035
TO
1005
1006 // Add field for transaction ID search
3c151c70 1007 $form->addElement('text', 'contribution_trxn_id', ts("Transaction ID"));
6a488035
TO
1008 $form->addElement('text', 'contribution_check_number', ts('Check Number'));
1009
1010 // Add field for pcp display in roll search
8a4f27dc 1011 $form->addYesNo('contribution_pcp_display_in_roll', ts('Personal Campaign Page Honor Roll?'), TRUE);
6a488035 1012
36bf52ef 1013 // Soft credit related fields
be2fb01f 1014 $options = [
3dbf477c 1015 'only_contribs' => ts('Contributions Only'),
e0b774f0 1016 'only_scredits' => ts('Soft Credits Only'),
353ffa53
TO
1017 'both_related' => ts('Soft Credits with related Hard Credit'),
1018 'both' => ts('Both'),
be2fb01f
CW
1019 ];
1020 $form->add('select', 'contribution_or_softcredits', ts('Contributions OR Soft Credits?'), $options, FALSE, ['class' => "crm-select2"]);
e88186f4 1021 $form->addSelect(
77b97be7 1022 'contribution_soft_credit_type_id',
be2fb01f 1023 [
353ffa53
TO
1024 'entity' => 'contribution_soft',
1025 'field' => 'soft_credit_type_id',
1026 'multiple' => TRUE,
1027 'context' => 'search',
be2fb01f 1028 ]
e88186f4 1029 );
36bf52ef 1030
be2fb01f 1031 $form->addField('financial_trxn_card_type_id', ['entity' => 'FinancialTrxn', 'name' => 'card_type_id', 'action' => 'get']);
898bfdcd 1032
be2fb01f 1033 $form->add('text', 'financial_trxn_pan_truncation', ts('Card Number'), [
c6ba3619
E
1034 'size' => 5,
1035 'maxlength' => 4,
1036 'autocomplete' => 'off',
be2fb01f 1037 ]);
c6ba3619 1038
c8dd6301 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',
1042 ts('Premium'),
1043 CRM_Contribute_PseudoConstant::products(),
1044 FALSE, [
1045 'class' => 'crm-select2',
1046 'multiple' => 'multiple',
1330f57a 1047 'placeholder' => ts('- any -'),
c8dd6301 1048 ]
1049 );
1050 }
6ffab5b7 1051
be2fb01f 1052 self::addCustomFormFields($form, ['Contribution']);
6a488035
TO
1053
1054 CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'contribution_campaign_id');
1055
1056 // Add batch select
91aff94c 1057 $batches = CRM_Contribute_PseudoConstant::batch();
39b795ba 1058
481a74f4 1059 if (!empty($batches)) {
6a488035
TO
1060 $form->add('select', 'contribution_batch_id',
1061 ts('Batch Name'),
be2fb01f 1062 [
dc7b39df
JV
1063 '' => ts('- any -'),
1064 // CRM-19325
3086e282 1065 'IS NULL' => ts('None'),
be2fb01f
CW
1066 ] + $batches,
1067 FALSE, ['class' => 'crm-select2']
ab345ca5 1068 );
6a488035
TO
1069 }
1070
1071 $form->assign('validCiviContribute', TRUE);
be2fb01f 1072 $form->setDefaults(['contribution_test' => 0]);
24782d26 1073
1074 CRM_Contribute_BAO_ContributionRecur::recurringContribution($form);
6a488035
TO
1075 }
1076
186c9c17 1077 /**
35e6241a
EM
1078 * Get table names.
1079 *
1080 * @todo better function comment needed - what IS the point of this?
1081 *
1082 * @param array $tables
186c9c17 1083 */
00be9182 1084 public static function tableNames(&$tables) {
6a488035 1085 // Add contribution table
a7488080 1086 if (!empty($tables['civicrm_product'])) {
be2fb01f 1087 $tables = array_merge(['civicrm_contribution' => 1], $tables);
6a488035
TO
1088 }
1089
8cc574cf 1090 if (!empty($tables['civicrm_contribution_product']) && empty($tables['civicrm_product'])) {
6a488035
TO
1091 $tables['civicrm_product'] = 1;
1092 }
1093 }
a91e698a 1094
1095 /**
fe482240 1096 * Add the where for dates.
77b97be7 1097 *
014c4014
TO
1098 * @param array $values
1099 * Array of query values.
1100 * @param object $query
1101 * The query object.
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.
77b97be7
EM
1108 *
1109 * @return bool
a91e698a 1110 */
00be9182 1111 public static function buildDateWhere(&$values, $query, $name, $field, $title) {
a91e698a 1112 $fieldPart = strpos($name, $field);
22e263ad 1113 if ($fieldPart === FALSE) {
7c550ca0 1114 return NULL;
a91e698a 1115 }
1116 // we only have recurring dates using this ATM so lets' short cut to find the table name
1117 $table = 'contribution_recur';
d3e86119 1118 $fieldName = explode($table . '_', $field);
a91e698a 1119 $query->dateQueryBuilder($values,
1120 'civicrm_' . $table, $field, $fieldName[1], $title
1121 );
1122 return TRUE;
1123 }
b32bc653 1124
686df921 1125 /**
1126 * Add the soft credit fields to the select fields.
1127 *
1128 * Extracted into separate function to improve readability of main select function.
1129 *
1130 * @param $query
1131 */
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";
1139 }
1140 $query->_element['contribution_soft_credit_name'] = 1;
1141 $query->_element['contribution_soft_credit_contact_id'] = 1;
1142
1143 $query->_tables['civicrm_contribution'] = 1;
1144 $query->_tables['civicrm_contribution_soft'] = 1;
1145 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1146 }
1147
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;
1152 }
1153
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";
1157 }
1158 $query->_element['contribution_soft_credit_amount'] = 1;
1159 $query->_tables['civicrm_contribution'] = 1;
1160 $query->_tables['civicrm_contribution_soft'] = 1;
1161 }
1162
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";
1166 }
1167 $query->_element['contribution_soft_credit_type'] = 1;
1168 $query->_tables['civicrm_contribution'] = 1;
1169 $query->_tables['contribution_softcredit_type'] = 1;
1170 }
1171
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";
1175 }
1176 $query->_element['contribution_soft_credit_contribution_id'] = 1;
1177 $query->_tables['civicrm_contribution'] = 1;
1178 $query->_tables['civicrm_contribution_soft'] = 1;
1179 }
1180
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;
1188 }
1189
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;
1197 }
1198
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;
1204 }
1205 }
1206
6a488035 1207}