Merge pull request #14220 from pradpnayak/core/issues/923
[civicrm-core.git] / CRM / Contribute / BAO / Query.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33 class CRM_Contribute_BAO_Query extends CRM_Core_BAO_Query {
34
35 public static $_contribOrSoftCredit = "only_contribs";
36
37 public static $_contribRecurPayment = NULL;
38
39 /**
40 * Function get the searchable fields for contribution.
41 *
42 * This is basically the contribution fields plus some related entity fields.
43 *
44 * @param bool $checkPermission
45 *
46 * @return array
47 * Associative array of contribution fields
48 */
49 public static function getFields($checkPermission = TRUE) {
50 if (!isset(\Civi::$statics[__CLASS__]) || !isset(\Civi::$statics[__CLASS__]['fields']) || !isset(\Civi::$statics[__CLASS__]['fields']['contribution'])) {
51 // Adding fields with some care as those without unique names could clobber others.
52 // Refer to CRM_Contribute_Form_SearchTest for existing tests ... and to add more!
53 $testedRecurFields = array_fill_keys(['contribution_recur_trxn_id', 'contribution_recur_processor_id', 'contribution_recur_payment_processor_id'], 1);
54 $recurFields = array_intersect_key(CRM_Contribute_DAO_ContributionRecur::fields(), $testedRecurFields);
55 $fields = array_merge($recurFields, CRM_Contribute_BAO_Contribution::exportableFields($checkPermission));
56 CRM_Contribute_BAO_Contribution::appendPseudoConstantsToFields($fields);
57 unset($fields['contribution_contact_id']);
58 \Civi::$statics[__CLASS__]['fields']['contribution'] = $fields;
59 }
60 return \Civi::$statics[__CLASS__]['fields']['contribution'];
61 }
62
63 /**
64 * If contributions are involved, add the specific contribute fields.
65 *
66 * @param CRM_Contact_BAO_Query $query
67 */
68 public static function select(&$query) {
69 // if contribute mode add contribution id
70 if ($query->_mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
71 $query->_select['contribution_id'] = "civicrm_contribution.id as contribution_id";
72 $query->_element['contribution_id'] = 1;
73 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
74 }
75
76 // get accounting code
77 if (!empty($query->_returnProperties['accounting_code'])) {
78 $query->_select['accounting_code'] = "civicrm_financial_account.accounting_code as accounting_code";
79 $query->_element['accounting_code'] = 1;
80 $query->_tables['civicrm_accounting_code'] = 1;
81 $query->_tables['civicrm_financial_account'] = 1;
82 }
83
84 if (!empty($query->_returnProperties['contribution_note'])) {
85 $query->_select['contribution_note'] = "civicrm_note.note as contribution_note";
86 $query->_element['contribution_note'] = 1;
87 $query->_tables['contribution_note'] = 1;
88 $query->_tables['civicrm_contribution'] = 1;
89 }
90
91 if (!empty($query->_returnProperties['contribution_batch'])) {
92 $query->_select['contribution_batch'] = "civicrm_batch.title as contribution_batch";
93 $query->_element['contribution_batch'] = 1;
94 $query->_tables['civicrm_financial_trxn'] = 1;
95 $query->_tables['contribution_batch'] = 1;
96 }
97
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 }
102
103 self::addSoftCreditFields($query);
104 }
105
106 /**
107 * Get where clause.
108 *
109 * @param CRM_Contact_BAO_Query $query
110 */
111 public static function where(&$query) {
112 self::initializeAnySoftCreditClause($query);
113 foreach (array_keys($query->_params) as $id) {
114 if (empty($query->_params[$id][0])) {
115 continue;
116 }
117 if (substr($query->_params[$id][0], 0, 13) == 'contribution_' || substr($query->_params[$id][0], 0, 10) == 'financial_' || substr($query->_params[$id][0], 0, 8) == 'payment_') {
118 if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
119 $query->_useDistinct = TRUE;
120 }
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
134 self::whereClauseSingle($query->_params[$id], $query);
135 }
136 }
137 }
138
139 /**
140 * Get where clause for a single value.
141 *
142 * @param array $values
143 * @param CRM_Contact_BAO_Query $query
144 */
145 public static function whereClauseSingle(&$values, &$query) {
146 list($name, $op, $value, $grouping, $wildcard) = $values;
147
148 $quoteValue = NULL;
149 $fields = self::getFields();
150
151 if (!empty($value) && !is_array($value)) {
152 $quoteValue = "\"$value\"";
153 }
154
155 $recurrringFields = CRM_Contribute_BAO_ContributionRecur::getRecurringFields();
156 unset($recurrringFields['contribution_recur_payment_made']);
157 foreach ($recurrringFields as $dateField => $dateFieldTitle) {
158 if (self::buildDateWhere($values, $query, $name, $dateField, $dateFieldTitle)) {
159 return;
160 }
161 }
162 // These are legacy names.
163 // @todo enotices when these are hit so we can start to elimnate them.
164 $fieldAliases = [
165 'financial_type' => 'financial_type_id',
166 'contribution_page' => 'contribution_page_id',
167 'payment_instrument' => 'payment_instrument_id',
168 // or payment_instrument_id?
169 'contribution_payment_instrument' => 'contribution_payment_instrument_id',
170 'contribution_status' => 'contribution_status_id',
171 ];
172
173 $name = isset($fieldAliases[$name]) ? $fieldAliases[$name] : $name;
174 $qillName = $name;
175 if (in_array($name, $fieldAliases)) {
176 $qillName = array_search($name, $fieldAliases);
177 }
178 $pseudoExtraParam = [];
179
180 switch ($name) {
181 case 'contribution_date':
182 case 'contribution_date_low':
183 case 'contribution_date_low_time':
184 case 'contribution_date_high':
185 case 'contribution_date_high_time':
186 // process to / from date
187 $query->dateQueryBuilder($values,
188 'civicrm_contribution', 'contribution_date', 'receive_date', ts('Contribution Date')
189 );
190 return;
191
192 case 'contribution_amount':
193 case 'contribution_amount_low':
194 case 'contribution_amount_high':
195 // process min/max amount
196 $query->numberRangeBuilder($values,
197 'civicrm_contribution', 'contribution_amount',
198 'total_amount', 'Contribution Amount',
199 NULL
200 );
201 return;
202
203 case 'contribution_thankyou_date_is_not_null':
204 if ($value) {
205 $op = "IS NOT NULL";
206 $query->_qill[$grouping][] = ts('Contribution Thank-you Sent');
207 }
208 else {
209 $op = "IS NULL";
210 $query->_qill[$grouping][] = ts('Contribution Thank-you Not Sent');
211 }
212 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.thankyou_date", $op);
213 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
214 return;
215
216 case 'contribution_receipt_date_is_not_null':
217 if ($value) {
218 $op = "IS NOT NULL";
219 $query->_qill[$grouping][] = ts('Contribution Receipt Sent');
220 }
221 else {
222 $op = "IS NULL";
223 $query->_qill[$grouping][] = ts('Contribution Receipt Not Sent');
224 }
225 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.receipt_date", $op);
226 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
227 return;
228
229 case 'contribution_cancel_date':
230 case 'contribution_cancel_date_low':
231 case 'contribution_cancel_date_low_time':
232 case 'contribution_cancel_date_high':
233 case 'contribution_cancel_date_high_time':
234 // process to / from date
235 $query->dateQueryBuilder($values,
236 'civicrm_contribution', 'contribution_cancel_date', 'cancel_date', ts('Cancelled / Refunded Date')
237 );
238 return;
239
240 case 'financial_type_id':
241 case 'invoice_id':
242 case 'invoice_number':
243 case 'payment_instrument_id':
244 case 'contribution_payment_instrument_id':
245 case 'contribution_page_id':
246 case 'contribution_status_id':
247 case 'contribution_id':
248 case 'contribution_currency_type':
249 case 'contribution_currency':
250 case 'contribution_source':
251 case 'contribution_trxn_id':
252 case 'contribution_check_number':
253 case 'contribution_contact_id':
254 case (strpos($name, '_amount') !== FALSE):
255 case (strpos($name, '_date') !== FALSE && $name != 'contribution_fulfilled_date'):
256 case 'contribution_campaign_id':
257
258 $fieldNamesNotToStripContributionFrom = [
259 'contribution_currency_type',
260 'contribution_status_id',
261 'contribution_page_id',
262 ];
263 // @todo these are mostly legacy params. Find a better way to deal with them.
264 if (!in_array($name, $fieldNamesNotToStripContributionFrom)
265 ) {
266 if (!isset($fields[$name])) {
267 $qillName = str_replace('contribution_', '', $qillName);
268 }
269 $name = str_replace('contribution_', '', $name);
270 }
271 if (in_array($name, ['contribution_currency', 'contribution_currency_type'])) {
272 $qillName = $name = 'currency';
273 $pseudoExtraParam = ['labelColumn' => 'name'];
274 }
275
276 $dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
277
278 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.$name", $op, $value, $dataType);
279 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_Contribution', $name, $value, $op, $pseudoExtraParam);
280 if (!($name == 'id' && $value == 0)) {
281 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
282 }
283 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
284 return;
285
286 case 'contribution_pcp_made_through_id':
287 case 'contribution_soft_credit_type_id':
288 $qillName = $name;
289 if ($name == 'contribution_pcp_made_through_id') {
290 $qillName = $name = 'pcp_id';
291 $fields[$name] = ['title' => ts('Personal Campaign Page'), 'type' => 2];
292 }
293 if ($name == 'contribution_soft_credit_type_id') {
294 $qillName = str_replace('_id', '', $qillName);
295 $fields[$qillName]['type'] = $fields[$qillName]['data_type'];
296 $name = str_replace('contribution_', '', $name);
297 }
298 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_soft.$name",
299 $op, $value, CRM_Utils_Type::typeToString($fields[$qillName]['type'])
300 );
301 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_ContributionSoft', $name, $value, $op);
302 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
303 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
304 return;
305
306 case 'contribution_or_softcredits':
307 if ($value == 'only_scredits') {
308 $query->_where[$grouping][] = "contribution_search_scredit_combined.scredit_id IS NOT NULL";
309 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits Only');
310 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
311 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
312 }
313 elseif ($value == 'both_related') {
314 $query->_where[$grouping][] = "contribution_search_scredit_combined.filter_id IS NOT NULL";
315 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits with related Hard Credit');
316 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
317 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
318 }
319 elseif ($value == 'both') {
320 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Both');
321 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
322 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
323 }
324 // default option: $value == 'only_contribs'
325 return;
326
327 case 'contribution_is_test':
328 // By default is Contribution Search form we choose is_test = 0 in otherwords always show active contribution
329 // so in case if any one choose any Yes/No avoid the default clause otherwise it will be conflict in whereClause
330 $key = array_search('civicrm_contribution.is_test = 0', $query->_where[$grouping]);
331 if (!empty($key)) {
332 unset($query->_where[$grouping][$key]);
333 }
334 case 'contribution_test':
335 // We dont want to include all tests for sql OR CRM-7827
336 if (!$value || $query->getOperator() != 'OR') {
337 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.is_test", $op, $value, "Boolean");
338 if ($value) {
339 $query->_qill[$grouping][] = ts("Only Display Test Contributions");
340 }
341 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
342 }
343 return;
344
345 case 'contribution_is_pay_later':
346 case 'contribution_pay_later':
347 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.is_pay_later", $op, $value, "Boolean");
348 if ($value) {
349 $query->_qill[$grouping][] = ts("Find Pay Later Contributions");
350 }
351 else {
352 $query->_qill[$grouping][] = ts("Exclude Pay Later Contributions");
353 }
354 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
355 return;
356
357 case 'contribution_recurring':
358 if ($value) {
359 $query->_where[$grouping][] = "civicrm_contribution.contribution_recur_id IS NOT NULL";
360 $query->_qill[$grouping][] = ts("Find Recurring Contributions");
361 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
362 }
363 else {
364 $query->_where[$grouping][] = "civicrm_contribution.contribution_recur_id IS NULL";
365 $query->_qill[$grouping][] = ts("Exclude Recurring Contributions");
366 }
367 return;
368
369 case 'contribution_recur_id':
370 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.contribution_recur_id",
371 $op, $value, "Integer"
372 );
373 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
374 return;
375
376 case 'contribution_recur_payment_processor_id':
377 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_recur.payment_processor_id", $op, $value, "String");
378 $paymentProcessors = civicrm_api3('PaymentProcessor', 'get', []);
379 $paymentProcessorNames = [];
380 foreach ($value as $paymentProcessorId) {
381 $paymentProcessorNames[] = $paymentProcessors['values'][$paymentProcessorId]['name'];
382 }
383 $query->_qill[$grouping][] = ts("Recurring Contribution Payment Processor %1 %2", [1 => $op, 2 => implode(', ', $paymentProcessorNames)]);
384 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
385 return;
386
387 case 'contribution_recur_processor_id':
388 case 'contribution_recur_trxn_id':
389 $spec = $fields[$name];
390 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($spec['where'],
391 $op, $value, "String"
392 );
393 $query->_qill[$grouping][] = ts("Recurring Contribution %1 %2 '%3'", [1 => $fields[$name]['title'], 2 => $op, 3 => $value]);
394 $query->_tables[$spec['table_name']] = $query->_whereTables[$spec['table_name']] = 1;
395 return;
396
397 case 'contribution_recur_payment_made':
398 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_recur.id", 'IS NOT EMPTY');
399 if ($value == 2) {
400 $query->_qill[$grouping][] = ts("Recurring contributions with at least one payment");
401 self::$_contribRecurPayment = TRUE;
402 }
403 else {
404 $query->_qill[$grouping][] = ts("All recurring contributions regardless of payments");
405 self::$_contribRecurPayment = FALSE;
406 }
407 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
408 return;
409
410 case 'contribution_recur_contribution_status_id':
411 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_recur.contribution_status_id", $op, $value, 'String');
412 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_ContributionRecur', 'contribution_status_id', $value, $op, $pseudoExtraParam);
413 $query->_qill[$grouping][] = ts("Recurring Contribution Status %1 '%2'", [1 => $op, 2 => $value]);
414 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
415 return;
416
417 case 'contribution_note':
418 $value = CRM_Core_DAO::escapeString($value);
419 if ($wildcard) {
420 $value = "%$value%";
421 $op = 'LIKE';
422 }
423 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_note.note', $op, $value, "String");
424 $query->_qill[$grouping][] = ts('Contribution Note %1 %2', [1 => $op, 2 => $quoteValue]);
425 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = $query->_whereTables['contribution_note'] = 1;
426 return;
427
428 case 'contribution_membership_id':
429 $query->_where[$grouping][] = " civicrm_membership.id $op $value";
430 $query->_tables['contribution_membership'] = $query->_whereTables['contribution_membership'] = 1;
431
432 return;
433
434 case 'contribution_participant_id':
435 $query->_where[$grouping][] = " civicrm_participant.id $op $value";
436 $query->_tables['contribution_participant'] = $query->_whereTables['contribution_participant'] = 1;
437 return;
438
439 case 'contribution_pcp_display_in_roll':
440 $query->_where[$grouping][] = " civicrm_contribution_soft.pcp_display_in_roll $op '$value'";
441 if ($value) {
442 $query->_qill[$grouping][] = ts("Personal Campaign Page Honor Roll");
443 }
444 else {
445 $query->_qill[$grouping][] = ts("NOT Personal Campaign Page Honor Roll");
446 }
447 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
448 return;
449
450 case 'contribution_batch_id':
451 list($qillOp, $qillValue) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Batch_BAO_EntityBatch', 'batch_id', $value, $op);
452 $query->_qill[$grouping][] = ts('Batch Name %1 %2', [1 => $qillOp, 2 => $qillValue]);
453 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_entity_batch.batch_id', $op, $value);
454 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
455 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
456 $query->_tables['contribution_batch'] = $query->_whereTables['contribution_batch'] = 1;
457 return;
458
459 case 'contribution_product_id':
460 // CRM-16713 - contribution search by premiums on 'Find Contribution' form.
461 $qillName = $name;
462 list($operator, $productValue) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_Product', $name, $value, $op);
463 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $operator, 3 => $productValue]);
464 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_product.id", $op, $value);
465 $query->_tables['civicrm_product'] = $query->_whereTables['civicrm_product'] = 1;
466 return;
467
468 case 'contribution_is_payment':
469 $query->_where[$grouping][] = " civicrm_financial_trxn.is_payment $op $value";
470 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
471 return;
472
473 case 'financial_trxn_card_type_id':
474 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_financial_trxn.card_type_id', $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', 'card_type_id', $value, $op);
478 $query->_qill[$grouping][] = ts('Card Type %1 %2', [1 => $op, 2 => $value]);
479 return;
480
481 case 'financial_trxn_pan_truncation':
482 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_financial_trxn.pan_truncation', $op, $value);
483 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
484 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
485 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Financial_DAO_FinancialTrxn', 'pan_truncation', $value, $op);
486 $query->_qill[$grouping][] = ts('Card Number %1 %2', [1 => $op, 2 => $value]);
487 return;
488
489 default:
490 //all other elements are handle in this case
491 $fldName = substr($name, 13);
492 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
493 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.financial_type_id", 'IN', array_keys($financialTypes), 'String');
494 if (!isset($fields[$fldName])) {
495 // CRM-12597
496 CRM_Core_Session::setStatus(ts(
497 'We did not recognize the search field: %1. Please check and fix your contribution related smart groups.',
498 [1 => $fldName]
499 )
500 );
501 return;
502 }
503 $whereTable = $fields[$fldName];
504 if (!is_array($value)) {
505 $value = trim($value);
506 }
507
508 $dataType = "String";
509 if (!empty($whereTable['type'])) {
510 $dataType = CRM_Utils_Type::typeToString($whereTable['type']);
511 }
512
513 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($whereTable['where'], $op, $value, $dataType);
514 $query->_qill[$grouping][] = "$whereTable[title] $op $quoteValue";
515 list($tableName) = explode('.', $whereTable['where'], 2);
516 $query->_tables[$tableName] = $query->_whereTables[$tableName] = 1;
517 if ($tableName == 'civicrm_contribution_product') {
518 $query->_tables['civicrm_product'] = $query->_whereTables['civicrm_product'] = 1;
519 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
520 }
521 else {
522 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
523 }
524 }
525 }
526
527 /**
528 * Get from clause.
529 *
530 * @param string $name
531 * @param string $mode
532 * @param string $side
533 *
534 * @return NULL|string
535 */
536 public static function from($name, $mode, $side) {
537 $from = NULL;
538 switch ($name) {
539 case 'civicrm_contribution':
540 $from = " $side JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id ";
541 if (in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
542 // switch the from table if its only soft credit search
543 $from = " $side JOIN contribution_search_scredit_combined ON contribution_search_scredit_combined.contact_id = contact_a.id ";
544 $from .= " $side JOIN civicrm_contribution ON civicrm_contribution.id = contribution_search_scredit_combined.id ";
545 $from .= " $side JOIN civicrm_contribution_soft ON civicrm_contribution_soft.id = contribution_search_scredit_combined.scredit_id";
546 }
547 break;
548
549 case 'civicrm_contribution_recur':
550 if ($mode == 1) {
551 // 'Made payment for the recurring contributions?' is ticked yes
552 $from = " $side JOIN civicrm_contribution_recur ON contact_a.id = civicrm_contribution_recur.contact_id ";
553 if (self::$_contribRecurPayment == TRUE) {
554 $from .= " INNER JOIN civicrm_contribution cr ON cr.contribution_recur_id = civicrm_contribution_recur.id ";
555 }
556 }
557 else {
558 $from = " $side JOIN civicrm_contribution_recur ON civicrm_contribution.contribution_recur_id = civicrm_contribution_recur.id ";
559 }
560 break;
561
562 case 'civicrm_financial_type':
563 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
564 $from = " INNER JOIN civicrm_financial_type ON civicrm_contribution.financial_type_id = civicrm_financial_type.id ";
565 }
566 else {
567 $from = " $side JOIN civicrm_financial_type ON civicrm_contribution.financial_type_id = civicrm_financial_type.id ";
568 }
569 break;
570
571 case 'civicrm_financial_account':
572 if ($mode & CRM_Contact_BAO_Query::MODE_CONTACTS) {
573 $from = " $side JOIN civicrm_financial_account ON contact_a.id = civicrm_financial_account.contact_id ";
574 }
575 break;
576
577 case 'civicrm_accounting_code':
578 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
579 $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' ";
580 $from .= " INNER JOIN civicrm_financial_account ON civicrm_financial_account.id = civicrm_entity_financial_account.financial_account_id ";
581 $from .= " INNER JOIN civicrm_option_value cov ON cov.value = civicrm_entity_financial_account.account_relationship AND cov.name = 'Income Account is' ";
582 $from .= " INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id AND cog.name = 'account_relationship' ";
583 }
584 break;
585
586 case 'civicrm_contribution_page':
587 $from = " $side JOIN civicrm_contribution_page ON civicrm_contribution.contribution_page_id = civicrm_contribution_page.id";
588 break;
589
590 case 'civicrm_product':
591 $from = " $side JOIN civicrm_contribution_product ON civicrm_contribution_product.contribution_id = civicrm_contribution.id";
592 $from .= " $side JOIN civicrm_product ON civicrm_contribution_product.product_id =civicrm_product.id ";
593 break;
594
595 case 'contribution_softcredit_type':
596 $from = " $side JOIN civicrm_option_group option_group_contribution_softcredit_type ON
597 (option_group_contribution_softcredit_type.name = 'soft_credit_type')";
598 $from .= " $side JOIN civicrm_option_value contribution_softcredit_type ON
599 ( civicrm_contribution_soft.soft_credit_type_id = contribution_softcredit_type.value
600 AND option_group_contribution_softcredit_type.id = contribution_softcredit_type.option_group_id )";
601 break;
602
603 case 'contribution_note':
604 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contribution' AND
605 civicrm_contribution.id = civicrm_note.entity_id )";
606 break;
607
608 case 'contribution_membership':
609 $from = " $side JOIN civicrm_membership_payment ON civicrm_membership_payment.contribution_id = civicrm_contribution.id";
610 $from .= " $side JOIN civicrm_membership ON civicrm_membership_payment.membership_id = civicrm_membership.id ";
611 break;
612
613 case 'civicrm_campaign':
614 //CRM-16764 - get survey clause from campaign bao
615 if (!CRM_Campaign_BAO_Query::$_applySurveyClause) {
616 $from = " $side JOIN civicrm_campaign ON civicrm_campaign.id = civicrm_contribution.campaign_id";
617 }
618 break;
619
620 case 'contribution_participant':
621 $from = " $side JOIN civicrm_participant_payment ON civicrm_participant_payment.contribution_id = civicrm_contribution.id";
622 $from .= " $side JOIN civicrm_participant ON civicrm_participant_payment.participant_id = civicrm_participant.id ";
623 break;
624
625 case 'civicrm_contribution_soft':
626 if (!in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
627 $from = " $side JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id";
628 }
629 break;
630
631 case 'civicrm_contribution_soft_contact':
632 if (in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
633 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution.contact_id = civicrm_contact_d.id )
634 AND contribution_search_scredit_combined.scredit_id IS NOT NULL";
635 }
636 else {
637 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution_soft.contact_id = civicrm_contact_d.id )";
638 }
639 break;
640
641 case 'civicrm_contribution_soft_email':
642 $from .= " $side JOIN civicrm_email as soft_email ON (civicrm_contact_d.id = soft_email.contact_id )";
643 break;
644
645 case 'civicrm_contribution_soft_phone':
646 $from .= " $side JOIN civicrm_phone as soft_phone ON (civicrm_contact_d.id = soft_phone.contact_id )";
647 break;
648
649 case 'contribution_batch':
650 $from .= " $side JOIN civicrm_entity_batch ON ( civicrm_entity_batch.entity_table = 'civicrm_financial_trxn'
651 AND civicrm_financial_trxn.id = civicrm_entity_batch.entity_id )";
652
653 $from .= " $side JOIN civicrm_batch ON civicrm_entity_batch.batch_id = civicrm_batch.id";
654 break;
655
656 case 'civicrm_financial_trxn':
657 $from .= " $side JOIN civicrm_entity_financial_trxn ON (
658 civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution'
659 AND civicrm_contribution.id = civicrm_entity_financial_trxn.entity_id )";
660
661 $from .= " $side JOIN civicrm_financial_trxn ON (
662 civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id )";
663 break;
664 }
665 return $from;
666 }
667
668 /**
669 * Initialise the soft credit clause.
670 *
671 * @param CRM_Contact_BAO_Query $query
672 */
673 public static function initializeAnySoftCreditClause(&$query) {
674 // @todo have a generic initialize on all components that gets called every query
675 // & rename this to match that fn name.
676 if ($query->_mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
677 if (self::isSoftCreditOptionEnabled($query->_params)) {
678 unset($query->_distinctComponentClause);
679 $query->_rowCountClause = " count(civicrm_contribution.id)";
680 $query->_groupByComponentClause = " GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.contact_id, contribution_search_scredit_combined.scredit_id ";
681 }
682 else {
683 $query->_distinctComponentClause = ' civicrm_contribution.id';
684 }
685 }
686 }
687
688 /**
689 * Check if soft credits are enables.
690 *
691 * @param array $queryParams
692 *
693 * @return bool
694 */
695 public static function isSoftCreditOptionEnabled($queryParams = []) {
696 static $tempTableFilled = FALSE;
697 if (!empty($queryParams)) {
698 foreach (array_keys($queryParams) as $id) {
699 if (empty($queryParams[$id][0])) {
700 continue;
701 }
702 if ($queryParams[$id][0] == 'contribution_or_softcredits') {
703 self::$_contribOrSoftCredit = $queryParams[$id][2];
704 }
705 }
706 }
707 if (in_array(self::$_contribOrSoftCredit,
708 ["only_scredits", "both_related", "both"])) {
709 if (!$tempTableFilled) {
710 // build a temp table which is union of contributions and soft credits
711 // note: group-by in first part ensures uniqueness in counts
712 $tempQuery = "
713 CREATE TEMPORARY TABLE IF NOT EXISTS contribution_search_scredit_combined AS
714 SELECT con.id as id, con.contact_id, cso.id as filter_id, NULL as scredit_id
715 FROM civicrm_contribution con
716 LEFT JOIN civicrm_contribution_soft cso ON con.id = cso.contribution_id
717 GROUP BY id, contact_id, scredit_id, cso.id
718 UNION ALL
719 SELECT scredit.contribution_id as id, scredit.contact_id, scredit.id as filter_id, scredit.id as scredit_id
720 FROM civicrm_contribution_soft as scredit";
721 CRM_Core_DAO::executeQuery($tempQuery);
722 $tempTableFilled = TRUE;
723 }
724 return TRUE;
725 }
726 return FALSE;
727 }
728
729 /**
730 * Get return properties for soft credits.
731 *
732 * @param bool $isExportMode
733 *
734 * @return array
735 */
736 public static function softCreditReturnProperties($isExportMode = FALSE) {
737 $properties = [
738 'contribution_soft_credit_name' => 1,
739 'contribution_soft_credit_amount' => 1,
740 'contribution_soft_credit_type' => 1,
741 ];
742 if ($isExportMode) {
743 $properties['contribution_soft_credit_contact_id'] = 1;
744 $properties['contribution_soft_credit_contribution_id'] = 1;
745 }
746 return $properties;
747 }
748
749 /**
750 * Get the list of fields required to populate the selector.
751 *
752 * The default return properties array returns far too many fields for 'everyday use. Every field you add to this array
753 * kills a small kitten so add carefully.
754 *
755 * @param array $queryParams
756 * @return array
757 */
758 public static function selectorReturnProperties($queryParams) {
759 $properties = [
760 'contact_type' => 1,
761 'contact_sub_type' => 1,
762 'sort_name' => 1,
763 'financial_type' => 1,
764 'contribution_source' => 1,
765 'is_test' => 1,
766 'receive_date' => 1,
767 'is_pay_later' => 1,
768 'thankyou_date' => 1,
769 'total_amount' => 1,
770 // Without this value here we get an e-notice BUT the value does not appear to be rendered anywhere.
771 'contribution_campaign_id' => 1,
772 'contribution_status_id' => 1,
773 // @todo return this & fix query to do pseudoconstant thing.
774 'contribution_status' => 1,
775 'currency' => 1,
776 'cancel_date' => 1,
777 'contribution_recur_id' => 1,
778 ];
779 if (self::isSiteHasProducts()) {
780 $properties['product_name'] = 1;
781 $properties['contribution_product_id'] = 1;
782 }
783 if (self::isSoftCreditOptionEnabled($queryParams)) {
784 $properties = array_merge($properties, self::softCreditReturnProperties());
785 }
786
787 return $properties;
788 }
789
790 /**
791 * Do any products exist in this site's database.
792 *
793 * @return bool
794 */
795 public static function isSiteHasProducts() {
796 if (!isset(\Civi::$statics[__CLASS__]['has_products'])) {
797 \Civi::$statics[__CLASS__]['has_products'] = (bool) CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_contribution_product LIMIT 1');
798 }
799 return \Civi::$statics[__CLASS__]['has_products'];
800 }
801
802 /**
803 * Function you should avoid.
804 *
805 * This function returns default properties for contribution queries. However, they are
806 * far more than are required in 'most' cases and you should always try to return the return properties
807 * you actually require.
808 *
809 * It would be nice to throw an e-notice when this is called but it would trash the tests :-(.
810 *
811 * @param int $mode
812 * @param bool $includeCustomFields
813 *
814 * @return array|NULL
815 */
816 public static function defaultReturnProperties($mode, $includeCustomFields = TRUE) {
817 $properties = NULL;
818 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
819 $properties = [
820 // add
821 'contact_type' => 1,
822 // fields
823 'contact_sub_type' => 1,
824 // to
825 'sort_name' => 1,
826 //this
827 'display_name' => 1,
828 // array
829 'financial_type' => 1,
830 // to
831 'contribution_source' => 1,
832 // strangle
833 'receive_date' => 1,
834 // site
835 'thankyou_date' => 1,
836 // performance
837 'cancel_date' => 1,
838 // and
839 'total_amount' => 1,
840 // torture
841 'accounting_code' => 1,
842 // small
843 'payment_instrument' => 1,
844 // kittens
845 'payment_instrument_id' => 1,
846 // argh
847 'contribution_check_number' => 1,
848 // no
849 'non_deductible_amount' => 1,
850 // not
851 'fee_amount' => 1,
852 // another
853 'net_amount' => 1,
854 // expensive
855 'trxn_id' => 1,
856 // join
857 'invoice_id' => 1,
858 'invoice_number' => 1,
859 // added
860 'currency' => 1,
861 // to
862 'cancel_reason' => 1,
863 //every
864 'receipt_date' => 1,
865 // query
866 //whether
867 // or
868 // not
869 // the
870 // field
871 // is
872 'is_test' => 1,
873 // actually
874 'is_pay_later' => 1,
875 // required
876 'contribution_status' => 1,
877 // instead
878 'contribution_status_id' => 1,
879 // of
880 'contribution_recur_id' => 1,
881 // adding
882 'amount_level' => 1,
883 // here
884 'contribution_note' => 1,
885 // set
886 'contribution_batch' => 1,
887 // return properties
888 'contribution_campaign_title' => 1,
889 // on
890 'contribution_campaign_id' => 1,
891 // calling
892 //function
893 ];
894 if (self::isSiteHasProducts()) {
895 $properties['fulfilled_date'] = 1;
896 $properties['product_name'] = 1;
897 $properties['contribution_product_id'] = 1;
898 $properties['product_option'] = 1;
899 $properties['sku'] = 1;
900 $properties['contribution_start_date'] = 1;
901 $properties['contribution_end_date'] = 1;
902 }
903 if (self::isSoftCreditOptionEnabled()) {
904 $properties = array_merge($properties, self::softCreditReturnProperties());
905 }
906 if ($includeCustomFields) {
907 // also get all the custom contribution properties
908 $fields = CRM_Core_BAO_CustomField::getFieldsForImport('Contribution');
909 if (!empty($fields)) {
910 foreach ($fields as $name => $dontCare) {
911 $properties[$name] = 1;
912 }
913 }
914 }
915 }
916 return $properties;
917 }
918
919 /**
920 * Add all the elements shared between contribute search and advnaced search.
921 *
922 * @param CRM_Core_Form $form
923 */
924 public static function buildSearchForm(&$form) {
925
926 // Added contribution source
927 $form->addElement('text', 'contribution_source', ts('Contribution Source'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'source'));
928
929 CRM_Core_Form_Date::buildDateRange($form, 'contribution_date', 1, '_low', '_high', ts('From:'), FALSE);
930 // CRM-17602
931 // This hidden element added for displaying Date Range error correctly. Definitely a dirty hack, but... it works.
932 $form->addElement('hidden', 'contribution_date_range_error');
933 $form->addFormRule(['CRM_Contribute_BAO_Query', 'formRule'], $form);
934
935 $form->add('text', 'contribution_amount_low', ts('From'), ['size' => 8, 'maxlength' => 8]);
936 $form->addRule('contribution_amount_low', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('9.99', ' ')]), 'money');
937
938 $form->add('text', 'contribution_amount_high', ts('To'), ['size' => 8, 'maxlength' => 8]);
939 $form->addRule('contribution_amount_high', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('99.99', ' ')]), 'money');
940
941 $form->addField('cancel_reason', ['entity' => 'Contribution']);
942 CRM_Core_Form_Date::buildDateRange($form, 'contribution_cancel_date', 1, '_low', '_high', ts('From:'), FALSE);
943 $form->addElement('hidden', 'contribution_cancel_date_range_error');
944
945 // Adding select option for curreny type -- CRM-4711
946 $form->add('select', 'contribution_currency_type',
947 ts('Currency Type'),
948 [
949 '' => ts('- any -'),
950 ] +
951 CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', ['labelColumn' => 'name']),
952 FALSE, ['class' => 'crm-select2']
953 );
954
955 // CRM-13848
956 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::VIEW);
957 $form->addSelect('financial_type_id',
958 ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => $financialTypes]
959 );
960
961 $form->add('select', 'contribution_page_id',
962 ts('Contribution Page'),
963 CRM_Contribute_PseudoConstant::contributionPage(),
964 FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]
965 );
966
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',
971 ['entity' => 'contribution', 'field' => 'payment_instrument_id', 'multiple' => 'multiple', 'label' => ts('Payment Method'), 'option_url' => NULL, 'placeholder' => ts('- any -')]
972 );
973
974 $form->add('select',
975 'contribution_pcp_made_through_id',
976 ts('Personal Campaign Page'),
977 CRM_Contribute_PseudoConstant::pcPage(), FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]);
978
979 $statusValues = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id');
980 $form->add('select', 'contribution_status_id',
981 ts('Contribution Status'), $statusValues,
982 FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']
983 );
984
985 // Add fields for thank you and receipt
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);
988
989 $form->addYesNo('contribution_pay_later', ts('Contribution is Pay Later?'), TRUE);
990 $form->addYesNo('contribution_recurring', ts('Contribution is Recurring?'), TRUE);
991
992 $form->addYesNo('contribution_test', ts('Contribution is a Test?'), TRUE);
993
994 // Add field for transaction ID search
995 $form->addElement('text', 'contribution_trxn_id', ts("Transaction ID"));
996 $form->addElement('text', 'invoice_number', ts("Invoice Number"));
997 $form->addElement('text', 'contribution_check_number', ts('Check Number'));
998
999 // Add field for pcp display in roll search
1000 $form->addYesNo('contribution_pcp_display_in_roll', ts('Personal Campaign Page Honor Roll?'), TRUE);
1001
1002 // Soft credit related fields
1003 $options = [
1004 'only_contribs' => ts('Contributions Only'),
1005 'only_scredits' => ts('Soft Credits Only'),
1006 'both_related' => ts('Soft Credits with related Hard Credit'),
1007 'both' => ts('Both'),
1008 ];
1009 $form->add('select', 'contribution_or_softcredits', ts('Contributions OR Soft Credits?'), $options, FALSE, ['class' => "crm-select2"]);
1010 $form->addSelect(
1011 'contribution_soft_credit_type_id',
1012 [
1013 'entity' => 'contribution_soft',
1014 'field' => 'soft_credit_type_id',
1015 'multiple' => TRUE,
1016 'context' => 'search',
1017 ]
1018 );
1019
1020 $form->addField('financial_trxn_card_type_id', ['entity' => 'FinancialTrxn', 'name' => 'card_type_id', 'action' => 'get']);
1021
1022 $form->add('text', 'financial_trxn_pan_truncation', ts('Card Number'), [
1023 'size' => 5,
1024 'maxlength' => 4,
1025 'autocomplete' => 'off',
1026 ]);
1027
1028 if (CRM_Contribute_BAO_Query::isSiteHasProducts()) {
1029 // CRM-16713 - contribution search by premiums on 'Find Contribution' form.
1030 $form->add('select', 'contribution_product_id',
1031 ts('Premium'),
1032 CRM_Contribute_PseudoConstant::products(),
1033 FALSE, [
1034 'class' => 'crm-select2',
1035 'multiple' => 'multiple',
1036 'placeholder' => ts('- any -'),
1037 ]
1038 );
1039 }
1040
1041 self::addCustomFormFields($form, ['Contribution']);
1042
1043 CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'contribution_campaign_id');
1044
1045 // Add batch select
1046 $batches = CRM_Contribute_PseudoConstant::batch();
1047
1048 if (!empty($batches)) {
1049 $form->add('select', 'contribution_batch_id',
1050 ts('Batch Name'),
1051 [
1052 '' => ts('- any -'),
1053 // CRM-19325
1054 'IS NULL' => ts('None'),
1055 ] + $batches,
1056 FALSE, ['class' => 'crm-select2']
1057 );
1058 }
1059
1060 $form->assign('validCiviContribute', TRUE);
1061 $form->setDefaults(['contribution_test' => 0]);
1062
1063 CRM_Contribute_BAO_ContributionRecur::recurringContribution($form);
1064 }
1065
1066 /**
1067 * Get table names.
1068 *
1069 * @todo better function comment needed - what IS the point of this?
1070 *
1071 * @param array $tables
1072 */
1073 public static function tableNames(&$tables) {
1074 // Add contribution table
1075 if (!empty($tables['civicrm_product'])) {
1076 $tables = array_merge(['civicrm_contribution' => 1], $tables);
1077 }
1078
1079 if (!empty($tables['civicrm_contribution_product']) && empty($tables['civicrm_product'])) {
1080 $tables['civicrm_product'] = 1;
1081 }
1082 }
1083
1084 /**
1085 * Add the where for dates.
1086 *
1087 * @param array $values
1088 * Array of query values.
1089 * @param object $query
1090 * The query object.
1091 * @param string $name
1092 * Query field that is set.
1093 * @param string $field
1094 * Name of field to be set.
1095 * @param string $title
1096 * Title of the field.
1097 *
1098 * @return bool
1099 */
1100 public static function buildDateWhere(&$values, $query, $name, $field, $title) {
1101 $fieldPart = strpos($name, $field);
1102 if ($fieldPart === FALSE) {
1103 return NULL;
1104 }
1105 // we only have recurring dates using this ATM so lets' short cut to find the table name
1106 $table = 'contribution_recur';
1107 $fieldName = explode($table . '_', $field);
1108 $query->dateQueryBuilder($values,
1109 'civicrm_' . $table, $field, $fieldName[1], $title
1110 );
1111 return TRUE;
1112 }
1113
1114 /**
1115 * Custom form rules.
1116 *
1117 * @param array $fields
1118 * @param array $files
1119 * @param CRM_Core_Form $form
1120 *
1121 * @return bool|array
1122 */
1123 public static function formRule($fields, $files, $form) {
1124 $errors = [];
1125
1126 if (!empty($fields['contribution_date_high']) && !empty($fields['contribution_date_low'])) {
1127 CRM_Utils_Rule::validDateRange($fields, 'contribution_date', $errors, ts('Date Received'));
1128 }
1129 if (!empty($fields['contribution_cancel_date_high']) && !empty($fields['contribution_cancel_date_low'])) {
1130 CRM_Utils_Rule::validDateRange($fields, 'contribution_cancel_date', $errors, ts('Cancel Date'));
1131 }
1132
1133 return empty($errors) ? TRUE : $errors;
1134 }
1135
1136 /**
1137 * Add the soft credit fields to the select fields.
1138 *
1139 * Extracted into separate function to improve readability of main select function.
1140 *
1141 * @param $query
1142 */
1143 private static function addSoftCreditFields(&$query) {
1144 $includeSoftCredits = self::isSoftCreditOptionEnabled($query->_params);
1145 if (!empty($query->_returnProperties['contribution_soft_credit_name'])) {
1146 if ($includeSoftCredits) {
1147 $query->_select['contribution_soft_credit_name'] = "civicrm_contact_d.sort_name as contribution_soft_credit_name";
1148 // also include contact id. Will help build hyperlinks
1149 $query->_select['contribution_soft_credit_contact_id'] = "civicrm_contact_d.id as contribution_soft_credit_contact_id";
1150 }
1151 $query->_element['contribution_soft_credit_name'] = 1;
1152 $query->_element['contribution_soft_credit_contact_id'] = 1;
1153
1154 $query->_tables['civicrm_contribution'] = 1;
1155 $query->_tables['civicrm_contribution_soft'] = 1;
1156 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1157 }
1158
1159 if (!empty($query->_returnProperties['contribution_soft_credit_contact_id'])) {
1160 $query->_tables['civicrm_contribution'] = 1;
1161 $query->_tables['civicrm_contribution_soft'] = 1;
1162 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1163 }
1164
1165 if (!empty($query->_returnProperties['contribution_soft_credit_amount'])) {
1166 if ($includeSoftCredits) {
1167 $query->_select['contribution_soft_credit_amount'] = "civicrm_contribution_soft.amount as contribution_soft_credit_amount";
1168 }
1169 $query->_element['contribution_soft_credit_amount'] = 1;
1170 $query->_tables['civicrm_contribution'] = 1;
1171 $query->_tables['civicrm_contribution_soft'] = 1;
1172 }
1173
1174 if (!empty($query->_returnProperties['contribution_soft_credit_type'])) {
1175 if ($includeSoftCredits) {
1176 $query->_select['contribution_soft_credit_type'] = "contribution_softcredit_type.label as contribution_soft_credit_type";
1177 }
1178 $query->_element['contribution_soft_credit_type'] = 1;
1179 $query->_tables['civicrm_contribution'] = 1;
1180 $query->_tables['contribution_softcredit_type'] = 1;
1181 }
1182
1183 if (!empty($query->_returnProperties['contribution_soft_credit_contribution_id'])) {
1184 if ($includeSoftCredits) {
1185 $query->_select['contribution_soft_credit_contribution_id'] = "civicrm_contribution_soft.contribution_id as contribution_soft_credit_contribution_id";
1186 }
1187 $query->_element['contribution_soft_credit_contribution_id'] = 1;
1188 $query->_tables['civicrm_contribution'] = 1;
1189 $query->_tables['civicrm_contribution_soft'] = 1;
1190 }
1191
1192 if (!empty($query->_returnProperties['contribution_soft_credit_email'])) {
1193 $query->_select['contribution_soft_credit_email'] = "soft_email.email as contribution_soft_credit_email";
1194 $query->_element['contribution_soft_credit_email'] = 1;
1195 $query->_tables['civicrm_contribution'] = 1;
1196 $query->_tables['civicrm_contribution_soft'] = 1;
1197 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1198 $query->_tables['civicrm_contribution_soft_email'] = 1;
1199 }
1200
1201 if (!empty($query->_returnProperties['contribution_soft_credit_phone'])) {
1202 $query->_select['contribution_soft_credit_email'] = "soft_phone.phone as contribution_soft_credit_phone";
1203 $query->_element['contribution_soft_credit_phone'] = 1;
1204 $query->_tables['civicrm_contribution'] = 1;
1205 $query->_tables['civicrm_contribution_soft'] = 1;
1206 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1207 $query->_tables['civicrm_contribution_soft_phone'] = 1;
1208 }
1209
1210 if (!empty($query->_returnProperties['contribution_soft_credit_pcp_id'])) {
1211 $query->_select['contribution_soft_credit_pcp_id'] = "civicrm_contribution_soft.pcp_id as contribution_soft_credit_pcp_id";
1212 $query->_element['contribution_soft_credit_pcp_id'] = 1;
1213 $query->_tables['civicrm_contribution'] = 1;
1214 $query->_tables['civicrm_contribution_soft'] = 1;
1215 }
1216 }
1217
1218 }