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