Merge pull request #6122 from marcov4lente/CRM-16789
[civicrm-core.git] / CRM / Contribute / BAO / Query.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 */
34 class CRM_Contribute_BAO_Query {
35
36 /**
37 * Static field for all the export/import contribution fields.
38 *
39 * @var array
40 */
41 static $_contributionFields = NULL;
42
43 static $_contribOrSoftCredit = "only_contribs";
44
45 /**
46 * Function get the import/export fields for contribution.
47 *
48 * @return array
49 * self::$_contributionFields associative array of contribution fields
50 */
51 public static function &getFields() {
52 if (!self::$_contributionFields) {
53 self::$_contributionFields = array();
54
55 $fields = CRM_Contribute_BAO_Contribution::exportableFields();
56
57 unset($fields['contribution_contact_id']);
58
59 self::$_contributionFields = $fields;
60 }
61 return self::$_contributionFields;
62 }
63
64 /**
65 * If contributions are involved, add the specific contribute fields.
66 *
67 * @param CRM_Contact_BAO_Query $query
68 */
69 public static function select(&$query) {
70 // if contribute mode add contribution id
71 if ($query->_mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
72 $query->_select['contribution_id'] = "civicrm_contribution.id as contribution_id";
73 $query->_element['contribution_id'] = 1;
74 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
75 }
76
77 // get financial_type
78 if (!empty($query->_returnProperties['financial_type'])) {
79 $query->_select['financial_type'] = "civicrm_financial_type.name as financial_type";
80 $query->_element['financial_type'] = 1;
81 $query->_tables['civicrm_contribution'] = 1;
82 $query->_tables['civicrm_financial_type'] = 1;
83 }
84
85 // get accounting code
86 if (!empty($query->_returnProperties['accounting_code'])) {
87 $query->_select['accounting_code'] = "civicrm_financial_account.accounting_code as accounting_code";
88 $query->_element['accounting_code'] = 1;
89 $query->_tables['civicrm_accounting_code'] = 1;
90 $query->_tables['civicrm_financial_account'] = 1;
91 }
92
93 if (!empty($query->_returnProperties['contribution_note'])) {
94 $query->_select['contribution_note'] = "civicrm_note.note as contribution_note";
95 $query->_element['contribution_note'] = 1;
96 $query->_tables['contribution_note'] = 1;
97 $query->_tables['civicrm_contribution'] = 1;
98 }
99
100 if (!empty($query->_returnProperties['contribution_batch'])) {
101 $query->_select['contribution_batch'] = "civicrm_batch.title as contribution_batch";
102 $query->_element['contribution_batch'] = 1;
103 $query->_tables['contribution_batch'] = 1;
104 }
105
106 if (!empty($query->_returnProperties['contribution_source'])) {
107 $query->_select['contribution_source'] = "civicrm_contribution.source as contribution_source";
108 $query->_element['contribution_source'] = 1;
109 $query->_tables['civicrm_contribution'] = 1;
110 }
111
112 // get contribution_status
113 if (!empty($query->_returnProperties['contribution_status_id'])) {
114 $query->_select['contribution_status_id'] = "contribution_status.value as contribution_status_id";
115 $query->_element['contribution_status_id'] = 1;
116 $query->_tables['civicrm_contribution'] = 1;
117 $query->_tables['contribution_status'] = 1;
118 }
119
120 // get contribution_status label
121 if (!empty($query->_returnProperties['contribution_status'])) {
122 $query->_select['contribution_status'] = "contribution_status.label as contribution_status";
123 $query->_element['contribution_status'] = 1;
124 $query->_tables['civicrm_contribution'] = 1;
125 $query->_tables['contribution_status'] = 1;
126 }
127
128 // get payment instrument
129 if (!empty($query->_returnProperties['payment_instrument'])) {
130 $query->_select['payment_instrument'] = "contribution_payment_instrument.label as payment_instrument";
131 $query->_element['payment_instrument'] = 1;
132 $query->_tables['civicrm_contribution'] = 1;
133 $query->_tables['contribution_payment_instrument'] = 1;
134 }
135
136 // get payment instrument id
137 if (!empty($query->_returnProperties['payment_instrument_id'])) {
138 $query->_select['instrument_id'] = "contribution_payment_instrument.value as instrument_id";
139 $query->_select['payment_instrument_id'] = "contribution_payment_instrument.value as payment_instrument_id";
140 $query->_element['instrument_id'] = $query->_element['payment_instrument_id'] = 1;
141 $query->_tables['civicrm_contribution'] = 1;
142 $query->_tables['contribution_payment_instrument'] = 1;
143 }
144
145 if (!empty($query->_returnProperties['check_number'])) {
146 $query->_select['contribution_check_number'] = "civicrm_contribution.check_number as contribution_check_number";
147 $query->_element['contribution_check_number'] = 1;
148 $query->_tables['civicrm_contribution'] = 1;
149 }
150
151 if (!empty($query->_returnProperties['contribution_campaign_id'])) {
152 $query->_select['contribution_campaign_id'] = 'civicrm_contribution.campaign_id as contribution_campaign_id';
153 $query->_element['contribution_campaign_id'] = 1;
154 $query->_tables['civicrm_contribution'] = 1;
155 }
156
157 // LCD 716
158 if (!empty($query->_returnProperties['contribution_soft_credit_name'])) {
159 $query->_select['contribution_soft_credit_name'] = "civicrm_contact_d.sort_name as contribution_soft_credit_name";
160 $query->_element['contribution_soft_credit_name'] = 1;
161
162 // also include contact id. Will help build hyperlinks
163 $query->_select['contribution_soft_credit_contact_id'] = "civicrm_contact_d.id as contribution_soft_credit_contact_id";
164 $query->_element['contribution_soft_credit_contact_id'] = 1;
165
166 $query->_tables['civicrm_contribution'] = 1;
167 $query->_tables['civicrm_contribution_soft'] = 1;
168 $query->_tables['civicrm_contribution_soft_contact'] = 1;
169 }
170
171 if (!empty($query->_returnProperties['contribution_soft_credit_contact_id'])) {
172 $query->_tables['civicrm_contribution'] = 1;
173 $query->_tables['civicrm_contribution_soft'] = 1;
174 }
175
176 if (!empty($query->_returnProperties['contribution_soft_credit_amount'])) {
177 $query->_select['contribution_soft_credit_amount'] = "civicrm_contribution_soft.amount as contribution_soft_credit_amount";
178 $query->_element['contribution_soft_credit_amount'] = 1;
179 $query->_tables['civicrm_contribution'] = 1;
180 $query->_tables['civicrm_contribution_soft'] = 1;
181 }
182
183 if (!empty($query->_returnProperties['contribution_soft_credit_type'])) {
184 $query->_select['contribution_soft_credit_type'] = "contribution_softcredit_type.label as contribution_soft_credit_type";
185 $query->_element['contribution_soft_credit_type'] = 1;
186 $query->_tables['civicrm_contribution'] = 1;
187 $query->_tables['contribution_softcredit_type'] = 1;
188 }
189
190 if (!empty($query->_returnProperties['contribution_soft_credit_contribution_id'])) {
191 $query->_select['contribution_soft_credit_contribution_id'] = "civicrm_contribution_soft.contribution_id as contribution_soft_credit_contribution_id";
192 $query->_element['contribution_soft_credit_contribution_id'] = 1;
193 $query->_tables['civicrm_contribution'] = 1;
194 $query->_tables['civicrm_contribution_soft'] = 1;
195 }
196
197 if (!empty($query->_returnProperties['contribution_soft_credit_email'])) {
198 $query->_select['contribution_soft_credit_email'] = "soft_email.email as contribution_soft_credit_email";
199 $query->_element['contribution_soft_credit_email'] = 1;
200 $query->_tables['civicrm_contribution'] = 1;
201 $query->_tables['civicrm_contribution_soft'] = 1;
202 $query->_tables['civicrm_contribution_soft_contact'] = 1;
203 $query->_tables['civicrm_contribution_soft_email'] = 1;
204 }
205
206 if (!empty($query->_returnProperties['contribution_soft_credit_phone'])) {
207 $query->_select['contribution_soft_credit_email'] = "soft_phone.phone as contribution_soft_credit_phone";
208 $query->_element['contribution_soft_credit_phone'] = 1;
209 $query->_tables['civicrm_contribution'] = 1;
210 $query->_tables['civicrm_contribution_soft'] = 1;
211 $query->_tables['civicrm_contribution_soft_contact'] = 1;
212 $query->_tables['civicrm_contribution_soft_phone'] = 1;
213 }
214 if (!empty($query->_returnProperties['contribution_campaign_title'])) {
215 $query->_select['contribution_campaign_title'] = "civicrm_campaign.title as contribution_campaign_title";
216 $query->_element['contribution_campaign_title'] = $query->_tables['civicrm_campaign'] = 1;
217 }
218 // LCD 716 END
219 }
220
221 /**
222 * Get where clause.
223 *
224 * @param CRM_Contact_BAO_Query $query
225 */
226 public static function where(&$query) {
227 $grouping = NULL;
228 self::initializeAnySoftCreditClause($query);
229 foreach (array_keys($query->_params) as $id) {
230 if (empty($query->_params[$id][0])) {
231 continue;
232 }
233 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_') {
234 if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
235 $query->_useDistinct = TRUE;
236 }
237 // CRM-12065
238 if (
239 $query->_params[$id][0] == 'contribution_type_id' ||
240 $query->_params[$id][0] == 'contribution_type'
241 ) {
242 CRM_Core_Session::setStatus(
243 ts('The contribution type criteria is now obsolete, please update your smart group'),
244 '',
245 'alert'
246 );
247 continue;
248 }
249
250 $grouping = $query->_params[$id][3];
251 self::whereClauseSingle($query->_params[$id], $query);
252 }
253 }
254 }
255
256 /**
257 * Get where clause for a single value.
258 *
259 * @param array $values
260 * @param CRM_Contact_BAO_Query $query
261 */
262 public static function whereClauseSingle(&$values, &$query) {
263 list($name, $op, $value, $grouping, $wildcard) = $values;
264
265 $quoteValue = NULL;
266 $fields = array_merge(CRM_Contribute_BAO_Contribution::fields(), self::getFields());
267
268 if (!empty($value) && !is_array($value)) {
269 $quoteValue = "\"$value\"";
270 }
271
272 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
273 foreach (self::getRecurringFields() as $dateField => $dateFieldTitle) {
274 if (self::buildDateWhere($values, $query, $name, $dateField, $dateFieldTitle)) {
275 return;
276 }
277 }
278 switch ($name) {
279 case 'contribution_date':
280 case 'contribution_date_low':
281 case 'contribution_date_low_time':
282 case 'contribution_date_high':
283 case 'contribution_date_high_time':
284 // process to / from date
285 $query->dateQueryBuilder($values,
286 'civicrm_contribution', 'contribution_date', 'receive_date', 'Contribution Date'
287 );
288 return;
289
290 case 'contribution_amount':
291 case 'contribution_amount_low':
292 case 'contribution_amount_high':
293 // process min/max amount
294 $query->numberRangeBuilder($values,
295 'civicrm_contribution', 'contribution_amount',
296 'total_amount', 'Contribution Amount',
297 NULL
298 );
299 return;
300
301 case 'contribution_thankyou_date_is_not_null':
302 if ($value) {
303 $op = "IS NOT NULL";
304 $query->_qill[$grouping][] = ts('Contribution Thank-you Sent');
305 }
306 else {
307 $op = "IS NULL";
308 $query->_qill[$grouping][] = ts('Contribution Thank-you Not Sent');
309 }
310 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.thankyou_date", $op);
311 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
312 return;
313
314 case 'contribution_receipt_date_is_not_null':
315 if ($value) {
316 $op = "IS NOT NULL";
317 $query->_qill[$grouping][] = ts('Contribution Receipt Sent');
318 }
319 else {
320 $op = "IS NULL";
321 $query->_qill[$grouping][] = ts('Contribution Receipt Not Sent');
322 }
323 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.receipt_date", $op);
324 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
325 return;
326
327 case 'financial_type':
328 case 'contribution_page':
329 case 'payment_instrument':
330 case 'contribution_payment_instrument':
331 case 'contribution_status':
332 $name .= '_id';
333 case 'financial_type_id':
334 case 'invoice_id':
335 case 'payment_instrument_id':
336 case 'contribution_payment_instrument_id':
337 case 'contribution_page_id':
338 case 'contribution_status_id':
339 case 'contribution_id':
340 case 'contribution_currency_type':
341 case 'contribution_currency':
342 case 'contribution_source':
343 case 'contribution_trxn_id':
344 case 'contribution_check_number':
345 case 'contribution_contact_id':
346 case (strpos($name, '_amount') !== FALSE):
347 case (strpos($name, '_date') !== FALSE && $name != 'contribution_fulfilled_date'):
348 $qillName = $name;
349 $pseudoExtraParam = NULL;
350 // @todo including names using a switch statement & then using an 'if' to filter them out is ... odd!
351 if ((strpos($name, '_amount') !== FALSE) || (strpos($name, '_date') !== FALSE) || in_array($name,
352 array(
353 'contribution_id',
354 'contribution_currency',
355 'contribution_source',
356 'contribution_trxn_id',
357 'contribution_check_number',
358 'contribution_payment_instrument_id',
359 'contribution_contact_id',
360 )
361 )
362 ) {
363 $name = str_replace('contribution_', '', $name);
364 if (!in_array($name, array('source', 'id', 'contact_id'))) {
365 $qillName = str_replace('contribution_', '', $qillName);
366 }
367 }
368 if (in_array($name, array('contribution_currency', 'contribution_currency_type'))) {
369 $qillName = $name = 'currency';
370 $pseudoExtraParam = array('labelColumn' => 'name');
371 }
372
373 $dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
374
375 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.$name", $op, $value, $dataType);
376 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_Contribution', $name, $value, $op, $pseudoExtraParam);
377 $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
378 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
379 return;
380
381 case 'contribution_pcp_made_through_id':
382 case 'contribution_soft_credit_type_id':
383 $qillName = $name;
384 if ($name == 'contribution_pcp_made_through_id') {
385 $qillName = $name = 'pcp_id';
386 $fields[$name] = array('title' => ts('Personal Campaign Page'), 'type' => 2);
387 }
388 if ($name == 'contribution_soft_credit_type_id') {
389 $qillName = str_replace('_id', '', $qillName);
390 $fields[$qillName]['type'] = $fields[$qillName]['data_type'];
391 $name = str_replace('contribution_', '', $name);
392 }
393 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_soft.$name",
394 $op, $value, CRM_Utils_Type::typeToString($fields[$qillName]['type'])
395 );
396 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_ContributionSoft', $name, $value, $op);
397 $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
398 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
399 return;
400
401 case 'contribution_or_softcredits':
402 if ($value == 'only_scredits') {
403 $query->_where[$grouping][] = "contribution_search_scredit_combined.scredit_id IS NOT NULL";
404 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits Only');
405 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
406 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
407 }
408 elseif ($value == 'both_related') {
409 $query->_where[$grouping][] = "contribution_search_scredit_combined.filter_id IS NOT NULL";
410 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits with related Hard Credit');
411 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
412 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
413 }
414 elseif ($value == 'both') {
415 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Both');
416 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
417 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
418 }
419 // default option: $value == 'only_contribs'
420 return;
421
422 case 'contribution_is_test':
423 // By default is Contribution Search form we choose is_test = 0 in otherwords always show active contribution
424 // so in case if any one choose any Yes/No avoid the default clause otherwise it will be conflict in whereClause
425 $key = array_search('civicrm_contribution.is_test = 0', $query->_where[$grouping]);
426 if (!empty($key)) {
427 unset($query->_where[$grouping][$key]);
428 }
429 case 'contribution_test':
430 // We dont want to include all tests for sql OR CRM-7827
431 if (!$value || $query->getOperator() != 'OR') {
432 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.is_test", $op, $value, "Boolean");
433 if ($value) {
434 $query->_qill[$grouping][] = ts("Only Display Test Contributions");
435 }
436 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
437 }
438 return;
439
440 case 'contribution_is_pay_later':
441 case 'contribution_pay_later':
442 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.is_pay_later", $op, $value, "Boolean");
443 if ($value) {
444 $query->_qill[$grouping][] = ts("Find Pay Later Contributions");
445 }
446 else {
447 $query->_qill[$grouping][] = ts("Exclude Pay Later Contributions");
448 }
449 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
450 return;
451
452 case 'contribution_recurring':
453 if ($value) {
454 $query->_where[$grouping][] = "civicrm_contribution.contribution_recur_id IS NOT NULL";
455 $query->_qill[$grouping][] = ts("Find Recurring Contributions");
456 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
457 }
458 else {
459 $query->_where[$grouping][] = "civicrm_contribution.contribution_recur_id IS NULL";
460 $query->_qill[$grouping][] = ts("Exclude Recurring Contributions");
461 }
462 return;
463
464 case 'contribution_recur_id':
465 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.contribution_recur_id",
466 $op, $value, "Integer"
467 );
468 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
469 return;
470
471 case 'contribution_note':
472 $value = $strtolower(CRM_Core_DAO::escapeString($value));
473 if ($wildcard) {
474 $value = "%$value%";
475 $op = 'LIKE';
476 }
477 $wc = ($op != 'LIKE') ? "LOWER(civicrm_note.note)" : "civicrm_note.note";
478 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($wc, $op, $value, "String");
479 $query->_qill[$grouping][] = ts('Contribution Note %1 %2', array(1 => $op, 2 => $quoteValue));
480 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = $query->_whereTables['contribution_note'] = 1;
481 return;
482
483 case 'contribution_membership_id':
484 $query->_where[$grouping][] = " civicrm_membership.id $op $value";
485 $query->_tables['contribution_membership'] = $query->_whereTables['contribution_membership'] = 1;
486
487 return;
488
489 case 'contribution_participant_id':
490 $query->_where[$grouping][] = " civicrm_participant.id $op $value";
491 $query->_tables['contribution_participant'] = $query->_whereTables['contribution_participant'] = 1;
492 return;
493
494 case 'contribution_pcp_display_in_roll':
495 $query->_where[$grouping][] = " civicrm_contribution_soft.pcp_display_in_roll $op '$value'";
496 if ($value) {
497 $query->_qill[$grouping][] = ts("Personal Campaign Page Honor Roll");
498 }
499 else {
500 $query->_qill[$grouping][] = ts("NOT Personal Campaign Page Honor Roll");
501 }
502 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
503 return;
504
505 case 'contribution_campaign_id':
506 $campParams = array(
507 'op' => $op,
508 'campaign' => $value,
509 'grouping' => $grouping,
510 'tableName' => 'civicrm_contribution',
511 );
512 CRM_Campaign_BAO_Query::componentSearchClause($campParams, $query);
513 return;
514
515 case 'contribution_batch_id':
516 $batches = CRM_Contribute_PseudoConstant::batch();
517 $query->_where[$grouping][] = " civicrm_entity_batch.batch_id $op $value";
518 $query->_qill[$grouping][] = ts('Batch Name %1 %2', array(1 => $op, 2 => $batches[$value]));
519 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
520 $query->_tables['contribution_batch'] = $query->_whereTables['contribution_batch'] = 1;
521 return;
522
523 default:
524 //all other elements are handle in this case
525 $fldName = substr($name, 13);
526 if (!isset($fields[$fldName])) {
527 // CRM-12597
528 CRM_Core_Session::setStatus(ts(
529 'We did not recognize the search field: %1. Please check and fix your contribution related smart groups.',
530 array(1 => $fldName)
531 )
532 );
533 return;
534 }
535 $whereTable = $fields[$fldName];
536 $value = trim($value);
537
538 $dataType = "String";
539 if (!empty($whereTable['type'])) {
540 $dataType = CRM_Utils_Type::typeToString($whereTable['type']);
541 }
542
543 $wc = ($op != 'LIKE' && $dataType != 'Date') ? "LOWER($whereTable[where])" : "$whereTable[where]";
544 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($wc, $op, $value, $dataType);
545 $query->_qill[$grouping][] = "$whereTable[title] $op $quoteValue";
546 list($tableName, $fieldName) = explode('.', $whereTable['where'], 2);
547 $query->_tables[$tableName] = $query->_whereTables[$tableName] = 1;
548 if ($tableName == 'civicrm_contribution_product') {
549 $query->_tables['civicrm_product'] = $query->_whereTables['civicrm_product'] = 1;
550 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
551 }
552 else {
553 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
554 }
555 }
556 }
557
558 /**
559 * Get from clause.
560 *
561 * @param string $name
562 * @param string $mode
563 * @param string $side
564 *
565 * @return NULL|string
566 */
567 public static function from($name, $mode, $side) {
568 $from = NULL;
569 switch ($name) {
570 case 'civicrm_contribution':
571 $from = " $side JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id ";
572 if (in_array(self::$_contribOrSoftCredit, array("only_scredits", "both_related", "both"))) {
573 // switch the from table if its only soft credit search
574 $from = " $side JOIN contribution_search_scredit_combined ON contribution_search_scredit_combined.contact_id = contact_a.id ";
575 $from .= " $side JOIN civicrm_contribution ON civicrm_contribution.id = contribution_search_scredit_combined.id ";
576 $from .= " $side JOIN civicrm_contribution_soft ON civicrm_contribution_soft.id = contribution_search_scredit_combined.scredit_id";
577 }
578 break;
579
580 case 'civicrm_contribution_recur':
581 if ($mode == 1) {
582 // in contact mode join directly onto profile - in case no contributions exist yet
583 $from = " $side JOIN civicrm_contribution_recur ON contact_a.id = civicrm_contribution_recur.contact_id ";
584 }
585 else {
586 $from = " $side JOIN civicrm_contribution_recur ON civicrm_contribution.contribution_recur_id = civicrm_contribution_recur.id ";
587 }
588 break;
589
590 case 'civicrm_financial_type':
591 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
592 $from = " INNER JOIN civicrm_financial_type ON civicrm_contribution.financial_type_id = civicrm_financial_type.id ";
593 }
594 else {
595 $from = " $side JOIN civicrm_financial_type ON civicrm_contribution.financial_type_id = civicrm_financial_type.id ";
596 }
597 break;
598
599 case 'civicrm_financial_account':
600 if ($mode & CRM_Contact_BAO_Query::MODE_CONTACTS) {
601 $from = " $side JOIN civicrm_financial_account ON contact_a.id = civicrm_financial_account.contact_id ";
602 }
603 break;
604
605 case 'civicrm_accounting_code':
606 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
607 $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' ";
608 $from .= " INNER JOIN civicrm_financial_account ON civicrm_financial_account.id = civicrm_entity_financial_account.financial_account_id ";
609 $from .= " INNER JOIN civicrm_option_value cov ON cov.value = civicrm_entity_financial_account.account_relationship AND cov.name = 'Income Account is' ";
610 $from .= " INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id AND cog.name = 'account_relationship' ";
611 }
612 break;
613
614 case 'civicrm_contribution_page':
615 $from = " $side JOIN civicrm_contribution_page ON civicrm_contribution.contribution_page_id = civicrm_contribution_page.id";
616 break;
617
618 case 'civicrm_product':
619 $from = " $side JOIN civicrm_contribution_product ON civicrm_contribution_product.contribution_id = civicrm_contribution.id";
620 $from .= " $side JOIN civicrm_product ON civicrm_contribution_product.product_id =civicrm_product.id ";
621 break;
622
623 case 'contribution_payment_instrument':
624 $from = " $side JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')";
625 $from .= " $side JOIN civicrm_option_value contribution_payment_instrument ON (civicrm_contribution.payment_instrument_id = contribution_payment_instrument.value
626 AND option_group_payment_instrument.id = contribution_payment_instrument.option_group_id ) ";
627 break;
628
629 case 'contribution_status':
630 $from = " $side JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')";
631 $from .= " $side JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
632 AND option_group_contribution_status.id = contribution_status.option_group_id ) ";
633 break;
634
635 case 'contribution_softcredit_type':
636 $from = " $side JOIN civicrm_option_group option_group_contribution_softcredit_type ON
637 (option_group_contribution_softcredit_type.name = 'soft_credit_type')";
638 $from .= " $side JOIN civicrm_option_value contribution_softcredit_type ON
639 ( civicrm_contribution_soft.soft_credit_type_id = contribution_softcredit_type.value
640 AND option_group_contribution_softcredit_type.id = contribution_softcredit_type.option_group_id )";
641 break;
642
643 case 'contribution_note':
644 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contribution' AND
645 civicrm_contribution.id = civicrm_note.entity_id )";
646 break;
647
648 case 'contribution_membership':
649 $from = " $side JOIN civicrm_membership_payment ON civicrm_membership_payment.contribution_id = civicrm_contribution.id";
650 $from .= " $side JOIN civicrm_membership ON civicrm_membership_payment.membership_id = civicrm_membership.id ";
651 break;
652
653 case 'civicrm_campaign':
654 //CRM-16764 - get survey clause from campaign bao
655 if (!CRM_Campaign_BAO_Query::$_applySurveyClause) {
656 $from = " $side JOIN civicrm_campaign ON civicrm_campaign.id = civicrm_contribution.campaign_id";
657 }
658 break;
659
660 case 'contribution_participant':
661 $from = " $side JOIN civicrm_participant_payment ON civicrm_participant_payment.contribution_id = civicrm_contribution.id";
662 $from .= " $side JOIN civicrm_participant ON civicrm_participant_payment.participant_id = civicrm_participant.id ";
663 break;
664
665 case 'civicrm_contribution_soft':
666 if (!in_array(self::$_contribOrSoftCredit, array("only_scredits", "both_related", "both"))) {
667 $from = " $side JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id";
668 }
669 break;
670
671 case 'civicrm_contribution_soft_contact':
672 if (in_array(self::$_contribOrSoftCredit, array("only_scredits", "both_related", "both"))) {
673 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution.contact_id = civicrm_contact_d.id )
674 AND contribution_search_scredit_combined.scredit_id IS NOT NULL";
675 }
676 else {
677 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution_soft.contact_id = civicrm_contact_d.id )";
678 }
679 break;
680
681 case 'civicrm_contribution_soft_email':
682 $from .= " $side JOIN civicrm_email as soft_email ON (civicrm_contact_d.id = soft_email.contact_id )";
683 break;
684
685 case 'civicrm_contribution_soft_phone':
686 $from .= " $side JOIN civicrm_phone as soft_phone ON (civicrm_contact_d.id = soft_phone.contact_id )";
687 break;
688
689 case 'contribution_batch':
690 $from .= " $side JOIN civicrm_entity_financial_trxn ON (
691 civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution'
692 AND civicrm_contribution.id = civicrm_entity_financial_trxn.entity_id )";
693
694 $from .= " $side JOIN civicrm_financial_trxn ON (
695 civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id )";
696
697 $from .= " $side JOIN civicrm_entity_batch ON ( civicrm_entity_batch.entity_table = 'civicrm_financial_trxn'
698 AND civicrm_financial_trxn.id = civicrm_entity_batch.entity_id )";
699
700 $from .= " $side JOIN civicrm_batch ON civicrm_entity_batch.batch_id = civicrm_batch.id";
701 break;
702 }
703 return $from;
704 }
705
706 /**
707 * Initialise the soft credit clause.
708 *
709 * @param CRM_Contact_BAO_Query $query
710 */
711 public static function initializeAnySoftCreditClause(&$query) {
712 if (self::isSoftCreditOptionEnabled($query->_params)) {
713 if ($query->_mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
714 unset($query->_distinctComponentClause);
715 $query->_rowCountClause = " count(civicrm_contribution.id)";
716 $query->_groupByComponentClause = " GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.contact_id, contribution_search_scredit_combined.scredit_id ";
717 }
718 }
719 }
720
721 /**
722 * Check if soft credits are enables.
723 *
724 * @param array $queryParams
725 *
726 * @return bool
727 */
728 public static function isSoftCreditOptionEnabled($queryParams = array()) {
729 static $tempTableFilled = FALSE;
730 if (!empty($queryParams)) {
731 foreach (array_keys($queryParams) as $id) {
732 if (empty($queryParams[$id][0])) {
733 continue;
734 }
735 if ($queryParams[$id][0] == 'contribution_or_softcredits') {
736 self::$_contribOrSoftCredit = $queryParams[$id][2];
737 }
738 }
739 }
740 if (in_array(self::$_contribOrSoftCredit,
741 array("only_scredits", "both_related", "both"))) {
742 if (!$tempTableFilled) {
743 // build a temp table which is union of contributions and soft credits
744 // note: group-by in first part ensures uniqueness in counts
745 $tempQuery = "
746 CREATE TEMPORARY TABLE IF NOT EXISTS contribution_search_scredit_combined AS
747 SELECT con.id as id, con.contact_id, cso.id as filter_id, NULL as scredit_id
748 FROM civicrm_contribution con
749 LEFT JOIN civicrm_contribution_soft cso ON con.id = cso.contribution_id
750 GROUP BY id, contact_id, scredit_id
751 UNION ALL
752 SELECT scredit.contribution_id as id, scredit.contact_id, scredit.id as filter_id, scredit.id as scredit_id
753 FROM civicrm_contribution_soft as scredit";
754 CRM_Core_DAO::executeQuery($tempQuery);
755 $tempTableFilled = TRUE;
756 }
757 return TRUE;
758 }
759 return FALSE;
760 }
761
762 /**
763 * Get return properties for soft credits.
764 *
765 * @param bool $isExportMode
766 *
767 * @return array
768 */
769 public static function softCreditReturnProperties($isExportMode = FALSE) {
770 $properties = array(
771 'contribution_soft_credit_name' => 1,
772 'contribution_soft_credit_amount' => 1,
773 'contribution_soft_credit_type' => 1,
774 );
775 if ($isExportMode) {
776 $properties['contribution_soft_credit_contribution_id'] = 1;
777 }
778 return $properties;
779 }
780
781 /**
782 * @param $mode
783 * @param bool $includeCustomFields
784 *
785 * @return array|NULL
786 */
787 public static function defaultReturnProperties($mode, $includeCustomFields = TRUE) {
788 $properties = NULL;
789 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
790 $properties = array(
791 'contact_type' => 1,
792 'contact_sub_type' => 1,
793 'sort_name' => 1,
794 'display_name' => 1,
795 'financial_type' => 1,
796 'contribution_source' => 1,
797 'receive_date' => 1,
798 'thankyou_date' => 1,
799 'cancel_date' => 1,
800 'total_amount' => 1,
801 'accounting_code' => 1,
802 'payment_instrument' => 1,
803 'payment_instrument_id' => 1,
804 'check_number' => 1,
805 'non_deductible_amount' => 1,
806 'fee_amount' => 1,
807 'net_amount' => 1,
808 'trxn_id' => 1,
809 'invoice_id' => 1,
810 'currency' => 1,
811 'cancel_reason' => 1,
812 'receipt_date' => 1,
813 'product_name' => 1,
814 'sku' => 1,
815 'product_option' => 1,
816 'fulfilled_date' => 1,
817 'contribution_start_date' => 1,
818 'contribution_end_date' => 1,
819 'is_test' => 1,
820 'is_pay_later' => 1,
821 'contribution_status' => 1,
822 'contribution_status_id' => 1,
823 'contribution_recur_id' => 1,
824 'amount_level' => 1,
825 'contribution_note' => 1,
826 'contribution_batch' => 1,
827 'contribution_campaign_title' => 1,
828 'contribution_campaign_id' => 1,
829 );
830 if (self::isSoftCreditOptionEnabled()) {
831 $properties = array_merge($properties, self::softCreditReturnProperties());
832 }
833 if ($includeCustomFields) {
834 // also get all the custom contribution properties
835 $fields = CRM_Core_BAO_CustomField::getFieldsForImport('Contribution');
836 if (!empty($fields)) {
837 foreach ($fields as $name => $dontCare) {
838 $properties[$name] = 1;
839 }
840 }
841 }
842 }
843 return $properties;
844 }
845
846 /**
847 * Add all the elements shared between contribute search and advnaced search.
848 *
849 *
850 * @param CRM_Core_Form $form
851 *
852 * @return void
853 */
854 public static function buildSearchForm(&$form) {
855
856 // Added contribution source
857 $form->addElement('text', 'contribution_source', ts('Contribution Source'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'source'));
858
859 CRM_Core_Form_Date::buildDateRange($form, 'contribution_date', 1, '_low', '_high', ts('From:'), FALSE);
860
861 $form->add('text', 'contribution_amount_low', ts('From'), array('size' => 8, 'maxlength' => 8));
862 $form->addRule('contribution_amount_low', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money');
863
864 $form->add('text', 'contribution_amount_high', ts('To'), array('size' => 8, 'maxlength' => 8));
865 $form->addRule('contribution_amount_high', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
866
867 // Adding select option for curreny type -- CRM-4711
868 $form->add('select', 'contribution_currency_type',
869 ts('Currency Type'),
870 array(
871 '' => ts('- any -'),
872 ) +
873 CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', array('labelColumn' => 'name')),
874 FALSE, array('class' => 'crm-select2')
875 );
876
877 // CRM-13848
878 $form->addSelect('financial_type_id',
879 array('entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search')
880 );
881
882 $form->add('select', 'contribution_page_id',
883 ts('Contribution Page'),
884 array(
885 '' => ts('- any -'),
886 ) +
887 CRM_Contribute_PseudoConstant::contributionPage(),
888 FALSE, array('class' => 'crm-select2')
889 );
890
891 $form->addSelect('payment_instrument_id',
892 array('entity' => 'contribution', 'label' => ts('Payment Method'), 'option_url' => NULL, 'placeholder' => ts('- any -'))
893 );
894
895 // Fixme: Not a true entityRef field. Relies on PCP.js.tpl
896 $form->add('text', 'contribution_pcp_made_through_id', ts('Personal Campaign Page'), array('class' => 'twenty', 'id' => 'pcp_made_through_id', 'placeholder' => ts('- any -')));
897 // stores the label
898 $form->add('hidden', 'pcp_made_through');
899
900 $statusValues = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status');
901 // Remove status values that are only used for recurring contributions or pledges (In Progress, Overdue).
902 unset($statusValues['5'], $statusValues['6']);
903
904 $form->addSelect('contribution_status_id',
905 array('entity' => 'contribution', 'multiple' => 'multiple', 'label' => ts('Contribution Status(s)'), 'option_url' => NULL, 'placeholder' => ts('- any -'))
906 );
907
908 // Add fields for thank you and receipt
909 $form->addYesNo('contribution_thankyou_date_is_not_null', ts('Thank-you sent?'), TRUE);
910 $form->addYesNo('contribution_receipt_date_is_not_null', ts('Receipt sent?'), TRUE);
911
912 $form->addYesNo('contribution_pay_later', ts('Contribution is Pay Later?'), TRUE);
913 $form->addYesNo('contribution_recurring', ts('Contribution is Recurring?'), TRUE);
914
915 // Recurring contribution fields
916 foreach (self::getRecurringFields() as $key => $label) {
917 CRM_Core_Form_Date::buildDateRange($form, $key, 1, '_low', '_high');
918 // If data has been entered for a recurring field, tell the tpl layer to open the pane
919 if (!empty($form->_formValues[$key . '_relative']) || !empty($form->_formValues[$key . '_low']) || !empty($form->_formValues[$key . '_high'])) {
920 $form->assign('contribution_recur_pane_open', TRUE);
921 }
922 }
923
924 $form->addYesNo('contribution_test', ts('Contribution is a Test?'), TRUE);
925
926 // Add field for transaction ID search
927 $form->addElement('text', 'contribution_trxn_id', ts("Transaction ID"));
928 $form->addElement('text', 'invoice_id', ts("Invoice ID"));
929 $form->addElement('text', 'contribution_check_number', ts('Check Number'));
930
931 // Add field for pcp display in roll search
932 $form->addYesNo('contribution_pcp_display_in_roll', ts('Personal Campaign Page Honor Roll?'), TRUE);
933
934 // Soft credit related fields
935 $options = array(
936 'only_contribs' => ts('Contributions Only'),
937 'only_scredits' => ts('Soft Credits Only'),
938 'both_related' => ts('Soft Credits with related Hard Credit'),
939 'both' => ts('Both'),
940 );
941 $form->add('select', 'contribution_or_softcredits', ts('Contributions OR Soft Credits?'), $options, FALSE, array('class' => "crm-select2"));
942 $form->addSelect(
943 'contribution_soft_credit_type_id',
944 array(
945 'entity' => 'contribution_soft',
946 'field' => 'soft_credit_type_id',
947 'multiple' => TRUE,
948 'context' => 'search',
949 )
950 );
951
952 // Add all the custom searchable fields
953 $contribution = array('Contribution');
954 $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $contribution);
955 if ($groupDetails) {
956 $form->assign('contributeGroupTree', $groupDetails);
957 foreach ($groupDetails as $group) {
958 foreach ($group['fields'] as $field) {
959 $fieldId = $field['id'];
960 $elementName = 'custom_' . $fieldId;
961 CRM_Core_BAO_CustomField::addQuickFormElement($form,
962 $elementName,
963 $fieldId,
964 FALSE, FALSE, TRUE
965 );
966 }
967 }
968 }
969
970 CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'contribution_campaign_id');
971
972 // Add batch select
973 $batches = CRM_Contribute_PseudoConstant::batch();
974
975 if (!empty($batches)) {
976 $form->add('select', 'contribution_batch_id',
977 ts('Batch Name'),
978 array('' => ts('- any -')) + $batches,
979 FALSE, array('class' => 'crm-select2')
980 );
981 }
982
983 $form->assign('validCiviContribute', TRUE);
984 $form->setDefaults(array('contribution_test' => 0));
985 }
986
987 /**
988 * Function that may not be needed.
989 *
990 * @param array $row
991 * @param int $id
992 */
993 public static function searchAction(&$row, $id) {
994 }
995
996 /**
997 * Get table names.
998 *
999 * @todo better function comment needed - what IS the point of this?
1000 *
1001 * @param array $tables
1002 */
1003 public static function tableNames(&$tables) {
1004 // Add contribution table
1005 if (!empty($tables['civicrm_product'])) {
1006 $tables = array_merge(array('civicrm_contribution' => 1), $tables);
1007 }
1008
1009 if (!empty($tables['civicrm_contribution_product']) && empty($tables['civicrm_product'])) {
1010 $tables['civicrm_product'] = 1;
1011 }
1012 }
1013
1014 /**
1015 * Add the where for dates.
1016 *
1017 * @param array $values
1018 * Array of query values.
1019 * @param object $query
1020 * The query object.
1021 * @param string $name
1022 * Query field that is set.
1023 * @param string $field
1024 * Name of field to be set.
1025 * @param string $title
1026 * Title of the field.
1027 *
1028 * @return bool
1029 */
1030 public static function buildDateWhere(&$values, $query, $name, $field, $title) {
1031 $fieldPart = strpos($name, $field);
1032 if ($fieldPart === FALSE) {
1033 return NULL;
1034 }
1035 // we only have recurring dates using this ATM so lets' short cut to find the table name
1036 $table = 'contribution_recur';
1037 $fieldName = explode($table . '_', $field);
1038 $query->dateQueryBuilder($values,
1039 'civicrm_' . $table, $field, $fieldName[1], $title
1040 );
1041 return TRUE;
1042 }
1043
1044 /**
1045 * Get fields for recurring contributions.
1046 *
1047 * @return array
1048 */
1049 public static function getRecurringFields() {
1050 return array(
1051 'contribution_recur_start_date' => ts('Recurring Contribution Start Date'),
1052 'contribution_recur_next_sched_contribution_date' => ts('Next Scheduled Recurring Contribution'),
1053 'contribution_recur_cancel_date' => ts('Recurring Contribution Cancel Date'),
1054 'contribution_recur_end_date' => ts('Recurring Contribution End Date'),
1055 'contribution_recur_create_date' => ('Recurring Contribution Create Date'),
1056 'contribution_recur_modified_date' => ('Recurring Contribution Modified Date'),
1057 'contribution_recur_failure_retry_date' => ts('Failed Recurring Contribution Retry Date'),
1058 );
1059 }
1060
1061 }