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