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