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