Move inclusion of frontEndPaymentTrait to shared Parent class
[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'])) {
4edbe907 51 $recurFields = CRM_Contribute_DAO_ContributionRecur::fields();
52 foreach ($recurFields as $fieldKey => $field) {
53 // We can only safely add in those with unique names as those without could clobber others.
54 // The array is keyed by unique names so if it doesn't match the key there is no unique name & we unset
55 // Refer to CRM_Contribute_Form_SearchTest for existing tests ... and to add more!
56 if ($field['name'] === $fieldKey) {
57 unset($recurFields[$fieldKey]);
58 }
59 }
23faf53d 60 $fields = array_merge($recurFields, CRM_Contribute_BAO_Contribution::exportableFields($checkPermission));
a0090e6b 61 CRM_Contribute_BAO_Contribution::appendPseudoConstantsToFields($fields);
6a488035 62 unset($fields['contribution_contact_id']);
33a766c6 63 \Civi::$statics[__CLASS__]['fields']['contribution'] = $fields;
6a488035 64 }
33a766c6 65 return \Civi::$statics[__CLASS__]['fields']['contribution'];
6a488035
TO
66 }
67
68 /**
7fe37828 69 * If contributions are involved, add the specific contribute fields.
6a488035 70 *
35e6241a 71 * @param CRM_Contact_BAO_Query $query
6a488035 72 */
00be9182 73 public static function select(&$query) {
6a488035
TO
74 // if contribute mode add contribution id
75 if ($query->_mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
76 $query->_select['contribution_id'] = "civicrm_contribution.id as contribution_id";
77 $query->_element['contribution_id'] = 1;
78 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
79 }
80
6a488035 81 // get accounting code
a7488080 82 if (!empty($query->_returnProperties['accounting_code'])) {
353ffa53 83 $query->_select['accounting_code'] = "civicrm_financial_account.accounting_code as accounting_code";
6a488035
TO
84 $query->_element['accounting_code'] = 1;
85 $query->_tables['civicrm_accounting_code'] = 1;
86 $query->_tables['civicrm_financial_account'] = 1;
87 }
39b795ba 88
a7488080 89 if (!empty($query->_returnProperties['contribution_note'])) {
6a488035
TO
90 $query->_select['contribution_note'] = "civicrm_note.note as contribution_note";
91 $query->_element['contribution_note'] = 1;
92 $query->_tables['contribution_note'] = 1;
739189e4 93 $query->_tables['civicrm_contribution'] = 1;
6a488035
TO
94 }
95
a7488080 96 if (!empty($query->_returnProperties['contribution_batch'])) {
6a488035
TO
97 $query->_select['contribution_batch'] = "civicrm_batch.title as contribution_batch";
98 $query->_element['contribution_batch'] = 1;
898bfdcd 99 $query->_tables['civicrm_financial_trxn'] = 1;
6a488035
TO
100 $query->_tables['contribution_batch'] = 1;
101 }
102
9ebd3386 103 if (!empty($query->_returnProperties['contribution_campaign_title'])) {
104 $query->_select['contribution_campaign_title'] = "civicrm_campaign.title as contribution_campaign_title";
105 $query->_element['contribution_campaign_title'] = $query->_tables['civicrm_campaign'] = 1;
106 }
739a8336 107
686df921 108 self::addSoftCreditFields($query);
6a488035
TO
109 }
110
186c9c17 111 /**
35e6241a
EM
112 * Get where clause.
113 *
114 * @param CRM_Contact_BAO_Query $query
186c9c17 115 */
00be9182 116 public static function where(&$query) {
f654cacf 117 self::initializeAnySoftCreditClause($query);
6a488035 118 foreach (array_keys($query->_params) as $id) {
a7488080 119 if (empty($query->_params[$id][0])) {
6a488035
TO
120 continue;
121 }
afa0b07c 122 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_') {
2da8c6c4 123 if ($query->_mode == CRM_Contact_BAO_Query::MODE_CONTACTS) {
6a488035
TO
124 $query->_useDistinct = TRUE;
125 }
39b795ba
DL
126 // CRM-12065
127 if (
128 $query->_params[$id][0] == 'contribution_type_id' ||
129 $query->_params[$id][0] == 'contribution_type'
130 ) {
131 CRM_Core_Session::setStatus(
132 ts('The contribution type criteria is now obsolete, please update your smart group'),
133 '',
134 'alert'
135 );
136 continue;
137 }
138
6a488035
TO
139 self::whereClauseSingle($query->_params[$id], $query);
140 }
141 }
6a488035
TO
142 }
143
186c9c17 144 /**
35e6241a
EM
145 * Get where clause for a single value.
146 *
147 * @param array $values
148 * @param CRM_Contact_BAO_Query $query
7123f88c 149 *
150 * @throws \CiviCRM_API3_Exception
151 * @throws \CRM_Core_Exception
186c9c17 152 */
00be9182 153 public static function whereClauseSingle(&$values, &$query) {
6a488035
TO
154 list($name, $op, $value, $grouping, $wildcard) = $values;
155
dbc6f6d6 156 $quoteValue = NULL;
9d5c7f14 157 $fields = self::getFields();
163b1da9
KJ
158
159 if (!empty($value) && !is_array($value)) {
6a488035
TO
160 $quoteValue = "\"$value\"";
161 }
162
e1bbe1bf 163 $fieldAliases = self::getLegacySupportedFields();
164
165 $fieldName = $name = self::getFieldName($values);
3123273f 166 $qillName = $name;
4fc150ab 167 if (in_array($name, $fieldAliases)) {
168 $qillName = array_search($name, $fieldAliases);
169 }
be2fb01f 170 $pseudoExtraParam = [];
4edbe907 171 $fieldSpec = CRM_Utils_Array::value($fieldName, $fields, []);
172 $tableName = CRM_Utils_Array::value('table_name', $fieldSpec, 'civicrm_contribution');
173 $dataType = CRM_Utils_Type::typeToString(CRM_Utils_Array::value('type', $fieldSpec));
174 if ($dataType === 'Timestamp' || $dataType === 'Date') {
1157f03f 175 $title = empty($fieldSpec['unique_title']) ? $fieldSpec['title'] : $fieldSpec['unique_title'];
4edbe907 176 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
177 $query->dateQueryBuilder($values,
1157f03f 178 $tableName, $fieldName, $fieldSpec['name'], $title
4edbe907 179 );
180 return;
181 }
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
4ca8b3e8 233 case 'financial_type_id':
b5a37491 234 case 'invoice_id':
9cad3ff4 235 case 'invoice_number':
8fb22579
PN
236 case 'payment_instrument_id':
237 case 'contribution_payment_instrument_id':
3c151c70 238 case 'contribution_page_id':
7051f2e5 239 case 'contribution_status_id':
3c151c70 240 case 'contribution_id':
241 case 'contribution_currency_type':
242 case 'contribution_currency':
243 case 'contribution_source':
3c151c70 244 case 'contribution_trxn_id':
3a6eb174 245 case 'contribution_check_number':
994567a3 246 case 'contribution_contact_id':
3c151c70 247 case (strpos($name, '_amount') !== FALSE):
6f56dc34 248 case 'contribution_campaign_id':
3123273f 249
be2fb01f 250 $fieldNamesNotToStripContributionFrom = [
93548514 251 'contribution_currency_type',
252 'contribution_status_id',
253 'contribution_page_id',
be2fb01f 254 ];
93548514 255 // @todo these are mostly legacy params. Find a better way to deal with them.
256 if (!in_array($name, $fieldNamesNotToStripContributionFrom)
3c151c70 257 ) {
3123273f 258 if (!isset($fields[$name])) {
3c151c70 259 $qillName = str_replace('contribution_', '', $qillName);
dbc6f6d6 260 }
3123273f 261 $name = str_replace('contribution_', '', $name);
5bbd985a 262 }
be2fb01f 263 if (in_array($name, ['contribution_currency', 'contribution_currency_type'])) {
3c151c70 264 $qillName = $name = 'currency';
be2fb01f 265 $pseudoExtraParam = ['labelColumn' => 'name'];
3c151c70 266 }
5bbd985a 267
3c151c70 268 $dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
269
270 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.$name", $op, $value, $dataType);
9ab34172 271 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_Contribution', $name, $value, $op, $pseudoExtraParam);
6822e118 272 if (!($name == 'id' && $value == 0)) {
be2fb01f 273 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
6822e118 274 }
6a488035
TO
275 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
276 return;
277
6a488035 278 case 'contribution_pcp_made_through_id':
3c151c70 279 case 'contribution_soft_credit_type_id':
280 $qillName = $name;
281 if ($name == 'contribution_pcp_made_through_id') {
282 $qillName = $name = 'pcp_id';
be2fb01f 283 $fields[$name] = ['title' => ts('Personal Campaign Page'), 'type' => 2];
3c151c70 284 }
285 if ($name == 'contribution_soft_credit_type_id') {
286 $qillName = str_replace('_id', '', $qillName);
287 $fields[$qillName]['type'] = $fields[$qillName]['data_type'];
288 $name = str_replace('contribution_', '', $name);
289 }
290 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_soft.$name",
291 $op, $value, CRM_Utils_Type::typeToString($fields[$qillName]['type'])
292 );
9ab34172 293 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_ContributionSoft', $name, $value, $op);
be2fb01f 294 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
6a488035
TO
295 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
296 return;
297
36bf52ef
DS
298 case 'contribution_or_softcredits':
299 if ($value == 'only_scredits') {
3dbf477c 300 $query->_where[$grouping][] = "contribution_search_scredit_combined.scredit_id IS NOT NULL";
36bf52ef 301 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits Only');
ed81a415 302 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
36bf52ef 303 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
0db6c3e1 304 }
4c9b6178 305 elseif ($value == 'both_related') {
3dbf477c 306 $query->_where[$grouping][] = "contribution_search_scredit_combined.filter_id IS NOT NULL";
4f3846df 307 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits with related Hard Credit');
ed81a415 308 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
3dbf477c 309 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
0db6c3e1 310 }
4c9b6178 311 elseif ($value == 'both') {
36bf52ef 312 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Both');
ed81a415 313 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
36bf52ef
DS
314 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
315 }
316 // default option: $value == 'only_contribs'
317 return;
318
6a488035 319 case 'contribution_is_test':
3a6eb174 320 // By default is Contribution Search form we choose is_test = 0 in otherwords always show active contribution
321 // so in case if any one choose any Yes/No avoid the default clause otherwise it will be conflict in whereClause
322 $key = array_search('civicrm_contribution.is_test = 0', $query->_where[$grouping]);
323 if (!empty($key)) {
324 unset($query->_where[$grouping][$key]);
325 }
6a488035 326 case 'contribution_test':
4b58de38
CW
327 // We dont want to include all tests for sql OR CRM-7827
328 if (!$value || $query->getOperator() != 'OR') {
329 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.is_test", $op, $value, "Boolean");
330 if ($value) {
331 $query->_qill[$grouping][] = ts("Only Display Test Contributions");
332 }
333 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
6a488035 334 }
6a488035
TO
335 return;
336
337 case 'contribution_is_pay_later':
338 case 'contribution_pay_later':
339 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.is_pay_later", $op, $value, "Boolean");
340 if ($value) {
341 $query->_qill[$grouping][] = ts("Find Pay Later Contributions");
342 }
343 else {
344 $query->_qill[$grouping][] = ts("Exclude Pay Later Contributions");
345 }
346 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
347 return;
348
349 case 'contribution_recurring':
350 if ($value) {
351 $query->_where[$grouping][] = "civicrm_contribution.contribution_recur_id IS NOT NULL";
352 $query->_qill[$grouping][] = ts("Find Recurring Contributions");
353 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
354 }
355 else {
356 $query->_where[$grouping][] = "civicrm_contribution.contribution_recur_id IS NULL";
357 $query->_qill[$grouping][] = ts("Exclude Recurring Contributions");
358 }
359 return;
360
361 case 'contribution_recur_id':
362 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.contribution_recur_id",
363 $op, $value, "Integer"
364 );
365 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
366 return;
367
5951bdaa 368 case 'contribution_recur_payment_processor_id':
64127e03 369 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_recur.payment_processor_id", $op, $value, "String");
be2fb01f
CW
370 $paymentProcessors = civicrm_api3('PaymentProcessor', 'get', []);
371 $paymentProcessorNames = [];
64127e03
MWMC
372 foreach ($value as $paymentProcessorId) {
373 $paymentProcessorNames[] = $paymentProcessors['values'][$paymentProcessorId]['name'];
374 }
be2fb01f 375 $query->_qill[$grouping][] = ts("Recurring Contribution Payment Processor %1 %2", [1 => $op, 2 => implode(', ', $paymentProcessorNames)]);
64127e03
MWMC
376 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
377 return;
378
379 case 'contribution_recur_processor_id':
95974e8e 380 case 'contribution_recur_trxn_id':
23faf53d 381 $spec = $fields[$name];
382 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($spec['where'],
95974e8e
DG
383 $op, $value, "String"
384 );
23faf53d 385 $query->_qill[$grouping][] = ts("Recurring Contribution %1 %2 '%3'", [1 => $fields[$name]['title'], 2 => $op, 3 => $value]);
386 $query->_tables[$spec['table_name']] = $query->_whereTables[$spec['table_name']] = 1;
95974e8e
DG
387 return;
388
389 case 'contribution_recur_payment_made':
390 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_recur.id", 'IS NOT EMPTY');
5aae2a90 391 if ($value == 2) {
95974e8e
DG
392 $query->_qill[$grouping][] = ts("Recurring contributions with at least one payment");
393 self::$_contribRecurPayment = TRUE;
394 }
395 else {
396 $query->_qill[$grouping][] = ts("All recurring contributions regardless of payments");
397 self::$_contribRecurPayment = FALSE;
398 }
399 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
5af1389d
VH
400 return;
401
402 case 'contribution_recur_contribution_status_id':
403 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_recur.contribution_status_id", $op, $value, 'String');
404 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_ContributionRecur', 'contribution_status_id', $value, $op, $pseudoExtraParam);
be2fb01f 405 $query->_qill[$grouping][] = ts("Recurring Contribution Status %1 '%2'", [1 => $op, 2 => $value]);
5af1389d 406 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
95974e8e
DG
407 return;
408
6a488035 409 case 'contribution_note':
d817ca8d 410 $value = CRM_Core_DAO::escapeString($value);
6a488035
TO
411 if ($wildcard) {
412 $value = "%$value%";
413 $op = 'LIKE';
414 }
d817ca8d 415 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_note.note', $op, $value, "String");
be2fb01f 416 $query->_qill[$grouping][] = ts('Contribution Note %1 %2', [1 => $op, 2 => $quoteValue]);
6a488035
TO
417 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = $query->_whereTables['contribution_note'] = 1;
418 return;
419
420 case 'contribution_membership_id':
421 $query->_where[$grouping][] = " civicrm_membership.id $op $value";
422 $query->_tables['contribution_membership'] = $query->_whereTables['contribution_membership'] = 1;
423
424 return;
425
426 case 'contribution_participant_id':
427 $query->_where[$grouping][] = " civicrm_participant.id $op $value";
428 $query->_tables['contribution_participant'] = $query->_whereTables['contribution_participant'] = 1;
429 return;
430
431 case 'contribution_pcp_display_in_roll':
432 $query->_where[$grouping][] = " civicrm_contribution_soft.pcp_display_in_roll $op '$value'";
433 if ($value) {
434 $query->_qill[$grouping][] = ts("Personal Campaign Page Honor Roll");
435 }
436 else {
437 $query->_qill[$grouping][] = ts("NOT Personal Campaign Page Honor Roll");
438 }
439 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
440 return;
441
6a488035 442 case 'contribution_batch_id':
3086e282 443 list($qillOp, $qillValue) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Batch_BAO_EntityBatch', 'batch_id', $value, $op);
be2fb01f 444 $query->_qill[$grouping][] = ts('Batch Name %1 %2', [1 => $qillOp, 2 => $qillValue]);
3086e282 445 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_entity_batch.batch_id', $op, $value);
39b795ba 446 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
898bfdcd 447 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
6a488035
TO
448 $query->_tables['contribution_batch'] = $query->_whereTables['contribution_batch'] = 1;
449 return;
450
6ffab5b7
WA
451 case 'contribution_product_id':
452 // CRM-16713 - contribution search by premiums on 'Find Contribution' form.
453 $qillName = $name;
454 list($operator, $productValue) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_Product', $name, $value, $op);
be2fb01f 455 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $operator, 3 => $productValue]);
6ffab5b7
WA
456 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_product.id", $op, $value);
457 $query->_tables['civicrm_product'] = $query->_whereTables['civicrm_product'] = 1;
458 return;
459
d42c359d
PN
460 case 'contribution_is_payment':
461 $query->_where[$grouping][] = " civicrm_financial_trxn.is_payment $op $value";
898bfdcd
PN
462 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
463 return;
464
d72b084a 465 case 'financial_trxn_card_type_id':
466 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_financial_trxn.card_type_id', $op, $value);
898bfdcd
PN
467 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
468 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
d72b084a 469 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Financial_DAO_FinancialTrxn', 'card_type_id', $value, $op);
be2fb01f 470 $query->_qill[$grouping][] = ts('Card Type %1 %2', [1 => $op, 2 => $value]);
d42c359d
PN
471 return;
472
c6ba3619
E
473 case 'financial_trxn_pan_truncation':
474 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_financial_trxn.pan_truncation', $op, $value);
475 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
476 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
477 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Financial_DAO_FinancialTrxn', 'pan_truncation', $value, $op);
be2fb01f 478 $query->_qill[$grouping][] = ts('Card Number %1 %2', [1 => $op, 2 => $value]);
c6ba3619
E
479 return;
480
6a488035
TO
481 default:
482 //all other elements are handle in this case
353ffa53 483 $fldName = substr($name, 13);
ec8c4582
DL
484 if (!isset($fields[$fldName])) {
485 // CRM-12597
486 CRM_Core_Session::setStatus(ts(
fb5b081b 487 'We did not recognize the search field: %1. Please check and fix your contribution related smart groups.',
be2fb01f 488 [1 => $fldName]
ec8c4582
DL
489 )
490 );
491 return;
492 }
6a488035 493 $whereTable = $fields[$fldName];
927898c5 494 if (!is_array($value)) {
495 $value = trim($value);
496 }
6a488035 497
3c151c70 498 $dataType = "String";
499 if (!empty($whereTable['type'])) {
500 $dataType = CRM_Utils_Type::typeToString($whereTable['type']);
6a488035
TO
501 }
502
2b3e31ac 503 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($whereTable['where'], $op, $value, $dataType);
6a488035 504 $query->_qill[$grouping][] = "$whereTable[title] $op $quoteValue";
2b3e31ac 505 list($tableName) = explode('.', $whereTable['where'], 2);
6a488035 506 $query->_tables[$tableName] = $query->_whereTables[$tableName] = 1;
4edbe907 507 if ($tableName === 'civicrm_contribution_product') {
6a488035
TO
508 $query->_tables['civicrm_product'] = $query->_whereTables['civicrm_product'] = 1;
509 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
510 }
511 else {
512 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
513 }
514 }
515 }
516
186c9c17 517 /**
35e6241a
EM
518 * Get from clause.
519 *
100fef9d 520 * @param string $name
35e6241a
EM
521 * @param string $mode
522 * @param string $side
186c9c17 523 *
e60f24eb 524 * @return NULL|string
186c9c17 525 */
00be9182 526 public static function from($name, $mode, $side) {
6a488035
TO
527 $from = NULL;
528 switch ($name) {
353ffa53
TO
529 case 'civicrm_contribution':
530 $from = " $side JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id ";
be2fb01f 531 if (in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
353ffa53 532 // switch the from table if its only soft credit search
bc438a52 533 $from = " $side JOIN " . \Civi::$statics[__CLASS__]['soft_credit_temp_table_name'] . " as contribution_search_scredit_combined ON contribution_search_scredit_combined.contact_id = contact_a.id ";
353ffa53
TO
534 $from .= " $side JOIN civicrm_contribution ON civicrm_contribution.id = contribution_search_scredit_combined.id ";
535 $from .= " $side JOIN civicrm_contribution_soft ON civicrm_contribution_soft.id = contribution_search_scredit_combined.scredit_id";
536 }
537 break;
6a488035
TO
538
539 case 'civicrm_contribution_recur':
86845f9b 540 if ($mode == 1) {
95974e8e 541 // 'Made payment for the recurring contributions?' is ticked yes
1415b394 542 $from = " $side JOIN civicrm_contribution_recur ON contact_a.id = civicrm_contribution_recur.contact_id ";
24782d26 543 if (self::$_contribRecurPayment == TRUE) {
5aae2a90 544 $from .= " INNER JOIN civicrm_contribution cr ON cr.contribution_recur_id = civicrm_contribution_recur.id ";
95974e8e 545 }
86845f9b 546 }
547 else {
548 $from = " $side JOIN civicrm_contribution_recur ON civicrm_contribution.contribution_recur_id = civicrm_contribution_recur.id ";
549 }
6a488035
TO
550 break;
551
552 case 'civicrm_financial_type':
553 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
554 $from = " INNER JOIN civicrm_financial_type ON civicrm_contribution.financial_type_id = civicrm_financial_type.id ";
555 }
556 else {
557 $from = " $side JOIN civicrm_financial_type ON civicrm_contribution.financial_type_id = civicrm_financial_type.id ";
558 }
559 break;
560
6ef17211 561 case 'civicrm_financial_account':
562 if ($mode & CRM_Contact_BAO_Query::MODE_CONTACTS) {
563 $from = " $side JOIN civicrm_financial_account ON contact_a.id = civicrm_financial_account.contact_id ";
564 }
565 break;
566
6a488035 567 case 'civicrm_accounting_code':
6ef17211 568 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
569 $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' ";
570 $from .= " INNER JOIN civicrm_financial_account ON civicrm_financial_account.id = civicrm_entity_financial_account.financial_account_id ";
571 $from .= " INNER JOIN civicrm_option_value cov ON cov.value = civicrm_entity_financial_account.account_relationship AND cov.name = 'Income Account is' ";
572 $from .= " INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id AND cog.name = 'account_relationship' ";
573 }
39b795ba 574 break;
6a488035
TO
575
576 case 'civicrm_contribution_page':
3c151c70 577 $from = " $side JOIN civicrm_contribution_page ON civicrm_contribution.contribution_page_id = civicrm_contribution_page.id";
6a488035
TO
578 break;
579
580 case 'civicrm_product':
581 $from = " $side JOIN civicrm_contribution_product ON civicrm_contribution_product.contribution_id = civicrm_contribution.id";
582 $from .= " $side JOIN civicrm_product ON civicrm_contribution_product.product_id =civicrm_product.id ";
583 break;
584
36bf52ef 585 case 'contribution_softcredit_type':
353ffa53 586 $from = " $side JOIN civicrm_option_group option_group_contribution_softcredit_type ON
36bf52ef 587 (option_group_contribution_softcredit_type.name = 'soft_credit_type')";
77b97be7 588 $from .= " $side JOIN civicrm_option_value contribution_softcredit_type ON
36bf52ef
DS
589 ( civicrm_contribution_soft.soft_credit_type_id = contribution_softcredit_type.value
590 AND option_group_contribution_softcredit_type.id = contribution_softcredit_type.option_group_id )";
591 break;
592
6a488035
TO
593 case 'contribution_note':
594 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contribution' AND
595 civicrm_contribution.id = civicrm_note.entity_id )";
596 break;
597
6a488035
TO
598 case 'contribution_membership':
599 $from = " $side JOIN civicrm_membership_payment ON civicrm_membership_payment.contribution_id = civicrm_contribution.id";
600 $from .= " $side JOIN civicrm_membership ON civicrm_membership_payment.membership_id = civicrm_membership.id ";
601 break;
602
9ebd3386 603 case 'civicrm_campaign':
38310a51 604 //CRM-16764 - get survey clause from campaign bao
605 if (!CRM_Campaign_BAO_Query::$_applySurveyClause) {
606 $from = " $side JOIN civicrm_campaign ON civicrm_campaign.id = civicrm_contribution.campaign_id";
607 }
9ebd3386 608 break;
609
6a488035
TO
610 case 'contribution_participant':
611 $from = " $side JOIN civicrm_participant_payment ON civicrm_participant_payment.contribution_id = civicrm_contribution.id";
612 $from .= " $side JOIN civicrm_participant ON civicrm_participant_payment.participant_id = civicrm_participant.id ";
613 break;
614
615 case 'civicrm_contribution_soft':
be2fb01f 616 if (!in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
3dbf477c
DS
617 $from = " $side JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id";
618 }
6a488035
TO
619 break;
620
621 case 'civicrm_contribution_soft_contact':
be2fb01f 622 if (in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
77b97be7 623 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution.contact_id = civicrm_contact_d.id )
3dbf477c 624 AND contribution_search_scredit_combined.scredit_id IS NOT NULL";
0db6c3e1
TO
625 }
626 else {
3dbf477c
DS
627 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution_soft.contact_id = civicrm_contact_d.id )";
628 }
6a488035
TO
629 break;
630
631 case 'civicrm_contribution_soft_email':
632 $from .= " $side JOIN civicrm_email as soft_email ON (civicrm_contact_d.id = soft_email.contact_id )";
633 break;
634
635 case 'civicrm_contribution_soft_phone':
636 $from .= " $side JOIN civicrm_phone as soft_phone ON (civicrm_contact_d.id = soft_phone.contact_id )";
637 break;
39b795ba 638
6a488035 639 case 'contribution_batch':
61412579 640 $from .= " $side JOIN civicrm_entity_batch ON ( civicrm_entity_batch.entity_table = 'civicrm_financial_trxn'
641 AND civicrm_financial_trxn.id = civicrm_entity_batch.entity_id )";
642
6a488035
TO
643 $from .= " $side JOIN civicrm_batch ON civicrm_entity_batch.batch_id = civicrm_batch.id";
644 break;
898bfdcd
PN
645
646 case 'civicrm_financial_trxn':
647 $from .= " $side JOIN civicrm_entity_financial_trxn ON (
648 civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution'
649 AND civicrm_contribution.id = civicrm_entity_financial_trxn.entity_id )";
650
651 $from .= " $side JOIN civicrm_financial_trxn ON (
652 civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id )";
653 break;
6a488035
TO
654 }
655 return $from;
656 }
657
186c9c17 658 /**
35e6241a
EM
659 * Initialise the soft credit clause.
660 *
661 * @param CRM_Contact_BAO_Query $query
186c9c17 662 */
00be9182 663 public static function initializeAnySoftCreditClause(&$query) {
5928ea72 664 // @todo have a generic initialize on all components that gets called every query
665 // & rename this to match that fn name.
9ae25b56 666 if ($query->_mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
667 if (self::isSoftCreditOptionEnabled($query->_params)) {
ed81a415 668 unset($query->_distinctComponentClause);
f654cacf 669 $query->_rowCountClause = " count(civicrm_contribution.id)";
ed81a415 670 $query->_groupByComponentClause = " GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.contact_id, contribution_search_scredit_combined.scredit_id ";
36bf52ef 671 }
9ae25b56 672 else {
673 $query->_distinctComponentClause = ' civicrm_contribution.id';
674 }
f654cacf
DS
675 }
676 }
677
186c9c17 678 /**
35e6241a
EM
679 * Check if soft credits are enables.
680 *
186c9c17
EM
681 * @param array $queryParams
682 *
683 * @return bool
684 */
be2fb01f 685 public static function isSoftCreditOptionEnabled($queryParams = []) {
f654cacf
DS
686 if (!empty($queryParams)) {
687 foreach (array_keys($queryParams) as $id) {
688 if (empty($queryParams[$id][0])) {
689 continue;
690 }
38e1cb31
DS
691 if ($queryParams[$id][0] == 'contribution_or_softcredits') {
692 self::$_contribOrSoftCredit = $queryParams[$id][2];
693 }
f654cacf
DS
694 }
695 }
77b97be7 696 if (in_array(self::$_contribOrSoftCredit,
be2fb01f 697 ["only_scredits", "both_related", "both"])) {
bc438a52 698 if (!isset(\Civi::$statics[__CLASS__]['soft_credit_temp_table_name'])) {
353ffa53
TO
699 // build a temp table which is union of contributions and soft credits
700 // note: group-by in first part ensures uniqueness in counts
bc438a52 701 $tempQuery = '
77b97be7 702 SELECT con.id as id, con.contact_id, cso.id as filter_id, NULL as scredit_id
3dbf477c 703 FROM civicrm_contribution con
4f3846df 704 LEFT JOIN civicrm_contribution_soft cso ON con.id = cso.contribution_id
e5cceea5 705 GROUP BY id, contact_id, scredit_id, cso.id
3dbf477c 706 UNION ALL
77b97be7 707 SELECT scredit.contribution_id as id, scredit.contact_id, scredit.id as filter_id, scredit.id as scredit_id
bc438a52 708 FROM civicrm_contribution_soft as scredit';
709 \Civi::$statics[__CLASS__]['soft_credit_temp_table_name'] = CRM_Utils_SQL_TempTable::build()->createWithQuery(
710 $tempQuery
711 )->getName();
f654cacf 712 }
353ffa53
TO
713 return TRUE;
714 }
36bf52ef
DS
715 return FALSE;
716 }
717
186c9c17 718 /**
35e6241a
EM
719 * Get return properties for soft credits.
720 *
186c9c17
EM
721 * @param bool $isExportMode
722 *
723 * @return array
724 */
353ffa53 725 public static function softCreditReturnProperties($isExportMode = FALSE) {
be2fb01f 726 $properties = [
353ffa53 727 'contribution_soft_credit_name' => 1,
4f3846df 728 'contribution_soft_credit_amount' => 1,
353ffa53 729 'contribution_soft_credit_type' => 1,
be2fb01f 730 ];
4f3846df 731 if ($isExportMode) {
5850d2e9 732 $properties['contribution_soft_credit_contact_id'] = 1;
4f3846df
DS
733 $properties['contribution_soft_credit_contribution_id'] = 1;
734 }
735 return $properties;
736 }
737
186c9c17 738 /**
c7940124 739 * Get the list of fields required to populate the selector.
740 *
741 * The default return properties array returns far too many fields for 'everyday use. Every field you add to this array
742 * kills a small kitten so add carefully.
b4bb60fc
OH
743 *
744 * @param array $queryParams
745 * @return array
c7940124 746 */
b4bb60fc 747 public static function selectorReturnProperties($queryParams) {
be2fb01f 748 $properties = [
c7940124 749 'contact_type' => 1,
750 'contact_sub_type' => 1,
751 'sort_name' => 1,
752 'financial_type' => 1,
753 'contribution_source' => 1,
754 'is_test' => 1,
755 'receive_date' => 1,
756 'is_pay_later' => 1,
757 'thankyou_date' => 1,
758 'total_amount' => 1,
5deb2f24 759 // Without this value here we get an e-notice BUT the value does not appear to be rendered anywhere.
760 'contribution_campaign_id' => 1,
c7940124 761 'contribution_status_id' => 1,
762 // @todo return this & fix query to do pseudoconstant thing.
763 'contribution_status' => 1,
9a59ce91 764 'currency' => 1,
1eae0d75 765 'cancel_date' => 1,
2e80df5b 766 'contribution_recur_id' => 1,
be2fb01f 767 ];
c8dd6301 768 if (self::isSiteHasProducts()) {
769 $properties['product_name'] = 1;
770 $properties['contribution_product_id'] = 1;
771 }
b4bb60fc 772 if (self::isSoftCreditOptionEnabled($queryParams)) {
8f7c2652 773 $properties = array_merge($properties, self::softCreditReturnProperties());
774 }
775
776 return $properties;
c7940124 777 }
778
c8dd6301 779 /**
780 * Do any products exist in this site's database.
781 *
782 * @return bool
783 */
784 public static function isSiteHasProducts() {
785 if (!isset(\Civi::$statics[__CLASS__]['has_products'])) {
786 \Civi::$statics[__CLASS__]['has_products'] = (bool) CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_contribution_product LIMIT 1');
787 }
788 return \Civi::$statics[__CLASS__]['has_products'];
789 }
790
c7940124 791 /**
792 * Function you should avoid.
793 *
794 * This function returns default properties for contribution queries. However, they are
795 * far more than are required in 'most' cases and you should always try to return the return properties
796 * you actually require.
797 *
798 * It would be nice to throw an e-notice when this is called but it would trash the tests :-(.
799 *
800 * @param int $mode
186c9c17
EM
801 * @param bool $includeCustomFields
802 *
e60f24eb 803 * @return array|NULL
186c9c17 804 */
00be9182 805 public static function defaultReturnProperties($mode, $includeCustomFields = TRUE) {
6a488035
TO
806 $properties = NULL;
807 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
be2fb01f 808 $properties = [
5928ea72 809 // add
6a488035 810 'contact_type' => 1,
5928ea72 811 // fields
6a488035 812 'contact_sub_type' => 1,
5928ea72 813 // to
6a488035 814 'sort_name' => 1,
5928ea72 815 //this
6a488035 816 'display_name' => 1,
5928ea72 817 // array
6a488035 818 'financial_type' => 1,
5928ea72 819 // to
6a488035 820 'contribution_source' => 1,
5928ea72 821 // strangle
6a488035 822 'receive_date' => 1,
5928ea72 823 // site
6a488035 824 'thankyou_date' => 1,
5928ea72 825 // performance
6e7cc0f5 826 'contribution_cancel_date' => 1,
5928ea72 827 // and
6a488035 828 'total_amount' => 1,
5928ea72 829 // torture
6a488035 830 'accounting_code' => 1,
5928ea72 831 // small
afa0b07c 832 'payment_instrument' => 1,
5928ea72 833 // kittens
3a6eb174 834 'payment_instrument_id' => 1,
5928ea72 835 // argh
7bc1d4da 836 'contribution_check_number' => 1,
5928ea72 837 // no
6a488035 838 'non_deductible_amount' => 1,
5928ea72 839 // not
6a488035 840 'fee_amount' => 1,
5928ea72 841 // another
6a488035 842 'net_amount' => 1,
5928ea72 843 // expensive
6a488035 844 'trxn_id' => 1,
5928ea72 845 // join
6a488035 846 'invoice_id' => 1,
802c1c41 847 'invoice_number' => 1,
5928ea72 848 // added
6a488035 849 'currency' => 1,
5928ea72 850 // to
6a488035 851 'cancel_reason' => 1,
5928ea72 852 //every
6a488035 853 'receipt_date' => 1,
5928ea72 854 // query
5928ea72 855 //whether
5928ea72 856 // or
5928ea72 857 // not
5928ea72 858 // the
5928ea72 859 // field
5928ea72 860 // is
6a488035 861 'is_test' => 1,
5928ea72 862 // actually
6a488035 863 'is_pay_later' => 1,
5928ea72 864 // required
6a488035 865 'contribution_status' => 1,
5928ea72 866 // instead
6a488035 867 'contribution_status_id' => 1,
5928ea72 868 // of
6a488035 869 'contribution_recur_id' => 1,
5928ea72 870 // adding
6a488035 871 'amount_level' => 1,
5928ea72 872 // here
6a488035 873 'contribution_note' => 1,
5928ea72 874 // set
6a488035 875 'contribution_batch' => 1,
5928ea72 876 // return properties
9ebd3386 877 'contribution_campaign_title' => 1,
5928ea72 878 // on
36bf52ef 879 'contribution_campaign_id' => 1,
5928ea72 880 // calling
5928ea72 881 //function
be2fb01f 882 ];
c8dd6301 883 if (self::isSiteHasProducts()) {
884 $properties['fulfilled_date'] = 1;
885 $properties['product_name'] = 1;
886 $properties['contribution_product_id'] = 1;
887 $properties['product_option'] = 1;
888 $properties['sku'] = 1;
889 $properties['contribution_start_date'] = 1;
890 $properties['contribution_end_date'] = 1;
891 }
d4e2b978 892 if (self::isSoftCreditOptionEnabled()) {
4f3846df 893 $properties = array_merge($properties, self::softCreditReturnProperties());
36bf52ef 894 }
6a488035
TO
895 if ($includeCustomFields) {
896 // also get all the custom contribution properties
897 $fields = CRM_Core_BAO_CustomField::getFieldsForImport('Contribution');
898 if (!empty($fields)) {
899 foreach ($fields as $name => $dontCare) {
900 $properties[$name] = 1;
901 }
902 }
903 }
904 }
905 return $properties;
906 }
907
7123f88c 908 /**
909 * Get the metadata for fields to be included on the search form.
910 *
911 * @throws \CiviCRM_API3_Exception
912 */
913 public static function getSearchFieldMetadata() {
914 $fields = [
915 'contribution_source',
916 'cancel_reason',
917 'invoice_number',
6e7cc0f5
SL
918 'receive_date',
919 'contribution_cancel_date',
7123f88c 920 ];
921 $metadata = civicrm_api3('Contribution', 'getfields', [])['values'];
922 return array_intersect_key($metadata, array_flip($fields));
923 }
924
6a488035 925 /**
c0aaecf9 926 * Add all the elements shared between contribute search and advanced search.
6a488035 927 *
7123f88c 928 * @param \CRM_Contribute_Form_Search $form
929 *
930 * @throws \CRM_Core_Exception
931 * @throws \CiviCRM_API3_Exception
6a488035 932 */
00be9182 933 public static function buildSearchForm(&$form) {
6a488035 934
7123f88c 935 $form->addSearchFieldMetadata(['Contribution' => self::getSearchFieldMetadata()]);
1157f03f 936 $form->addSearchFieldMetadata(['ContributionRecur' => CRM_Contribute_BAO_ContributionRecur::getContributionRecurSearchFieldMetadata()]);
7123f88c 937 $form->addFormFieldsFromMetadata();
6a488035 938
be2fb01f
CW
939 $form->add('text', 'contribution_amount_low', ts('From'), ['size' => 8, 'maxlength' => 8]);
940 $form->addRule('contribution_amount_low', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('9.99', ' ')]), 'money');
6a488035 941
be2fb01f
CW
942 $form->add('text', 'contribution_amount_high', ts('To'), ['size' => 8, 'maxlength' => 8]);
943 $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
944
945 // Adding select option for curreny type -- CRM-4711
946 $form->add('select', 'contribution_currency_type',
947 ts('Currency Type'),
be2fb01f 948 [
7c550ca0 949 '' => ts('- any -'),
be2fb01f
CW
950 ] +
951 CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', ['labelColumn' => 'name']),
952 FALSE, ['class' => 'crm-select2']
6a488035
TO
953 );
954
1f0d8c92 955 // CRM-13848
573fd305 956 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::VIEW);
15cf9198 957 $form->addSelect('financial_type_id',
be2fb01f 958 ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => $financialTypes]
6a488035
TO
959 );
960
961 $form->add('select', 'contribution_page_id',
962 ts('Contribution Page'),
ab345ca5 963 CRM_Contribute_PseudoConstant::contributionPage(),
be2fb01f 964 FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]
6a488035
TO
965 );
966
6e219d15
SP
967 // use contribution_payment_instrument_id instead of payment_instrument_id
968 // Contribution Edit form (pop-up on contribution/Contact(display Result as Contribution) open on search form),
969 // then payment method change action not working properly because of same html ID present two time on one page
970 $form->addSelect('contribution_payment_instrument_id',
be2fb01f 971 ['entity' => 'contribution', 'field' => 'payment_instrument_id', 'multiple' => 'multiple', 'label' => ts('Payment Method'), 'option_url' => NULL, 'placeholder' => ts('- any -')]
6a488035
TO
972 );
973
1517c3e8 974 $form->add('select',
975 'contribution_pcp_made_through_id',
976 ts('Personal Campaign Page'),
be2fb01f 977 CRM_Contribute_PseudoConstant::pcPage(), FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]);
6a488035 978
c0aaecf9 979 $statusValues = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'search');
2b65bb8c 980 $form->add('select', 'contribution_status_id',
981 ts('Contribution Status'), $statusValues,
be2fb01f 982 FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']
3c151c70 983 );
6a488035
TO
984
985 // Add fields for thank you and receipt
8a4f27dc
CW
986 $form->addYesNo('contribution_thankyou_date_is_not_null', ts('Thank-you sent?'), TRUE);
987 $form->addYesNo('contribution_receipt_date_is_not_null', ts('Receipt sent?'), TRUE);
6a488035 988
8a4f27dc
CW
989 $form->addYesNo('contribution_pay_later', ts('Contribution is Pay Later?'), TRUE);
990 $form->addYesNo('contribution_recurring', ts('Contribution is Recurring?'), TRUE);
b32bc653 991
8a4f27dc 992 $form->addYesNo('contribution_test', ts('Contribution is a Test?'), TRUE);
6a488035
TO
993
994 // Add field for transaction ID search
3c151c70 995 $form->addElement('text', 'contribution_trxn_id', ts("Transaction ID"));
6a488035
TO
996 $form->addElement('text', 'contribution_check_number', ts('Check Number'));
997
998 // Add field for pcp display in roll search
8a4f27dc 999 $form->addYesNo('contribution_pcp_display_in_roll', ts('Personal Campaign Page Honor Roll?'), TRUE);
6a488035 1000
36bf52ef 1001 // Soft credit related fields
be2fb01f 1002 $options = [
3dbf477c 1003 'only_contribs' => ts('Contributions Only'),
e0b774f0 1004 'only_scredits' => ts('Soft Credits Only'),
353ffa53
TO
1005 'both_related' => ts('Soft Credits with related Hard Credit'),
1006 'both' => ts('Both'),
be2fb01f
CW
1007 ];
1008 $form->add('select', 'contribution_or_softcredits', ts('Contributions OR Soft Credits?'), $options, FALSE, ['class' => "crm-select2"]);
e88186f4 1009 $form->addSelect(
77b97be7 1010 'contribution_soft_credit_type_id',
be2fb01f 1011 [
353ffa53
TO
1012 'entity' => 'contribution_soft',
1013 'field' => 'soft_credit_type_id',
1014 'multiple' => TRUE,
1015 'context' => 'search',
be2fb01f 1016 ]
e88186f4 1017 );
36bf52ef 1018
be2fb01f 1019 $form->addField('financial_trxn_card_type_id', ['entity' => 'FinancialTrxn', 'name' => 'card_type_id', 'action' => 'get']);
898bfdcd 1020
be2fb01f 1021 $form->add('text', 'financial_trxn_pan_truncation', ts('Card Number'), [
c6ba3619
E
1022 'size' => 5,
1023 'maxlength' => 4,
1024 'autocomplete' => 'off',
be2fb01f 1025 ]);
c6ba3619 1026
c8dd6301 1027 if (CRM_Contribute_BAO_Query::isSiteHasProducts()) {
1028 // CRM-16713 - contribution search by premiums on 'Find Contribution' form.
1029 $form->add('select', 'contribution_product_id',
1030 ts('Premium'),
1031 CRM_Contribute_PseudoConstant::products(),
1032 FALSE, [
1033 'class' => 'crm-select2',
1034 'multiple' => 'multiple',
1330f57a 1035 'placeholder' => ts('- any -'),
c8dd6301 1036 ]
1037 );
1038 }
6ffab5b7 1039
be2fb01f 1040 self::addCustomFormFields($form, ['Contribution']);
6a488035
TO
1041
1042 CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'contribution_campaign_id');
1043
1044 // Add batch select
91aff94c 1045 $batches = CRM_Contribute_PseudoConstant::batch();
39b795ba 1046
481a74f4 1047 if (!empty($batches)) {
6a488035
TO
1048 $form->add('select', 'contribution_batch_id',
1049 ts('Batch Name'),
be2fb01f 1050 [
dc7b39df
JV
1051 '' => ts('- any -'),
1052 // CRM-19325
3086e282 1053 'IS NULL' => ts('None'),
be2fb01f
CW
1054 ] + $batches,
1055 FALSE, ['class' => 'crm-select2']
ab345ca5 1056 );
6a488035
TO
1057 }
1058
1059 $form->assign('validCiviContribute', TRUE);
be2fb01f 1060 $form->setDefaults(['contribution_test' => 0]);
24782d26 1061
1062 CRM_Contribute_BAO_ContributionRecur::recurringContribution($form);
6a488035
TO
1063 }
1064
186c9c17 1065 /**
35e6241a
EM
1066 * Get table names.
1067 *
1068 * @todo better function comment needed - what IS the point of this?
1069 *
1070 * @param array $tables
186c9c17 1071 */
00be9182 1072 public static function tableNames(&$tables) {
6a488035 1073 // Add contribution table
a7488080 1074 if (!empty($tables['civicrm_product'])) {
be2fb01f 1075 $tables = array_merge(['civicrm_contribution' => 1], $tables);
6a488035
TO
1076 }
1077
8cc574cf 1078 if (!empty($tables['civicrm_contribution_product']) && empty($tables['civicrm_product'])) {
6a488035
TO
1079 $tables['civicrm_product'] = 1;
1080 }
1081 }
a91e698a 1082
1083 /**
fe482240 1084 * Add the where for dates.
77b97be7 1085 *
014c4014
TO
1086 * @param array $values
1087 * Array of query values.
1088 * @param object $query
1089 * The query object.
1090 * @param string $name
1091 * Query field that is set.
1092 * @param string $field
1093 * Name of field to be set.
1094 * @param string $title
1095 * Title of the field.
77b97be7
EM
1096 *
1097 * @return bool
a91e698a 1098 */
00be9182 1099 public static function buildDateWhere(&$values, $query, $name, $field, $title) {
a91e698a 1100 $fieldPart = strpos($name, $field);
22e263ad 1101 if ($fieldPart === FALSE) {
7c550ca0 1102 return NULL;
a91e698a 1103 }
1104 // we only have recurring dates using this ATM so lets' short cut to find the table name
1105 $table = 'contribution_recur';
d3e86119 1106 $fieldName = explode($table . '_', $field);
a91e698a 1107 $query->dateQueryBuilder($values,
1108 'civicrm_' . $table, $field, $fieldName[1], $title
1109 );
1110 return TRUE;
1111 }
b32bc653 1112
686df921 1113 /**
1114 * Add the soft credit fields to the select fields.
1115 *
1116 * Extracted into separate function to improve readability of main select function.
1117 *
1118 * @param $query
1119 */
1120 private static function addSoftCreditFields(&$query) {
1121 $includeSoftCredits = self::isSoftCreditOptionEnabled($query->_params);
1122 if (!empty($query->_returnProperties['contribution_soft_credit_name'])) {
1123 if ($includeSoftCredits) {
1124 $query->_select['contribution_soft_credit_name'] = "civicrm_contact_d.sort_name as contribution_soft_credit_name";
1125 // also include contact id. Will help build hyperlinks
1126 $query->_select['contribution_soft_credit_contact_id'] = "civicrm_contact_d.id as contribution_soft_credit_contact_id";
1127 }
1128 $query->_element['contribution_soft_credit_name'] = 1;
1129 $query->_element['contribution_soft_credit_contact_id'] = 1;
1130
1131 $query->_tables['civicrm_contribution'] = 1;
1132 $query->_tables['civicrm_contribution_soft'] = 1;
1133 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1134 }
1135
1136 if (!empty($query->_returnProperties['contribution_soft_credit_contact_id'])) {
1137 $query->_tables['civicrm_contribution'] = 1;
1138 $query->_tables['civicrm_contribution_soft'] = 1;
1139 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1140 }
1141
1142 if (!empty($query->_returnProperties['contribution_soft_credit_amount'])) {
1143 if ($includeSoftCredits) {
1144 $query->_select['contribution_soft_credit_amount'] = "civicrm_contribution_soft.amount as contribution_soft_credit_amount";
1145 }
1146 $query->_element['contribution_soft_credit_amount'] = 1;
1147 $query->_tables['civicrm_contribution'] = 1;
1148 $query->_tables['civicrm_contribution_soft'] = 1;
1149 }
1150
1151 if (!empty($query->_returnProperties['contribution_soft_credit_type'])) {
1152 if ($includeSoftCredits) {
1153 $query->_select['contribution_soft_credit_type'] = "contribution_softcredit_type.label as contribution_soft_credit_type";
1154 }
1155 $query->_element['contribution_soft_credit_type'] = 1;
1156 $query->_tables['civicrm_contribution'] = 1;
1157 $query->_tables['contribution_softcredit_type'] = 1;
1158 }
1159
1160 if (!empty($query->_returnProperties['contribution_soft_credit_contribution_id'])) {
1161 if ($includeSoftCredits) {
1162 $query->_select['contribution_soft_credit_contribution_id'] = "civicrm_contribution_soft.contribution_id as contribution_soft_credit_contribution_id";
1163 }
1164 $query->_element['contribution_soft_credit_contribution_id'] = 1;
1165 $query->_tables['civicrm_contribution'] = 1;
1166 $query->_tables['civicrm_contribution_soft'] = 1;
1167 }
1168
1169 if (!empty($query->_returnProperties['contribution_soft_credit_email'])) {
1170 $query->_select['contribution_soft_credit_email'] = "soft_email.email as contribution_soft_credit_email";
1171 $query->_element['contribution_soft_credit_email'] = 1;
1172 $query->_tables['civicrm_contribution'] = 1;
1173 $query->_tables['civicrm_contribution_soft'] = 1;
1174 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1175 $query->_tables['civicrm_contribution_soft_email'] = 1;
1176 }
1177
1178 if (!empty($query->_returnProperties['contribution_soft_credit_phone'])) {
1179 $query->_select['contribution_soft_credit_email'] = "soft_phone.phone as contribution_soft_credit_phone";
1180 $query->_element['contribution_soft_credit_phone'] = 1;
1181 $query->_tables['civicrm_contribution'] = 1;
1182 $query->_tables['civicrm_contribution_soft'] = 1;
1183 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1184 $query->_tables['civicrm_contribution_soft_phone'] = 1;
1185 }
1186
1187 if (!empty($query->_returnProperties['contribution_soft_credit_pcp_id'])) {
1188 $query->_select['contribution_soft_credit_pcp_id'] = "civicrm_contribution_soft.pcp_id as contribution_soft_credit_pcp_id";
1189 $query->_element['contribution_soft_credit_pcp_id'] = 1;
1190 $query->_tables['civicrm_contribution'] = 1;
1191 $query->_tables['civicrm_contribution_soft'] = 1;
1192 }
1193 }
1194
6a488035 1195}